diff --git a/Dockerfile b/Dockerfile index 7b25ff2e2f9..11a5ebcf5b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -97,7 +97,13 @@ ENV NPM_CONFIG_AUDIT=false \ NPM_CONFIG_FETCH_RETRY_MINTIMEOUT=20000 \ NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT=120000 \ NPM_CONFIG_FETCH_TIMEOUT=300000 -RUN npm ci --omit=dev +RUN npm ci --omit=dev \ + && test -f /usr/local/bin/node \ + && test -d /opt/nemoclaw/node_modules/json5 \ + && node_unsafe="$(find -L /usr/local/bin/node -maxdepth 0 \( ! -user root -o -perm /022 \) -print -quit)" \ + && test -z "$node_unsafe" \ + && json5_unsafe="$(find -L /opt/nemoclaw/node_modules/json5 \( ! -user root -o -perm /022 \) -print -quit)" \ + && test -z "$json5_unsafe" COPY scripts/patch-openclaw-tool-catalog.js /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.js COPY scripts/patch-openclaw-chat-send.js /usr/local/lib/nemoclaw/patch-openclaw-chat-send.js RUN chmod 755 /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.js \ @@ -529,10 +535,15 @@ 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/gateway-supervisor.sh /usr/local/lib/nemoclaw/gateway-supervisor.sh COPY scripts/lib/sandbox-rlimits.sh /usr/local/lib/nemoclaw/sandbox-rlimits.sh COPY scripts/lib/openclaw_device_approval_policy.py /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py COPY scripts/lib/clean_runtime_shell_env_shim.py /usr/local/lib/nemoclaw/clean_runtime_shell_env_shim.py +COPY scripts/state-dir-guard.py /usr/local/lib/nemoclaw/state-dir-guard.py +COPY scripts/openclaw-config-guard.py /usr/local/lib/nemoclaw/openclaw-config-guard.py +COPY scripts/managed-gateway-control.py /usr/local/lib/nemoclaw/managed-gateway-control.py COPY scripts/nemoclaw-start.sh /usr/local/bin/nemoclaw-start +COPY scripts/gateway-control.sh /usr/local/bin/nemoclaw-gateway-control # 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 # needs to read these files to install Node runtime preloads under /tmp. @@ -549,7 +560,17 @@ RUN chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-codex-acp \ /scripts/generate-openclaw-config.mts \ /src/lib/messaging/applier/build/messaging-build-applier.mts \ && chmod -R a+rX /src/lib/messaging \ - && chmod 444 /usr/local/lib/nemoclaw/sandbox-rlimits.sh \ + && chown root:root /usr/local/bin/nemoclaw-gateway-control \ + /usr/local/lib/nemoclaw/gateway-supervisor.sh \ + /usr/local/lib/nemoclaw/state-dir-guard.py \ + /usr/local/lib/nemoclaw/openclaw-config-guard.py \ + /usr/local/lib/nemoclaw/managed-gateway-control.py \ + && chmod 700 /usr/local/bin/nemoclaw-gateway-control \ + && chmod 500 /usr/local/lib/nemoclaw/state-dir-guard.py \ + /usr/local/lib/nemoclaw/openclaw-config-guard.py \ + /usr/local/lib/nemoclaw/managed-gateway-control.py \ + && chmod 444 /usr/local/lib/nemoclaw/gateway-supervisor.sh \ + /usr/local/lib/nemoclaw/sandbox-rlimits.sh \ && chmod 644 /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py \ /usr/local/lib/nemoclaw/clean_runtime_shell_env_shim.py \ && if [ -d /usr/local/lib/nemoclaw/preloads-compiled-channels ]; then \ @@ -907,15 +928,24 @@ RUN set -eu; \ done; \ rm -rf /root/.npm /sandbox/.npm -# Stale-base fallback for the gateway-in-sandbox-group setup (#2681). -# Newer base images already add the gateway user to the sandbox group, but -# the derived image must remain build-clean against older sandbox-base:latest -# tags too. The `id -nG` check makes this idempotent. +# Stale-base fallback for the gateway/root-in-sandbox-group setup (#2681). +# Newer base images already add both users to the sandbox group, but the +# derived image must remain build-clean against older sandbox-base:latest +# tags too. Root membership preserves PID 1 access when CAP_DAC_OVERRIDE is +# dropped. The `id -nG` checks make this idempotent. Remove this block after +# the minimum supported OpenClaw sandbox base tag is v0.0.71 or newer and +# Dockerfile.base guarantees both memberships; keep that base contract covered +# by test/sandbox-provisioning.test.ts. # hadolint ignore=DL4006 RUN if id gateway >/dev/null 2>&1 && id sandbox >/dev/null 2>&1; then \ if ! id -nG gateway | tr ' ' '\n' | grep -qx sandbox; then \ usermod -aG sandbox gateway; \ fi; \ + fi \ + && if id root >/dev/null 2>&1 && id sandbox >/dev/null 2>&1; then \ + if ! id -nG root | tr ' ' '\n' | grep -qx sandbox; then \ + usermod -aG sandbox root; \ + fi; \ fi # Keep the image readable to the root entrypoint after capabilities are dropped. @@ -1087,32 +1117,12 @@ RUN set -eu; \ # host-side delivery-chain monitoring (verify-deployment.ts, host # port forward, sandbox status). # -# The pgrep pattern matches both `openclaw gateway run` (the launcher -# command nemoclaw-start runs) and `openclaw-gateway` (the older re-execed -# binary form). Recent OpenClaw (v0.0.44 / 2026.5.18+) re-execs the -# long-running gateway into a process whose argv is plain `openclaw` with -# no `gateway` token at all (#4952), which that pattern cannot see — so on a -# marker-present container whose in-container curl probe failed, the stale -# pattern reported a live gateway as permanently unhealthy. -# -# When the pattern misses, fall back to the gateway PID that nemoclaw-start -# recorded in /tmp/nemoclaw-gateway.pid (record_gateway_pid, written for both -# the root and non-root launch paths and refreshed on every respawn) and -# confirm THAT pid is still a live `openclaw` process. This deliberately does -# not match any process merely named `openclaw`: a bare `pgrep -x openclaw` -# would keep Docker healthy when the real gateway has died but an unrelated -# `openclaw` one-shot (e.g. `openclaw agent ...`) happens to be running, -# defeating restart/self-healing. The recorded-pid check is gateway-specific -# and survives PID reuse via the comm prefix guard. `ps -o comm=` reads the -# (15-char) process name, which is `openclaw` for the re-execed gateway and -# `openclaw-gatewa(y)` for the legacy form — both match `openclaw*`. -# -# pgrep uses --ignore-ancestors so it cannot self-match the healthcheck -# shell that Docker spawns to run this CMD — that shell's argv contains -# the literal 'openclaw gateway' string we're searching for, and -# without --ignore-ancestors `pgrep -f` would happily report it as the -# live gateway even after the real process exited (procps 4.0+ supports -# this flag; the base image pins procps to 2:4.0.4-9). +# nemoclaw-start records `pid starttime` for the exact gateway process in +# /tmp/nemoclaw-gateway.pid on every launch. When curl sees connection +# refused, validate both values against `/proc//stat` field 22 before +# accepting the exact OpenClaw gateway cmdline fallback. A numeric PID or +# OpenClaw-looking argv alone is insufficient because either can belong to a +# recycled process. HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \ CMD port="${NEMOCLAW_DASHBOARD_PORT:-${OPENCLAW_GATEWAY_PORT:-}}"; \ if [ -z "$port" ]; then \ @@ -1123,11 +1133,12 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \ if [ "$rc" = 0 ]; then exit 0; fi; \ if [ "$rc" != 7 ]; then exit 1; fi; \ [ -f /tmp/nemoclaw-gateway-local ] || exit 0; \ - if ! pgrep --ignore-ancestors -f 'openclaw[ -]gateway' > /dev/null 2>&1; then \ - gwpid="$(cat /tmp/nemoclaw-gateway.pid 2>/dev/null)"; \ - case "${gwpid:-x}" in *[!0-9]*) exit 1 ;; esac; \ - case "$(ps -p "$gwpid" -o comm= 2>/dev/null)" in openclaw*) ;; *) exit 1 ;; esac; \ - fi; \ + gwpid=; gwstart=; gwextra=; \ + IFS=' ' read -r gwpid gwstart gwextra /dev/null || exit 1; \ + case "${gwpid:-x}" in *[!0-9]*) exit 1 ;; esac; \ + case "${gwstart:-x}" in *[!0-9]*) exit 1 ;; esac; \ + [ -z "$gwextra" ] || exit 1; \ + python3 -c 'import pathlib, sys; proc = pathlib.Path(sys.argv[1]); expected = sys.argv[2].encode("ascii"); port = sys.argv[3].encode(); parse = lambda data: (lambda fields: (fields[0], fields[19]))(data.rsplit(b") ", 1)[1].split()); before = parse((proc / "stat").read_bytes()); raw = (proc / "cmdline").read_bytes(); after = parse((proc / "stat").read_bytes()); trimmed = raw.rstrip(b"\0"); padding = len(raw) - len(trimmed); title = padding >= 1 and trimmed in (b"openclaw", b"openclaw-gateway"); argv = raw[:-1].split(b"\0") if padding == 1 else []; interpreters = (b"node", b"nodejs", b"/usr/local/bin/node", b"/usr/local/bin/nodejs", b"/usr/bin/node", b"/usr/bin/nodejs"); launchers = (b"/usr/local/bin/openclaw", b"/usr/local/lib/node_modules/openclaw/openclaw.mjs"); index = 1 if argv and argv[0] in interpreters else 0; command = index < len(argv) and argv[index] in launchers and argv[index + 1:] in ([b"gateway", b"run", b"--port", port], [b"gateway", b"run", b"--port=" + port]); identity = before[1] == expected == after[1] and before[0] != b"Z" and after[0] != b"Z"; raise SystemExit(not (identity and (title or command)))' "/proc/$gwpid" "$gwstart" "$port" 2>/dev/null || exit 1; \ [ -s /tmp/gateway.log ] # Entrypoint runs as root to start the gateway as the gateway user, diff --git a/Dockerfile.base b/Dockerfile.base index fca3d394825..3840a6a320b 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -97,12 +97,16 @@ RUN arch="$(dpkg --print-architecture)" \ # # `gateway` is also a member of the `sandbox` group so both users can write # to the mutable-default OpenClaw config tree (chmod g+w + setgid below). +# Keep root in that group too: hardened runtimes may drop CAP_DAC_OVERRIDE, +# but the root PID 1 lifecycle guard still needs descriptor-safe access to the +# sandbox-owned mutable tree before it can validate or transition it. # This replaces the previous EACCES-swallow approach for control-UI config # mutations — see #2681. UIDs stay distinct (security separation preserved); # the shared group only governs the mutable-default state directory. RUN groupadd -r gateway && useradd -r -g gateway -d /sandbox -s /usr/sbin/nologin gateway \ && groupadd -r sandbox && useradd -r -g sandbox -d /sandbox -s /bin/bash sandbox \ && usermod -aG sandbox gateway \ + && usermod -aG sandbox root \ && mkdir -p /sandbox/.nemoclaw \ && chown -R sandbox:sandbox /sandbox diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index c2b0463359c..bd0a3b3ef2e 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -107,21 +107,35 @@ COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ RUN chmod -R a+rX /opt/nemoclaw-blueprint/ # Copy startup script and the secret-boundary validator. The validator is the -# single source of truth shared between start.sh (cold start) and the host-side -# gateway recovery script (src/lib/agent/runtime.ts) so `sandbox recover` enforces -# the same boundary as the initial entrypoint. +# single source of truth used by start.sh at cold start and by its root-owned +# PID 1 lifecycle handler, so `recover` enforces the same boundary as startup. COPY scripts/lib/sandbox-init.sh /usr/local/lib/nemoclaw/sandbox-init.sh +COPY scripts/lib/gateway-supervisor.sh /usr/local/lib/nemoclaw/gateway-supervisor.sh COPY scripts/lib/sandbox-rlimits.sh /usr/local/lib/nemoclaw/sandbox-rlimits.sh COPY agents/hermes/start.sh /usr/local/bin/nemoclaw-start +COPY scripts/gateway-control.sh /usr/local/bin/nemoclaw-gateway-control +COPY scripts/managed-gateway-control.py /usr/local/lib/nemoclaw/managed-gateway-control.py COPY agents/hermes/validate-env-secret-boundary.py /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py COPY agents/hermes/seed-dashboard-config.py /usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py COPY agents/hermes/runtime-config-guard.py /usr/local/lib/nemoclaw/hermes-runtime-config-guard.py +COPY scripts/state-dir-guard.py /usr/local/lib/nemoclaw/state-dir-guard.py +COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ # Dockerfile.base is the source of truth for rlimit hooks. This Hermes replay # only repairs stale bases predating the v0.0.69 base layer, which may lack the # profile hook, bashrc hook, or root-owned helper mode. Remove it once the # minimum supported Hermes sandbox base tag guarantees those artifacts and # test/sandbox-rlimit-hooks.test.ts covers that base. RUN chmod 755 /usr/local/bin/nemoclaw-start /usr/local/lib/nemoclaw/sandbox-init.sh /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py /usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py /usr/local/lib/nemoclaw/hermes-runtime-config-guard.py \ + && chown root:root /usr/local/bin/nemoclaw-gateway-control /usr/local/lib/nemoclaw/gateway-supervisor.sh /usr/local/lib/nemoclaw/state-dir-guard.py /usr/local/lib/nemoclaw/managed-gateway-control.py \ + && chmod 700 /usr/local/bin/nemoclaw-gateway-control \ + && chmod 500 /usr/local/lib/nemoclaw/state-dir-guard.py /usr/local/lib/nemoclaw/managed-gateway-control.py \ + && chmod 444 /usr/local/lib/nemoclaw/gateway-supervisor.sh \ + && if [ -d /usr/local/lib/nemoclaw/preloads ]; then \ + chown -R 0:0 /usr/local/lib/nemoclaw/preloads \ + && find /usr/local/lib/nemoclaw/preloads -type f -exec chmod 444 {} + \ + && find /usr/local/lib/nemoclaw/preloads -type d -exec chmod 755 {} + \ + ; \ + fi \ && chmod 444 /usr/local/lib/nemoclaw/sandbox-rlimits.sh \ && mkdir -p /etc/profile.d \ && printf '%s\n' \ @@ -434,7 +448,7 @@ RUN mkdir -p /etc/nemoclaw \ # Backward-compatible marker for host-side shields logic on older sandboxes. RUN sha256sum /sandbox/.hermes/config.yaml /sandbox/.hermes/.env \ > /sandbox/.hermes/.config-hash \ - && chmod 600 /sandbox/.hermes/.config-hash \ + && chmod 640 /sandbox/.hermes/.config-hash \ && chown sandbox:sandbox /sandbox/.hermes/.config-hash # OpenShell's macOS VM backend currently remaps extracted rootfs ownership to diff --git a/agents/hermes/runtime-config-guard.py b/agents/hermes/runtime-config-guard.py index 30e934c9318..a4c9cb268c1 100755 --- a/agents/hermes/runtime-config-guard.py +++ b/agents/hermes/runtime-config-guard.py @@ -7,16 +7,24 @@ from __future__ import annotations import argparse +import base64 +import copy import errno +import fcntl +import grp import hashlib import json import os +import pwd import re import secrets +import signal import stat +import struct import subprocess import sys import tempfile +import time from dataclasses import dataclass @@ -24,6 +32,38 @@ ENV_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") SCOPED_PLACEHOLDER_PREFIX = "openshell:resolve:env:" BOUNDARY_VALIDATOR_TIMEOUT_SECONDS = 5 +FS_IOC_GETFLAGS = 0x80086601 +FS_IOC_SETFLAGS = 0x40086602 +FS_IMMUTABLE_FL = 0x00000010 +FS_APPEND_FL = 0x00000020 +MAX_CONFIG_INPUT_BYTES = 16 * 1024 * 1024 +MAX_ENV_BYTES = 4 * 1024 * 1024 +MAX_HASH_BYTES = 4 * 1024 +MAX_RUNTIME_PLAN_BYTES = 4 * 1024 * 1024 +MAX_RESTART_STATE_BYTES = 32 * 1024 * 1024 +MAX_MUTATION_LOCK_BYTES = 16 * 1024 +MAX_PROC_BYTES = 1024 * 1024 +PROC_ROOT = "/proc" +MAX_PROC_ENTRIES = 32768 +NEMOCLAW_START_ARGV = (b"nemoclaw-start", b"/usr/local/bin/nemoclaw-start") +OPENSHELL_SUPERVISOR_ARGV0 = b"/opt/openshell/bin/openshell-sandbox" +SEALED_FILE_NAMES = ("config.yaml", ".env", ".config-hash") +RESTART_ORPHAN_MARKER_NAME = ".nemoclaw-hermes-restart-seal" +SHIELDS_TRANSITION_LEASE_SECONDS = 300 +STATE_WORKER_LEASE_SECONDS = 15 * 60 +HERMES_STARTUP_READY_FILE = "/run/nemoclaw/hermes-startup-ready" +NEMOCLAW_RUNTIME_DIR = "/run/nemoclaw" +NEMOCLAW_RUNTIME_DIR_MODE = 0o711 +HERMES_RESTART_STATE_FILE = "/run/nemoclaw/hermes-restart-seal.json" +HERMES_MUTATION_LOCK_FILE = "/run/nemoclaw/hermes-config-mutation.lock" +DIRECTORY_FSYNC_UNSUPPORTED_ERRNOS = frozenset( + {errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP} +) +_DIRECTORY_FSYNC_WARNING_EMITTED = False +INSTALLED_RUNTIME_CONFIG_GUARD = ( + "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py" +) +GUARD_DEADLINE_SECONDS = 10 * 60 # Restrictive compatibility fallback for provider placeholders persisted before # Hermes messaging runtime-plan metadata existed. New channels must flow through # runtime-plan credentialBindings/envAliases; do not broaden this set without a @@ -44,6 +84,10 @@ class UnsafePathError(RuntimeError): """Raised when a mutable runtime config path is unsafe to trust.""" +class StrictHashMismatchError(UnsafePathError): + """Raised only when safe strict-hash bytes do not match safe config inputs.""" + + def _no_follow_flag() -> int: flag = getattr(os, "O_NOFOLLOW", 0) if not flag: @@ -67,6 +111,9 @@ class FileSnapshot: uid: int gid: int nlink: int + size: int + mtime_ns: int + ctime_ns: int @classmethod def from_stat(cls, st: os.stat_result) -> "FileSnapshot": @@ -77,6 +124,9 @@ def from_stat(cls, st: os.stat_result) -> "FileSnapshot": uid=st.st_uid, gid=st.st_gid, nlink=st.st_nlink, + size=st.st_size, + mtime_ns=st.st_mtime_ns, + ctime_ns=st.st_ctime_ns, ) @@ -89,22 +139,690 @@ def __init__(self, path: str, fd: int, snapshot: FileSnapshot): def close(self) -> None: os.close(self.fd) - def read_bytes(self) -> bytes: + def read_bytes(self, max_bytes: int = MAX_CONFIG_INPUT_BYTES) -> bytes: + if max_bytes < 0 or self.snapshot.size > max_bytes: + raise UnsafePathError( + f"refusing oversized runtime config path: {self.path}" + ) os.lseek(self.fd, 0, os.SEEK_SET) chunks: list[bytes] = [] + total = 0 while True: - chunk = os.read(self.fd, 1024 * 1024) + chunk = os.read(self.fd, min(1024 * 1024, max_bytes + 1 - total)) if not chunk: break + total += len(chunk) + if total > max_bytes: + raise UnsafePathError( + f"refusing oversized runtime config path: {self.path}" + ) chunks.append(chunk) + if FileSnapshot.from_stat(os.fstat(self.fd)) != self.snapshot: + raise UnsafePathError(f"refusing raced runtime config path: {self.path}") return b"".join(chunks) + def sha256(self, max_bytes: int) -> str: + if max_bytes < 0 or self.snapshot.size > max_bytes: + raise UnsafePathError( + f"refusing oversized runtime config path: {self.path}" + ) + os.lseek(self.fd, 0, os.SEEK_SET) + digest = hashlib.sha256() + total = 0 + while True: + chunk = os.read(self.fd, min(1024 * 1024, max_bytes + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > max_bytes: + raise UnsafePathError( + f"refusing oversized runtime config path: {self.path}" + ) + digest.update(chunk) + if FileSnapshot.from_stat(os.fstat(self.fd)) != self.snapshot: + raise UnsafePathError(f"refusing raced runtime config path: {self.path}") + return digest.hexdigest() + def _die(message: str) -> None: print(f"[SECURITY] {message}", file=sys.stderr) sys.exit(1) +def _deadline_expired(_signum: int, _frame: object) -> None: + raise UnsafePathError("Hermes runtime config guard exceeded its deadline") + + +def _open_proc_root() -> int: + return os.open( + PROC_ROOT, + os.O_RDONLY | _directory_flag() | _no_follow_flag() | _cloexec_flag(), + ) + + +def _open_proc_pid(proc_root_fd: int, pid: int | str) -> int: + return os.open( + str(pid), + os.O_RDONLY | _directory_flag() | _no_follow_flag() | _cloexec_flag(), + dir_fd=proc_root_fd, + ) + + +def _read_proc_pid_file( + proc_pid_fd: int, name: str, display_path: str +) -> bytes: + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=proc_pid_fd, + ) + try: + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(4096, MAX_PROC_BYTES + 1 - total)) + if not chunk: + return b"".join(chunks) + total += len(chunk) + if total > MAX_PROC_BYTES: + raise UnsafePathError( + f"refusing oversized proc entry: {display_path}" + ) + chunks.append(chunk) + finally: + os.close(fd) + + +def _proc_pid_namespace_inode(proc_pid_fd: int) -> int | None: + ns_fd = -1 + try: + ns_fd = os.open( + "ns", + os.O_RDONLY | _directory_flag() | _no_follow_flag() | _cloexec_flag(), + dir_fd=proc_pid_fd, + ) + inode = os.stat("pid", dir_fd=ns_fd, follow_symlinks=True).st_ino + return inode if inode > 0 else None + except OSError: + return None + finally: + if ns_fd >= 0: + os.close(ns_fd) + + +def _cmdline_is_nemoclaw_start(raw: bytes) -> bool: + return any(argument in NEMOCLAW_START_ARGV for argument in raw.split(b"\0")) + + +def _cmdline_is_openshell_supervisor(raw: bytes) -> bool: + arguments = raw.split(b"\0") + return bool(arguments and arguments[0] == OPENSHELL_SUPERVISOR_ARGV0) + + +def _parse_process_parent_pid(raw: bytes) -> int | None: + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + return None + closing_paren = text.rfind(")") + if closing_paren < 0: + return None + fields_after_comm = text[closing_paren + 2 :].split() + if len(fields_after_comm) <= 1: + return None + try: + parent_pid = int(fields_after_comm[1], 10) + except ValueError: + return None + return parent_pid if parent_pid >= 0 else None + + +def _process_status_identity(raw: bytes) -> tuple[int, tuple[int, ...]] | None: + try: + lines = raw.decode("ascii").splitlines() + except UnicodeDecodeError: + return None + uid_fields: list[str] | None = None + namespace_pids: tuple[int, ...] | None = None + for line in lines: + if line.startswith("Uid:"): + uid_fields = line.removeprefix("Uid:").split() + elif line.startswith("NSpid:"): + try: + namespace_pids = tuple( + int(value, 10) for value in line.removeprefix("NSpid:").split() + ) + except ValueError: + return None + if uid_fields is None or len(uid_fields) != 4 or not namespace_pids: + return None + try: + effective_uid = int(uid_fields[1], 10) + except ValueError: + return None + if effective_uid < 0 or any(pid <= 0 for pid in namespace_pids): + return None + return effective_uid, namespace_pids + + +def _pid1_is_nemoclaw_start() -> bool: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, 1) + cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline" + ) + except (OSError, UnsafePathError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + return _cmdline_is_nemoclaw_start(cmdline) + + +def _pinned_process_matches_startup_identity( + proc_root_fd: int, + pid: str, + expected_start_time: str, + expected_namespace_inode: int, + expected_effective_uid: int, +) -> bool: + proc_pid_fd = -1 + try: + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + pinned_before = os.fstat(proc_pid_fd) + first_start_time = _parse_process_start_time( + _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + ) + if first_start_time is None or not secrets.compare_digest( + first_start_time, expected_start_time + ): + return False + first_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + if ( + first_status is None + or first_status[0] != expected_effective_uid + or first_status[1][-1] != 1 + ): + return False + cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + if not _cmdline_is_nemoclaw_start(cmdline): + return False + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + if first_namespace_inode != expected_namespace_inode: + return False + second_start_time = _parse_process_start_time( + _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + ) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + second_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + return bool( + second_start_time is not None + and secrets.compare_digest(second_start_time, expected_start_time) + and second_status is not None + and second_status[0] == expected_effective_uid + and second_status[1][-1] == 1 + and _cmdline_is_nemoclaw_start(second_cmdline) + and second_namespace_inode == expected_namespace_inode + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ) + except (OSError, UnsafePathError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + + +def _startup_process_identity_is_live( + expected_start_time: str, + expected_namespace_inode: int, + expected_effective_uid: int = 0, +) -> bool: + if ( + not re.fullmatch(r"[0-9]+", expected_start_time) + or expected_namespace_inode <= 0 + ): + return False + proc_root_fd = -1 + try: + proc_root_fd = _open_proc_root() + observed = 0 + matches = 0 + with os.scandir(proc_root_fd) as entries: + for entry in entries: + if not entry.name.isascii() or not entry.name.isdigit(): + continue + observed += 1 + if observed > MAX_PROC_ENTRIES: + return False + if _pinned_process_matches_startup_identity( + proc_root_fd, + entry.name, + expected_start_time, + expected_namespace_inode, + expected_effective_uid, + ): + matches += 1 + if matches > 1: + return False + return matches == 1 + except OSError: + return False + finally: + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _openshell_supervisor_identity( + expected_effective_uid: int, +) -> tuple[str, int | None] | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, 1) + pinned_before = os.fstat(proc_pid_fd) + first_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline" + ) + first_status = _process_status_identity( + _read_proc_pid_file(proc_pid_fd, "status", f"{PROC_ROOT}/1/status") + ) + first_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/1/stat" + ) + first_start_time = _parse_process_start_time(first_stat) + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline" + ) + second_status = _process_status_identity( + _read_proc_pid_file(proc_pid_fd, "status", f"{PROC_ROOT}/1/status") + ) + second_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/1/stat" + ) + second_start_time = _parse_process_start_time(second_stat) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + if not ( + _cmdline_is_openshell_supervisor(first_cmdline) + and _cmdline_is_openshell_supervisor(second_cmdline) + and first_status is not None + and second_status is not None + and first_status[0] == expected_effective_uid + and second_status[0] == expected_effective_uid + and first_status[1][-1] == 1 + and second_status[1][-1] == 1 + and _parse_process_parent_pid(first_stat) == 0 + and _parse_process_parent_pid(second_stat) == 0 + and first_start_time is not None + and second_start_time is not None + and secrets.compare_digest(first_start_time, second_start_time) + and ( + (first_namespace_inode is None and second_namespace_inode is None) + or ( + first_namespace_inode is not None + and first_namespace_inode == second_namespace_inode + ) + ) + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ): + return None + return first_start_time, first_namespace_inode + except (OSError, UnsafePathError): + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _pinned_process_matches_supervised_nonroot_start( + proc_root_fd: int, + pid: str, + supervisor_identity: tuple[str, int | None], + expected_effective_uid: int, +) -> bool: + proc_pid_fd = -1 + try: + numeric_pid = int(pid, 10) + if numeric_pid <= 1: + return False + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + pinned_before = os.fstat(proc_pid_fd) + first_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + first_start_time = _parse_process_start_time(first_stat) + first_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + first_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + second_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + second_start_time = _parse_process_start_time(second_stat) + second_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + expected_namespace_inode = supervisor_identity[1] + namespace_matches = ( + expected_namespace_inode is None + and first_namespace_inode == second_namespace_inode + ) or ( + expected_namespace_inode is not None + and first_namespace_inode == expected_namespace_inode + and second_namespace_inode == expected_namespace_inode + ) + return bool( + first_start_time is not None + and second_start_time is not None + and secrets.compare_digest(first_start_time, second_start_time) + and _parse_process_parent_pid(first_stat) == 1 + and _parse_process_parent_pid(second_stat) == 1 + and first_status is not None + and second_status is not None + and first_status[0] == expected_effective_uid + and second_status[0] == expected_effective_uid + and first_status[1][-1] == numeric_pid + and second_status[1][-1] == numeric_pid + and _cmdline_is_nemoclaw_start(first_cmdline) + and _cmdline_is_nemoclaw_start(second_cmdline) + and namespace_matches + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ) + except (OSError, UnsafePathError, ValueError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + + +def _openshell_supervised_nonroot_start_is_live( + expected_root_uid: int, + expected_sandbox_uid: int, + required_pid: int | None = None, +) -> bool: + supervisor_identity = _openshell_supervisor_identity(expected_root_uid) + if supervisor_identity is None: + return False + proc_root_fd = -1 + try: + proc_root_fd = _open_proc_root() + observed = 0 + matches = 0 + matched_pid: int | None = None + with os.scandir(proc_root_fd) as entries: + for entry in entries: + if not entry.name.isascii() or not entry.name.isdigit(): + continue + observed += 1 + if observed > MAX_PROC_ENTRIES: + return False + if _pinned_process_matches_supervised_nonroot_start( + proc_root_fd, + entry.name, + supervisor_identity, + expected_sandbox_uid, + ): + matches += 1 + matched_pid = int(entry.name, 10) + if matches > 1: + return False + return bool( + matches == 1 + and (required_pid is None or matched_pid == required_pid) + and _openshell_supervisor_identity(expected_root_uid) + == supervisor_identity + ) + except OSError: + return False + finally: + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _process_effective_uid(pid: int) -> int | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + status = _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ).decode("utf-8") + except (OSError, UnsafePathError, UnicodeDecodeError): + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + uid_line = next( + (line for line in status.splitlines() if line.startswith("Uid:")), "" + ) + try: + values = [int(value) for value in uid_line.split()[1:]] + except ValueError: + return None + return values[1] if len(values) >= 2 else None + + +def _startup_ready_marker_absent() -> bool: + try: + os.stat(HERMES_STARTUP_READY_FILE, follow_symlinks=False) + except FileNotFoundError: + return True + except OSError: + return False + return False + + +def _validate_action_readiness(action: str, startup_owner: bool) -> None: + installed_current = os.path.abspath(__file__) == INSTALLED_RUNTIME_CONFIG_GUARD + try: + sandbox_uid = pwd.getpwnam("sandbox").pw_uid + except KeyError: + sandbox_uid = -1 + startup_actions = { + "ensure-api-key", + "refresh-hashes", + "provider-placeholders", + "publish-startup-ready", + "recover-prestate-lock", + } + if action in startup_actions: + if not _pid1_is_nemoclaw_start(): + if ( + installed_current + and startup_owner + and sandbox_uid >= 0 + and _startup_ready_marker_absent() + and _openshell_supervised_nonroot_start_is_live( + 0, sandbox_uid, os.getppid() + ) + ): + return + # Local source fixtures have no NemoClaw PID 1 and exercise the + # guard against temporary directories. The installed production + # helper never treats that compatibility path as authority. + if installed_current: + raise UnsafePathError( + "Hermes runtime config guard refuses mutation under a foreign PID 1" + ) + return + if not startup_owner or os.getppid() != 1: + raise UnsafePathError( + f"{action} is restricted to the Hermes PID 1 startup transaction" + ) + return + host_actions = { + "seal-restart", + "write-config", + "begin-shields-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "run-state-dir-transition", + } + pid1_is_nemoclaw_start = _pid1_is_nemoclaw_start() + startup_ready = _startup_ready_for_current_pid1() + if not pid1_is_nemoclaw_start and not startup_ready: + if ( + installed_current + and action in host_actions + and sandbox_uid >= 0 + and _startup_ready_marker_absent() + and _openshell_supervised_nonroot_start_is_live(0, sandbox_uid) + ): + return + # Local source fixtures retain the explicit compatibility path. The + # installed helper requires either the direct entrypoint PID 1 or a + # root-owned marker bound to the remapped live startup process. + if installed_current: + raise UnsafePathError( + "Hermes runtime config guard refuses mutation under a foreign PID 1" + ) + return + if ( + action + in { + "begin-shields-transition", + "apply-shields-transition", + "finish-shields-transition", + "run-state-dir-transition", + } + and startup_owner + and os.getppid() == 1 + ): + return + if action in host_actions and not startup_ready: + # The macOS VM compatibility path runs NemoClaw PID 1 without root and + # cannot publish a root-owned readiness lease. It also cannot exercise + # the privileged root transaction; allow the historical best-effort + # host path only when PID 1 itself is demonstrably non-root. Root PID 1 + # remains fail-closed on every missing or malformed readiness marker. + pid1_euid = _process_effective_uid(1) + if pid1_euid is not None and pid1_euid != 0: + return + raise UnsafePathError( + "Hermes startup is not ready for host config or gateway mutations" + ) + + +def _startup_ready_for_current_pid1() -> bool: + try: + opened = _open_regular(HERMES_STARTUP_READY_FILE) + except (FileNotFoundError, UnsafePathError): + return False + try: + snapshot = opened.snapshot + if ( + snapshot.uid != 0 + or snapshot.gid != 0 + or snapshot.mode != 0o600 + or snapshot.nlink != 1 + ): + return False + try: + text = opened.read_bytes(MAX_HASH_BYTES).decode("ascii") + except UnicodeDecodeError: + return False + legacy = re.fullmatch(r"v1 ([0-9]+)\n", text) + if legacy: + # Version 1 has no PID-namespace identity and is safe only when + # the helper directly observes the NemoClaw entrypoint as PID 1. + start_time = _process_start_time(1) + return bool( + start_time is not None + and _pid1_is_nemoclaw_start() + and secrets.compare_digest(legacy.group(1), start_time) + ) + current = re.fullmatch(r"v2 ([0-9]+) ([0-9]+)\n", text) + if not current: + return False + namespace_inode = int(current.group(2), 10) + return _startup_process_identity_is_live( + current.group(1), namespace_inode + ) + finally: + opened.close() + + +def publish_startup_ready() -> None: + start_time = _process_start_time(1) + namespace_inode = _process_namespace_inode(1) + if start_time is None or namespace_inode is None: + raise UnsafePathError("cannot identify Hermes PID 1 for startup readiness") + payload = f"v2 {start_time} {namespace_inode}\n".encode("ascii") + try: + opened = _open_regular(HERMES_STARTUP_READY_FILE) + except FileNotFoundError: + _atomic_replace( + HERMES_STARTUP_READY_FILE, + payload, + expected=None, + mode=0o600, + uid=0, + gid=0, + ) + return + try: + snapshot = opened.snapshot + finally: + opened.close() + if snapshot.uid != 0 or snapshot.gid != 0 or snapshot.mode != 0o600: + raise UnsafePathError("refusing unsafe stale Hermes startup readiness marker") + _atomic_replace( + HERMES_STARTUP_READY_FILE, + payload, + expected=snapshot, + mode=0o600, + uid=0, + gid=0, + ) + + def _split_path(path: str) -> tuple[str, str]: abs_path = os.path.abspath(path) return os.path.dirname(abs_path), os.path.basename(abs_path) @@ -116,217 +834,3113 @@ def _open_parent_dir(path: str) -> tuple[int, str]: try: dir_fd = os.open(directory, flags) except OSError as exc: - raise UnsafePathError(f"refusing runtime config update because {directory} is unsafe: {exc}") from exc + raise UnsafePathError( + f"refusing runtime config update because {directory} is unsafe: {exc}" + ) from exc st = os.fstat(dir_fd) if not stat.S_ISDIR(st.st_mode): os.close(dir_fd) - raise UnsafePathError(f"refusing runtime config update because {directory} is not a directory") + raise UnsafePathError( + f"refusing runtime config update because {directory} is not a directory" + ) return dir_fd, basename -def _validate_regular(path: str, st: os.stat_result) -> FileSnapshot: - if stat.S_ISLNK(st.st_mode): - raise UnsafePathError(f"refusing to follow symlink: {path}") - if not stat.S_ISREG(st.st_mode): - raise UnsafePathError(f"refusing non-regular runtime config path: {path}") - if st.st_nlink != 1: - raise UnsafePathError(f"refusing hardlinked runtime config path: {path}") - mode = stat.S_IMODE(st.st_mode) - if mode & 0o022: - raise UnsafePathError(f"refusing group/world-writable runtime config path: {path}") - return FileSnapshot.from_stat(st) +def _validate_regular(path: str, st: os.stat_result) -> FileSnapshot: + if stat.S_ISLNK(st.st_mode): + raise UnsafePathError(f"refusing to follow symlink: {path}") + if not stat.S_ISREG(st.st_mode): + raise UnsafePathError(f"refusing non-regular runtime config path: {path}") + if st.st_nlink != 1: + raise UnsafePathError(f"refusing hardlinked runtime config path: {path}") + mode = stat.S_IMODE(st.st_mode) + if mode & 0o022: + raise UnsafePathError( + f"refusing group/world-writable runtime config path: {path}" + ) + return FileSnapshot.from_stat(st) + + +def _open_regular(path: str, mode: int = os.O_RDONLY) -> OpenFile: + dir_fd, basename = _open_parent_dir(path) + try: + flags = mode | _no_follow_flag() | _cloexec_flag() + fd = os.open(basename, flags, dir_fd=dir_fd) + try: + snapshot = _validate_regular(path, os.fstat(fd)) + except Exception: + os.close(fd) + raise + return OpenFile(path, fd, snapshot) + finally: + os.close(dir_fd) + + +def _stat_path_at(dir_fd: int, basename: str) -> os.stat_result: + return os.stat(basename, dir_fd=dir_fd, follow_symlinks=False) + + +def _same_snapshot(st: os.stat_result, snapshot: FileSnapshot) -> bool: + return ( + st.st_dev == snapshot.dev + and st.st_ino == snapshot.ino + and stat.S_IMODE(st.st_mode) == snapshot.mode + and st.st_uid == snapshot.uid + and st.st_gid == snapshot.gid + and st.st_nlink == snapshot.nlink + and st.st_size == snapshot.size + and st.st_mtime_ns == snapshot.mtime_ns + and st.st_ctime_ns == snapshot.ctime_ns + and stat.S_ISREG(st.st_mode) + ) + + +def _assert_current_snapshot( + dir_fd: int, basename: str, path: str, snapshot: FileSnapshot +) -> None: + current = _stat_path_at(dir_fd, basename) + if not _same_snapshot(current, snapshot): + raise UnsafePathError(f"refusing raced runtime config path: {path}") + + +def _atomic_replace( + path: str, + data: bytes, + *, + expected: FileSnapshot | None, + mode: int, + uid: int, + gid: int, +) -> None: + dir_fd, basename = _open_parent_dir(path) + tmp_name = f".{basename}.nemoclaw.{os.getpid()}.{secrets.token_hex(8)}" + tmp_fd: int | None = None + try: + if expected is not None: + _assert_current_snapshot(dir_fd, basename, path, expected) + else: + try: + _stat_path_at(dir_fd, basename) + except FileNotFoundError: + pass + else: + raise UnsafePathError(f"refusing raced runtime config create: {path}") + + tmp_fd = os.open( + tmp_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | _no_follow_flag() | _cloexec_flag(), + 0o600, + dir_fd=dir_fd, + ) + try: + os.fchown(tmp_fd, uid, gid) + except PermissionError: + if os.geteuid() == 0: + raise + os.fchmod(tmp_fd, mode) + with os.fdopen(tmp_fd, "wb", closefd=True) as handle: + tmp_fd = None + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + + if expected is not None: + _assert_current_snapshot(dir_fd, basename, path, expected) + os.replace(tmp_name, basename, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) + _fsync_directory_after_replace(dir_fd) + except Exception: + try: + os.unlink(tmp_name, dir_fd=dir_fd) + except FileNotFoundError: + # The temp file may not exist yet, or may already have been removed + # by the failing operation path. + pass + except OSError: + # Cleanup must not mask the original atomic-write failure. + pass + raise + finally: + if tmp_fd is not None: + os.close(tmp_fd) + os.close(dir_fd) + + +def _fsync_directory_after_replace(dir_fd: int) -> None: + global _DIRECTORY_FSYNC_WARNING_EMITTED + + try: + os.fsync(dir_fd) + except OSError as exc: + if exc.errno not in DIRECTORY_FSYNC_UNSUPPORTED_ERRNOS: + raise + if not _DIRECTORY_FSYNC_WARNING_EMITTED: + print( + "[security] directory fsync is unsupported; the atomic Hermes config rename completed without a directory durability barrier", + file=sys.stderr, + ) + _DIRECTORY_FSYNC_WARNING_EMITTED = True + + +def _atomic_replace_preserving_flags( + path: str, data: bytes, expected: FileSnapshot +) -> None: + opened = _open_regular(path) + try: + if opened.snapshot != expected: + raise UnsafePathError(f"refusing raced runtime config path: {path}") + original_flags = _get_inode_flags(opened.fd) + mutable_flags = original_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + if mutable_flags != original_flags: + _set_inode_flags(opened.fd, mutable_flags) + mutable_snapshot = FileSnapshot.from_stat(os.fstat(opened.fd)) + try: + _atomic_replace( + path, + data, + expected=mutable_snapshot, + mode=expected.mode, + uid=expected.uid, + gid=expected.gid, + ) + except Exception: + if mutable_flags != original_flags: + try: + _set_inode_flags(opened.fd, original_flags) + except Exception: + # Preserve the primary replacement failure; the caller + # retains the sealed transaction for explicit recovery. + pass + raise + finally: + opened.close() + + replacement = _open_regular(path) + try: + if original_flags: + _set_inode_flags(replacement.fd, original_flags) + finally: + replacement.close() + + +def _read_text( + path: str, max_bytes: int = MAX_CONFIG_INPUT_BYTES +) -> tuple[str, FileSnapshot]: + opened = _open_regular(path) + try: + return opened.read_bytes(max_bytes).decode("utf-8"), opened.snapshot + finally: + opened.close() + + +def _sha256_entry(path: str, max_bytes: int) -> tuple[str, FileSnapshot]: + opened = _open_regular(path) + try: + digest = opened.sha256(max_bytes) + return f"{digest} {path}\n", opened.snapshot + finally: + opened.close() + + +def _write_existing( + path: str, text: str, snapshot: FileSnapshot, mode: int | None = None +) -> None: + if mode is not None and mode != snapshot.mode: + _atomic_replace( + path, + text.encode("utf-8"), + expected=snapshot, + mode=mode, + uid=snapshot.uid, + gid=snapshot.gid, + ) + return + _atomic_replace_preserving_flags(path, text.encode("utf-8"), snapshot) + + +def _write_hash(path: str, text: str) -> None: + try: + opened = _open_regular(path) + except FileNotFoundError: + _atomic_replace( + path, + text.encode("utf-8"), + expected=None, + mode=0o600, + uid=os.geteuid(), + gid=os.getegid(), + ) + return + try: + snapshot = opened.snapshot + finally: + opened.close() + _atomic_replace_preserving_flags(path, text.encode("utf-8"), snapshot) + + +def _hash_text( + config_path: str, env_path: str +) -> tuple[str, FileSnapshot, FileSnapshot]: + config_entry, config_snapshot = _sha256_entry( + config_path, MAX_CONFIG_INPUT_BYTES + ) + env_entry, env_snapshot = _sha256_entry(env_path, MAX_ENV_BYTES) + return config_entry + env_entry, config_snapshot, env_snapshot + + +def _sealed_file_limit(name: str) -> int: + if name == "config.yaml": + return MAX_CONFIG_INPUT_BYTES + if name == ".env": + return MAX_ENV_BYTES + if name == ".config-hash": + return MAX_HASH_BYTES + raise UnsafePathError(f"refusing unknown Hermes sealed path: {name}") + + +def _decode_bounded_base64(value: str, max_bytes: int, label: str) -> bytes: + # Check the encoded shape before decoding so a hostile journal cannot make + # Python allocate an attacker-sized temporary merely to reject it later. + max_encoded = ((max_bytes + 2) // 3) * 4 + if len(value) > max_encoded: + raise UnsafePathError(f"refusing oversized {label}") + try: + decoded = base64.b64decode(value, validate=True) + except (ValueError, UnicodeEncodeError, base64.binascii.Error) as exc: + raise UnsafePathError(f"refusing invalid {label}") from exc + if len(decoded) > max_bytes: + raise UnsafePathError(f"refusing oversized {label}") + return decoded + + +def refresh_hashes(hermes_dir: str, hash_file: str, mode: str) -> None: + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + compat_hash = os.path.join(hermes_dir, ".config-hash") + hash_text, config_snapshot, env_snapshot = _hash_text(config_path, env_path) + + def assert_inputs_stable() -> None: + config = _open_regular(config_path) + env = _open_regular(env_path) + try: + if config.snapshot != config_snapshot or env.snapshot != env_snapshot: + raise UnsafePathError( + "refusing raced Hermes config/env path before hash refresh" + ) + finally: + config.close() + env.close() + + # `both` is the transaction contract: both trust anchors must advance or + # the caller rolls the config write back. `compat` remains best-effort for + # legacy startup paths where an old locked image can expose a read-only + # in-tree anchor. + # Hash refresh is an atomic rename, so directory write authority is what + # matters; a correctly shields-locked compatibility file is itself 0444. + compat_writable = os.access(hermes_dir, os.W_OK) + if mode == "both" or (mode == "compat" and compat_writable): + assert_inputs_stable() + _write_hash(compat_hash, hash_text) + + # In `both` mode the root-owned strict anchor is the commit record and must + # advance last. A crash after compat but before strict therefore makes the + # next startup fail strict verification instead of blessing a half-commit. + if mode in ("strict", "both"): + assert_inputs_stable() + _write_hash(hash_file, hash_text) + + # Detect same-inode rewrites that raced either anchor update. The restart + # path temporarily makes both inputs root-owned/read-only, so this final + # check also proves the launched gateway will consume the validated bytes. + assert_inputs_stable() + + +def _inode_metadata(st: os.stat_result) -> dict[str, int]: + return { + "dev": st.st_dev, + "ino": st.st_ino, + "mode": stat.S_IMODE(st.st_mode), + "uid": st.st_uid, + "gid": st.st_gid, + } + + +def _get_inode_flags(fd: int) -> int: + try: + result = fcntl.ioctl(fd, FS_IOC_GETFLAGS, struct.pack("I", 0)) + return struct.unpack("I", result)[0] + except OSError as exc: + if exc.errno in (errno.ENOTTY, errno.EOPNOTSUPP, errno.EINVAL): + return 0 + raise + + +def _set_inode_flags(fd: int, flags: int) -> None: + try: + fcntl.ioctl(fd, FS_IOC_SETFLAGS, struct.pack("I", flags)) + except OSError as exc: + if flags == 0 and exc.errno in (errno.ENOTTY, errno.EOPNOTSUPP, errno.EINVAL): + return + raise UnsafePathError( + f"refusing restart seal because inode flags could not be restored: {exc}" + ) from exc + + +def _open_directory(path: str) -> int: + flags = os.O_RDONLY | _directory_flag() | _no_follow_flag() | _cloexec_flag() + fd = os.open(path, flags) + if not stat.S_ISDIR(os.fstat(fd).st_mode): + os.close(fd) + raise UnsafePathError( + f"refusing restart seal because {path} is not a directory" + ) + return fd + + +def _open_child_directory(parent_fd: int, name: str, path: str) -> int: + flags = os.O_RDONLY | _directory_flag() | _no_follow_flag() | _cloexec_flag() + fd = os.open(name, flags, dir_fd=parent_fd) + if not stat.S_ISDIR(os.fstat(fd).st_mode): + os.close(fd) + raise UnsafePathError( + f"refusing restart seal because {path} is not a directory" + ) + return fd + + +def _same_inode(st: os.stat_result, metadata: dict[str, int]) -> bool: + return st.st_dev == metadata["dev"] and st.st_ino == metadata["ino"] + + +def _read_hash_file(path: str) -> str: + opened = _open_regular(path) + try: + return opened.read_bytes(MAX_HASH_BYTES).decode("utf-8") + finally: + opened.close() + + +def _verify_strict_hash(hermes_dir: str, hash_file: str) -> None: + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + actual, _config_snapshot, _env_snapshot = _hash_text(config_path, env_path) + strict = _read_hash_file(hash_file) + _parse_two_file_hash(strict, config_path, env_path) + if actual != strict: + raise StrictHashMismatchError( + "strict hash verification failed for Hermes restart seal" + ) + + +def _verify_compat_hash(hash_file: str, compat_hash_file: str) -> None: + if _read_hash_file(compat_hash_file) != _read_hash_file(hash_file): + raise UnsafePathError("compat hash verification failed for Hermes restart seal") + + +def _parse_two_file_hash( + text: str, config_path: str, env_path: str +) -> tuple[str, str]: + parts = text.split("\n") + if len(parts) != 3 or parts[-1] != "": + raise UnsafePathError("refusing malformed Hermes config hash") + lines = parts[:-1] + expected_paths = (config_path, env_path) + if len(lines) != len(expected_paths): + raise UnsafePathError("refusing malformed Hermes config hash") + digests: list[str] = [] + for line, expected_path in zip(lines, expected_paths, strict=True): + match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) + if match is None or match.group(2) != expected_path: + raise UnsafePathError("refusing malformed Hermes config hash") + digests.append(match.group(1)) + return digests[0], digests[1] + + +def _without_single_generated_api_server_key(text: str) -> str: + retained: list[str] = [] + removed = 0 + for line in text.splitlines(keepends=True): + parsed = _parse_env_assignment(line) + if parsed is None or parsed[1] != "API_SERVER_KEY": + retained.append(line) + continue + if removed != 0 or re.fullmatch(r"API_SERVER_KEY=[0-9a-f]{64}\n", line) is None: + raise UnsafePathError( + "refusing unexpected API_SERVER_KEY change during non-root startup" + ) + removed += 1 + if removed != 1: + raise UnsafePathError( + "refusing missing API_SERVER_KEY change during non-root startup" + ) + return "".join(retained) + + +def _managed_nonroot_reconciliation_is_allowed() -> bool: + installed_current = os.path.abspath(__file__) == INSTALLED_RUNTIME_CONFIG_GUARD + if not installed_current: + return False + try: + sandbox_uid = pwd.getpwnam("sandbox").pw_uid + except KeyError: + return False + return _startup_ready_marker_absent() and _openshell_supervised_nonroot_start_is_live( + 0, sandbox_uid + ) + + +def _mutable_nonroot_reconciliation_posture_is_allowed( + hermes_meta: dict[str, int], + file_states: dict[str, dict[str, object]], +) -> bool: + try: + sandbox_uid, sandbox_gid = _sandbox_identity() + except UnsafePathError: + return False + + # OpenShell can present the live non-root home as private 0700 after the + # managed supervisor/dashboard has started. Shields-down transitions use + # the canonical set-id 03770 form. Both are sandbox-owned mutable roots; + # the root-owned 0755/0444 shields-up posture must never be reconciled. + if ( + hermes_meta.get("uid") != sandbox_uid + or hermes_meta.get("gid") != sandbox_gid + or hermes_meta.get("mode") not in (0o700, 0o3770) + ): + return False + + for name in ("config.yaml", ".env", ".config-hash"): + original = file_states.get(name, {}).get("original") + if ( + not isinstance(original, dict) + or original.get("uid") != sandbox_uid + or original.get("gid") != sandbox_gid + or int(original.get("mode", 0)) not in (0o600, 0o640) + ): + return False + return True + + +def _reconcile_nonroot_startup_api_key_hash( + hermes_dir: str, + hash_file: str, + expected_config_sha256: str, + hermes_meta: dict[str, int], + file_states: dict[str, dict[str, object]], +) -> None: + """Advance strict trust across the one non-root startup mutation we permit. + + OpenShell starts the Hermes entrypoint as ``sandbox``. That process must + mint a per-sandbox API bearer token, but it cannot update the root-owned + strict hash. A later root config write may reconcile that exact append only + after the namespace has been frozen. Every other config or env difference + remains a hard refusal. + """ + + if not _managed_nonroot_reconciliation_is_allowed(): + raise UnsafePathError( + "strict hash verification failed outside managed non-root startup" + ) + if not _mutable_nonroot_reconciliation_posture_is_allowed( + hermes_meta, file_states + ): + raise UnsafePathError( + "refusing strict hash reconciliation outside mutable Hermes posture" + ) + + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + compat_hash_path = os.path.join(hermes_dir, ".config-hash") + strict_text = _read_hash_file(hash_file) + strict_config_sha256, strict_env_sha256 = _parse_two_file_hash( + strict_text, config_path, env_path + ) + actual_text, config_snapshot, env_snapshot = _hash_text(config_path, env_path) + actual_config_sha256, _actual_env_sha256 = _parse_two_file_hash( + actual_text, config_path, env_path + ) + + if not secrets.compare_digest(_read_hash_file(compat_hash_path), actual_text): + raise UnsafePathError( + "compat hash does not match frozen Hermes inputs during non-root reconciliation" + ) + if not secrets.compare_digest(actual_config_sha256, expected_config_sha256): + raise UnsafePathError("Hermes config changed after the host read it; retry the command") + if not secrets.compare_digest(actual_config_sha256, strict_config_sha256): + raise UnsafePathError( + "refusing config drift during non-root strict hash reconciliation" + ) + + env_text, env_read_snapshot = _read_text(env_path, MAX_ENV_BYTES) + if env_read_snapshot != env_snapshot: + raise UnsafePathError("refusing raced Hermes env during strict hash reconciliation") + prior_env_text = _without_single_generated_api_server_key(env_text) + if not secrets.compare_digest( + hashlib.sha256(prior_env_text.encode("utf-8")).hexdigest(), strict_env_sha256 + ): + raise UnsafePathError( + "refusing non-API-key env drift during non-root strict hash reconciliation" + ) + + # Recheck both path snapshots immediately before the root-owned commit. + # A writable descriptor retained before the namespace freeze must not race + # the bytes whose trust is being advanced. + for path, expected_snapshot in ( + (config_path, config_snapshot), + (env_path, env_snapshot), + ): + opened = _open_regular(path) + try: + if opened.snapshot != expected_snapshot: + raise UnsafePathError( + "refusing raced Hermes inputs during strict hash reconciliation" + ) + finally: + opened.close() + + # The compatibility anchor already commits the frozen current inputs. + # Advance the root-owned strict anchor last, then let the ordinary seal + # verification and inode replacement path re-prove both anchors. + _write_hash(hash_file, actual_text) + + +def _state_file_parent_is_safe(path: str) -> None: + parent_fd, _basename = _open_parent_dir(path) + try: + st = os.fstat(parent_fd) + if st.st_uid != os.geteuid() or stat.S_IMODE(st.st_mode) & 0o022: + raise UnsafePathError( + f"refusing restart seal because state directory for {path} is not private" + ) + finally: + os.close(parent_fd) + + +def _ensure_private_runtime_directory( + runtime_dir: str, expected_uid: int, expected_gid: int, expected_mode: int +) -> None: + """Create one fixed protected runtime directory through a pinned safe parent.""" + + parent = os.path.dirname(runtime_dir) + basename = os.path.basename(runtime_dir) + if not parent or not basename or basename in (".", ".."): + raise UnsafePathError("refusing invalid Hermes runtime state directory") + try: + parent_fd = _open_directory(parent) + except OSError as exc: + raise UnsafePathError("Hermes runtime state parent is unavailable") from exc + child_fd: int | None = None + try: + parent_st = os.fstat(parent_fd) + if ( + parent_st.st_uid != expected_uid + or parent_st.st_gid != expected_gid + or stat.S_IMODE(parent_st.st_mode) & 0o022 + ): + raise UnsafePathError("refusing unsafe Hermes runtime state parent") + try: + os.mkdir(basename, expected_mode, dir_fd=parent_fd) + except FileExistsError: + pass + except OSError as exc: + raise UnsafePathError("Hermes runtime state directory is unavailable") from exc + try: + child_fd = _open_child_directory(parent_fd, basename, runtime_dir) + except OSError as exc: + raise UnsafePathError("Hermes runtime state directory is unavailable") from exc + child_st = os.fstat(child_fd) + if ( + child_st.st_uid != expected_uid + or child_st.st_gid != expected_gid + or stat.S_IMODE(child_st.st_mode) & 0o022 + ): + raise UnsafePathError("refusing unsafe Hermes runtime state directory") + if stat.S_IMODE(child_st.st_mode) != expected_mode: + # Managed OpenShell starts the supervisor as the sandbox user. It + # must be able to stat the fixed startup-readiness pathname while + # remaining unable to list or write this root-owned directory. + os.fchmod(child_fd, expected_mode) + child_st = os.fstat(child_fd) + if stat.S_IMODE(child_st.st_mode) != expected_mode: + raise UnsafePathError("could not make Hermes runtime state directory private") + finally: + if child_fd is not None: + os.close(child_fd) + os.close(parent_fd) + + +def _ensure_production_runtime_directory(lock_path: str, state_file: str) -> None: + if (lock_path, state_file) != ( + HERMES_MUTATION_LOCK_FILE, + HERMES_RESTART_STATE_FILE, + ): + return + if os.geteuid() != 0 or os.getegid() != 0: + raise UnsafePathError("Hermes production runtime state requires root") + _ensure_private_runtime_directory( + NEMOCLAW_RUNTIME_DIR, 0, 0, NEMOCLAW_RUNTIME_DIR_MODE + ) + + +def _acquire_mutation_lock( + lock_path: str, + token: str, + purpose: str, + state_file: str, +) -> None: + if not re.fullmatch(r"[0-9a-f]{64}", token): + raise UnsafePathError("refusing invalid Hermes config mutation lock token") + _ensure_production_runtime_directory(lock_path, state_file) + if os.path.exists(state_file): + raise UnsafePathError("Hermes config mutation is already in progress") + + parent = os.path.dirname(lock_path) + basename = os.path.basename(lock_path) + parent_fd = _open_directory(parent) + tmp_name = f".{basename}.{os.getpid()}.{secrets.token_hex(8)}" + tmp_fd: int | None = None + try: + parent_st = os.fstat(parent_fd) + if parent_st.st_uid != os.geteuid() or stat.S_IMODE(parent_st.st_mode) & 0o022: + raise UnsafePathError("refusing unsafe Hermes config mutation lock parent") + + tmp_fd = os.open( + tmp_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | _no_follow_flag() | _cloexec_flag(), + 0o600, + dir_fd=parent_fd, + ) + process_start_time = _process_start_time(os.getpid()) + payload = ( + json.dumps( + { + "version": 1, + "token": token, + "purpose": purpose, + "pid": os.getpid(), + "pid_start_time": process_start_time, + }, + sort_keys=True, + ) + + "\n" + ).encode("utf-8") + offset = 0 + while offset < len(payload): + offset += os.write(tmp_fd, payload[offset:]) + os.fchmod(tmp_fd, 0o600) + os.fsync(tmp_fd) + os.close(tmp_fd) + tmp_fd = None + + # A hard link publishes a complete record atomically without replacing + # an existing lock. A kill before this leaves no visible lock; a kill + # after it leaves a complete token that release can validate. + try: + os.link( + tmp_name, + basename, + src_dir_fd=parent_fd, + dst_dir_fd=parent_fd, + follow_symlinks=False, + ) + except FileExistsError as exc: + raise UnsafePathError( + "Hermes config mutation is already in progress" + ) from exc + finally: + if tmp_fd is not None: + os.close(tmp_fd) + try: + os.unlink(tmp_name, dir_fd=parent_fd) + except FileNotFoundError: + # The hard-link publication or an earlier cleanup consumed it. + pass + os.close(parent_fd) + + +def _parse_process_start_time(raw: bytes) -> str | None: + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + return None + closing_paren = text.rfind(")") + if closing_paren < 0: + return None + fields_after_comm = text[closing_paren + 2 :].split() + # The suffix starts at field 3 (`state`); starttime is field 22. + if len(fields_after_comm) <= 19: + return None + return fields_after_comm[19] + + +def _process_start_time(pid: int) -> str | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + raw = _read_proc_pid_file(proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat") + except (OSError, UnsafePathError): + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + return _parse_process_start_time(raw) + + +def _process_namespace_inode(pid: int) -> int | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + return _proc_pid_namespace_inode(proc_pid_fd) + except OSError: + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _read_proc_file(path: str) -> bytes: + fd = os.open(path, os.O_RDONLY | _cloexec_flag()) + try: + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(4096, MAX_PROC_BYTES + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > MAX_PROC_BYTES: + raise UnsafePathError(f"refusing oversized proc entry: {path}") + chunks.append(chunk) + return b"".join(chunks) + finally: + os.close(fd) + + +def _read_mutation_lock(lock_path: str) -> tuple[int, dict[str, object]]: + parent_fd, basename = _open_parent_dir(lock_path) + try: + fd = os.open( + basename, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=parent_fd, + ) + try: + owner_st = os.fstat(fd) + if ( + not stat.S_ISREG(owner_st.st_mode) + or owner_st.st_uid != os.geteuid() + or owner_st.st_gid != os.getegid() + or stat.S_IMODE(owner_st.st_mode) != 0o600 + or owner_st.st_nlink != 1 + ): + raise UnsafePathError("refusing unsafe Hermes config mutation lock") + owner_snapshot = FileSnapshot.from_stat(owner_st) + if owner_st.st_size > MAX_MUTATION_LOCK_BYTES: + raise UnsafePathError("refusing oversized Hermes config mutation lock") + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read( + fd, min(4096, MAX_MUTATION_LOCK_BYTES + 1 - total) + ) + if not chunk: + break + total += len(chunk) + if total > MAX_MUTATION_LOCK_BYTES: + raise UnsafePathError( + "refusing oversized Hermes config mutation lock" + ) + chunks.append(chunk) + if FileSnapshot.from_stat(os.fstat(fd)) != owner_snapshot: + raise UnsafePathError("refusing raced Hermes config mutation lock") + try: + owner = json.loads(b"".join(chunks).decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise UnsafePathError( + "refusing corrupt Hermes config mutation lock" + ) from exc + recorded = owner.get("token") if isinstance(owner, dict) else None + if not isinstance(owner, dict) or not isinstance(recorded, str): + raise UnsafePathError( + "refusing corrupt Hermes config mutation lock token" + ) + return parent_fd, owner + finally: + os.close(fd) + except Exception: + os.close(parent_fd) + raise + + +def _release_mutation_lock(lock_path: str, token: str) -> None: + try: + parent_fd, owner = _read_mutation_lock(lock_path) + except FileNotFoundError: + return + try: + recorded = owner.get("token") + if not isinstance(recorded, str): + raise UnsafePathError("refusing corrupt Hermes config mutation lock token") + if not secrets.compare_digest(recorded, token): + raise UnsafePathError("refusing Hermes config mutation lock token mismatch") + os.unlink(os.path.basename(lock_path), dir_fd=parent_fd) + finally: + os.close(parent_fd) + + +def _claim_transition_worker( + state_file: str, lock_token: str, purpose: str +) -> dict[str, object]: + if not re.fullmatch(r"[0-9a-f]{64}", lock_token): + raise UnsafePathError("refusing invalid Hermes transition worker token") + state_data = _load_restart_state(state_file) + recorded = state_data.get("mutation_lock_token") + lock_path = state_data.get("mutation_lock_path") + if ( + not isinstance(recorded, str) + or not isinstance(lock_path, str) + or not secrets.compare_digest(recorded, lock_token) + ): + raise UnsafePathError( + "refusing Hermes transition worker lock token mismatch" + ) + + # Read the owner and capture the exact inode snapshot through one + # descriptor. The compare-before-replace below then prevents two host + # workers from both observing the dead begin owner and stealing the lease + # from each other between separate read/open operations. + opened = _open_regular(lock_path) + try: + snapshot = opened.snapshot + if ( + snapshot.uid != os.geteuid() + or snapshot.gid != os.getegid() + or snapshot.mode != 0o600 + or snapshot.nlink != 1 + ): + raise UnsafePathError("refusing unsafe Hermes config mutation lock") + raw_owner = opened.read_bytes(MAX_MUTATION_LOCK_BYTES) + finally: + opened.close() + try: + owner = json.loads(raw_owner.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise UnsafePathError("refusing corrupt Hermes config mutation lock") from exc + if not isinstance(owner, dict): + raise UnsafePathError("refusing corrupt Hermes config mutation lock") + owner_token = owner.get("token") + if not isinstance(owner_token, str) or not secrets.compare_digest( + owner_token, lock_token + ): + raise UnsafePathError("refusing mismatched Hermes mutation lock owner") + if _mutation_lock_owner_is_live(owner) and owner.get("pid") != os.getpid(): + raise UnsafePathError("Hermes transition worker is still active") + + payload = ( + json.dumps( + { + "version": 1, + "token": lock_token, + "purpose": purpose, + "pid": os.getpid(), + "pid_start_time": _process_start_time(os.getpid()), + }, + sort_keys=True, + ) + + "\n" + ).encode("utf-8") + _atomic_replace( + lock_path, + payload, + expected=snapshot, + mode=0o600, + uid=os.geteuid(), + gid=os.getegid(), + ) + transition = state_data.get("shields_transition") + if isinstance(transition, dict): + transition["lease_expires_ns"] = ( + time.time_ns() + STATE_WORKER_LEASE_SECONDS * 1_000_000_000 + ) + state_data["shields_transition"] = transition + _write_restart_state(state_file, state_data, create=False) + return state_data + + +def recover_dead_prestate_mutation_lock(state_file: str) -> bool: + """Remove only a dead, fully published lock that has no recovery state.""" + + if os.path.exists(state_file): + raise UnsafePathError("refusing pre-state lock recovery while state exists") + lock_path = os.path.join(os.path.dirname(state_file), "hermes-config-mutation.lock") + parent_fd, basename = _open_parent_dir(lock_path) + quarantine = f".{basename}.dead.{os.getpid()}.{secrets.token_hex(8)}" + fd: int | None = None + moved = False + try: + try: + fd = os.open( + basename, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=parent_fd, + ) + except FileNotFoundError: + return False + st = os.fstat(fd) + if ( + not stat.S_ISREG(st.st_mode) + or st.st_uid != os.geteuid() + or st.st_gid != os.getegid() + or stat.S_IMODE(st.st_mode) != 0o600 + or st.st_nlink != 1 + or st.st_size > MAX_MUTATION_LOCK_BYTES + ): + raise UnsafePathError("refusing unsafe dead Hermes mutation lock") + opened = OpenFile(lock_path, fd, FileSnapshot.from_stat(st)) + try: + raw = opened.read_bytes(MAX_MUTATION_LOCK_BYTES) + finally: + # `fd` remains owned by this function; OpenFile.close is not used. + pass + try: + owner = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise UnsafePathError("refusing corrupt dead Hermes mutation lock") from exc + if ( + not isinstance(owner, dict) + or owner.get("version") != 1 + or not isinstance(owner.get("purpose"), str) + or not isinstance(owner.get("pid"), int) + or not isinstance(owner.get("pid_start_time"), str) + or not isinstance(owner.get("token"), str) + or not re.fullmatch(r"[0-9a-f]{64}", str(owner.get("token"))) + ): + raise UnsafePathError("refusing malformed dead Hermes mutation lock") + if _mutation_lock_owner_is_live(owner): + raise UnsafePathError("Hermes config mutation owner is still active") + + os.rename(basename, quarantine, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + moved = True + quarantine_fd = os.open( + quarantine, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=parent_fd, + ) + try: + moved_st = os.fstat(quarantine_fd) + if moved_st.st_dev != st.st_dev or moved_st.st_ino != st.st_ino: + raise UnsafePathError("dead Hermes mutation lock changed during quarantine") + finally: + os.close(quarantine_fd) + if os.path.exists(state_file): + raise UnsafePathError("Hermes mutation state appeared during lock recovery") + os.unlink(quarantine, dir_fd=parent_fd) + moved = False + os.fsync(parent_fd) + return True + except Exception: + if moved: + try: + os.rename( + quarantine, + basename, + src_dir_fd=parent_fd, + dst_dir_fd=parent_fd, + ) + except OSError: + # Keep the quarantined root-owned lock and propagate the + # original recovery failure; never guess at its ownership. + pass + raise + finally: + if fd is not None: + os.close(fd) + os.close(parent_fd) + + +def _mutation_lock_owner_is_live(owner: dict[str, object]) -> bool: + pid = owner.get("pid") + start_time = owner.get("pid_start_time") + if not isinstance(pid, int) or pid <= 1 or not isinstance(start_time, str): + return False + if _process_start_time(pid) != start_time: + return False + try: + status = _read_proc_file(f"/proc/{pid}/status").decode("utf-8") + cmdline = _read_proc_file(f"/proc/{pid}/cmdline").split(b"\0") + except (FileNotFoundError, PermissionError, UnicodeDecodeError): + return False + uid_line = next( + (line for line in status.splitlines() if line.startswith("Uid:")), "" + ) + try: + uids = [int(value) for value in uid_line.split()[1:]] + except ValueError: + return False + if len(uids) < 2 or uids[0] != 0 or uids[1] != 0: + return False + purpose = owner.get("purpose") + if not isinstance(purpose, str): + return False + guard_names = { + b"/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + os.path.realpath(__file__).encode("utf-8"), + } + state_guard_names = { + b"/usr/local/lib/nemoclaw/state-dir-guard.py", + os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "..", "scripts", "state-dir-guard.py") + ).encode("utf-8"), + } + if purpose.startswith("state-dir-"): + return any(argument in guard_names | state_guard_names for argument in cmdline) + if not any(argument in guard_names for argument in cmdline): + return False + return any( + action in cmdline + for action in ( + b"seal-restart", + b"write-config", + b"transition-shields", + b"begin-shields-transition", + b"apply-shields-transition", + b"finish-shields-transition", + b"prepare-shields-abort", + b"abort-shields-transition", + ) + ) + + +def inspect_mutation_owner(state_file: str, expected_token: str = "") -> str: + lock_path = os.path.join(os.path.dirname(state_file), "hermes-config-mutation.lock") + state_exists = os.path.exists(state_file) + lock_exists = os.path.exists(lock_path) + state_data: dict[str, object] | None = None + state_token = "" + if state_exists: + state_data = _load_restart_state(state_file) + candidate = state_data.get("mutation_lock_token") + if not isinstance(candidate, str): + raise UnsafePathError("refusing mutation state without a lock token") + state_token = candidate + + owner: dict[str, object] | None = None + if lock_exists: + parent_fd, owner = _read_mutation_lock(lock_path) + os.close(parent_fd) + lock_token = owner.get("token") + if not isinstance(lock_token, str): + raise UnsafePathError("refusing mutation lock without a token") + if state_token and not secrets.compare_digest(lock_token, state_token): + raise UnsafePathError("refusing mismatched Hermes mutation state and lock") + + token_match = bool( + expected_token + and state_token + and secrets.compare_digest(expected_token, state_token) + ) + original_locked = False + if state_data is not None and "files" in state_data: + original_locked = _restart_state_was_locked(state_data) + active = owner is not None and _mutation_lock_owner_is_live(owner) + if state_data is not None and str(state_data.get("phase", "")).startswith( + "shields-transition-" + ): + transition = state_data.get("shields_transition") + lease_expires_ns = ( + transition.get("lease_expires_ns") if isinstance(transition, dict) else None + ) + if isinstance(lease_expires_ns, int) and time.time_ns() < lease_expires_ns: + active = True + recovery_safe = not ( + state_data is not None + and str(state_data.get("phase", "")).startswith("shields-transition-") + ) + resumable_lock = bool( + state_data is not None + and state_data.get("phase") + in ("shields-transition-pending", "shields-transition-applied") + and isinstance(state_data.get("shields_transition"), dict) + and state_data["shields_transition"].get("mode") == "locked" + ) + return ( + f"state={int(state_exists)} lock={int(lock_exists)} " + f"owner_active={int(active)} token_match={int(token_match)} " + f"original_locked={int(original_locked)} recovery_safe={int(recovery_safe)} " + f"resumable_lock={int(resumable_lock)}" + ) + + +def _write_restart_state( + path: str, state_data: dict[str, object], *, create: bool +) -> None: + _state_file_parent_is_safe(path) + encoded = (json.dumps(state_data, sort_keys=True) + "\n").encode("utf-8") + if len(encoded) > MAX_RESTART_STATE_BYTES: + raise UnsafePathError("refusing oversized Hermes restart seal state") + if create: + _atomic_replace( + path, + encoded, + expected=None, + mode=0o600, + uid=os.geteuid(), + gid=os.getegid(), + ) + return + opened = _open_regular(path) + try: + snapshot = opened.snapshot + finally: + opened.close() + _atomic_replace( + path, + encoded, + expected=snapshot, + mode=0o600, + uid=os.geteuid(), + gid=os.getegid(), + ) + + +def _load_restart_state(path: str) -> dict[str, object]: + text, _snapshot = _read_text(path, MAX_RESTART_STATE_BYTES) + try: + value = json.loads(text) + except json.JSONDecodeError as exc: + raise UnsafePathError( + f"refusing corrupt Hermes restart seal state: {exc}" + ) from exc + if not isinstance(value, dict) or value.get("version") != 1: + raise UnsafePathError("refusing unsupported Hermes restart seal state") + return value + + +def _ensure_restart_orphan_marker(hermes_fd: int) -> None: + try: + fd = os.open( + RESTART_ORPHAN_MARKER_NAME, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | _no_follow_flag() | _cloexec_flag(), + 0o400, + dir_fd=hermes_fd, + ) + except FileExistsError: + fd = os.open( + RESTART_ORPHAN_MARKER_NAME, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + marker_st = os.fstat(fd) + if ( + not stat.S_ISREG(marker_st.st_mode) + or marker_st.st_uid != os.geteuid() + or marker_st.st_gid != os.getegid() + or stat.S_IMODE(marker_st.st_mode) != 0o400 + or marker_st.st_nlink != 1 + ): + raise UnsafePathError("refusing unsafe Hermes restart orphan marker") + finally: + os.close(fd) + return + try: + os.fchmod(fd, 0o400) + os.fchown(fd, os.geteuid(), os.getegid()) + os.fsync(fd) + finally: + os.close(fd) + os.fsync(hermes_fd) + + +def _remove_restart_orphan_marker(hermes_fd: int) -> None: + try: + os.unlink(RESTART_ORPHAN_MARKER_NAME, dir_fd=hermes_fd) + os.fsync(hermes_fd) + except FileNotFoundError: + # Removing an already-absent orphan marker is intentionally idempotent. + pass + + +def _restore_restart_seal( + state_file: str, *, verify_hash: bool, retain_transaction: bool = False +) -> bool: + if not os.path.exists(state_file): + return False + state_data = _load_restart_state(state_file) + lock_token = state_data.get("mutation_lock_token") + lock_path = state_data.get("mutation_lock_path") + if not isinstance(lock_token, str) or not isinstance(lock_path, str): + raise UnsafePathError("refusing restart unseal without a mutation lock token") + if state_data.get("phase") == "acquired": + _release_mutation_lock(lock_path, lock_token) + os.unlink(state_file) + return True + + hermes_dir = str(state_data["hermes_dir"]) + hash_file = str(state_data["hash_file"]) + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + file_fds: list[tuple[int, dict[str, object]]] = [] + try: + parent_meta = state_data["parent"] + hermes_meta = state_data["hermes"] + if not isinstance(parent_meta, dict) or not isinstance(hermes_meta, dict): + raise UnsafePathError("refusing malformed Hermes restart seal metadata") + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError( + "refusing restart unseal because the sandbox directory changed" + ) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + if not _same_inode(os.fstat(hermes_fd), hermes_meta): + raise UnsafePathError( + "refusing restart unseal because the Hermes directory changed" + ) + + if verify_hash: + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash(hash_file, os.path.join(hermes_dir, ".config-hash")) + + # Re-freeze the mutable sealed posture and clear any partially restored + # immutable flags first. This makes unseal retryable if a prior attempt + # failed after restoring one file but before completing the transaction. + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o755) + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + # Restore runs as root. Keep the config tree inaccessible to sandbox + # processes until every sealed file and directory is back in posture. + os.fchmod(hermes_fd, 0o700) + _ensure_restart_orphan_marker(hermes_fd) + + files = state_data["files"] + if not isinstance(files, dict): + raise UnsafePathError("refusing malformed Hermes restart file metadata") + for name in SEALED_FILE_NAMES: + file_state = files.get(name) + if not isinstance(file_state, dict): + raise UnsafePathError( + f"refusing missing Hermes restart metadata for {name}" + ) + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: + raise UnsafePathError(f"refusing unsafe sealed Hermes path: {name}") + sealed = file_state.get("sealed") + if isinstance(sealed, dict) and not _same_inode(st, sealed): + raise UnsafePathError( + f"refusing restart unseal because sealed {name} changed" + ) + original = file_state.get("original") + if not isinstance(original, dict): + raise UnsafePathError( + f"refusing malformed original metadata for {name}" + ) + _set_inode_flags( + fd, + _get_inode_flags(fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + file_fds.append((fd, file_state)) + fd = -1 + finally: + if fd >= 0: + os.close(fd) + + # Restore all ordinary metadata before reapplying any immutable flags. + # Parent remains frozen until the very last operation. + for fd, file_state in file_fds: + original = file_state["original"] + if not isinstance(original, dict): + raise UnsafePathError( + "refusing malformed original Hermes file metadata" + ) + os.fchown(fd, original["uid"], original["gid"]) + os.fchmod(fd, original["mode"]) + for fd, file_state in file_fds: + _set_inode_flags(fd, int(file_state.get("flags", 0))) + + # Restore the directories while the persistent root-owned marker still + # identifies this transaction. Chown can clear setgid, so chmod follows + # chown. The marker is removed only after every mode/owner/flag is exact; + # losing rootfs-local /run state at any earlier point remains detectable. + os.fchown(hermes_fd, hermes_meta["uid"], hermes_meta["gid"]) + os.fchmod(hermes_fd, hermes_meta["mode"]) + _set_inode_flags(hermes_fd, int(state_data.get("hermes_flags", 0))) + if not retain_transaction: + os.fchmod(parent_fd, parent_meta["mode"]) + _set_inode_flags(parent_fd, int(state_data.get("parent_flags", 0))) + _remove_restart_orphan_marker(hermes_fd) + # Seal rejects set-id parent modes, so this final ownership change + # cannot silently clear a mode bit. Before it succeeds, root parent + # ownership remains the durable orphan marker; afterward metadata + # is exact and no marker is needed. + os.fchown(parent_fd, parent_meta["uid"], parent_meta["gid"]) + finally: + for fd, _file_state in file_fds: + os.close(fd) + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + + if not retain_transaction: + _release_mutation_lock(lock_path, lock_token) + os.unlink(state_file) + return True + + +def seal_restart( + hermes_dir: str, + hash_file: str, + state_file: str, + purpose: str = "restart-seal", + mutation_lock_token: str | None = None, + expected_config_sha256: str | None = None, +) -> bool: + if os.path.exists(state_file): + raise UnsafePathError("Hermes restart seal is already active") + mutation_lock_token = mutation_lock_token or secrets.token_hex(32) + mutation_lock_path = os.path.join( + os.path.dirname(state_file), "hermes-config-mutation.lock" + ) + _acquire_mutation_lock(mutation_lock_path, mutation_lock_token, purpose, state_file) + state_data: dict[str, object] = { + "version": 1, + "phase": "acquired", + "mutation_lock_token": mutation_lock_token, + "mutation_lock_path": mutation_lock_path, + "hermes_dir": hermes_dir, + "hash_file": hash_file, + } + try: + _write_restart_state(state_file, state_data, create=True) + except Exception: + _release_mutation_lock(mutation_lock_path, mutation_lock_token) + raise + + state_created = True + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd: int | None = None + hermes_fd: int | None = None + try: + parent_fd = _open_directory(parent_path) + parent_meta = _inode_metadata(os.fstat(parent_fd)) + parent_flags = _get_inode_flags(parent_fd) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + hermes_meta = _inode_metadata(os.fstat(hermes_fd)) + hermes_flags = _get_inode_flags(hermes_fd) + + # `/sandbox` ownership is the durable orphan-transaction marker when + # the rootfs-local `/run` token is lost during container recreation. + # Do not clear an immutable parent before that ownership marker can be + # established, because a crash in between would be undetectable on the + # next container. NemoClaw does not use an immutable `/sandbox` parent. + if parent_flags & (FS_IMMUTABLE_FL | FS_APPEND_FL): + raise UnsafePathError( + "refusing restart seal because /sandbox has blocking inode flags" + ) + if parent_meta["mode"] & (stat.S_ISUID | stat.S_ISGID): + raise UnsafePathError( + "refusing restart seal because /sandbox has set-id mode bits" + ) + if hermes_flags & (FS_IMMUTABLE_FL | FS_APPEND_FL): + raise UnsafePathError( + "refusing restart seal because .hermes has blocking inode flags" + ) + + file_states: dict[str, dict[str, object]] = {} + for name in SEALED_FILE_NAMES: + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + st = os.fstat(fd) + _validate_regular(os.path.join(hermes_dir, name), st) + file_states[name] = { + "original": _inode_metadata(st), + "flags": _get_inode_flags(fd), + } + finally: + os.close(fd) + + # Persist recovery metadata before the first freeze mutation. A killed + # guard/PID 1 in the same container writable layer can idempotently + # restore the exact contract. If recreation loses `/run`, root ownership + # of the persistent /sandbox parent makes startup fail closed instead. + state_data.update( + { + "phase": "locking", + "parent": parent_meta, + "parent_flags": parent_flags, + "hermes": hermes_meta, + "hermes_flags": hermes_flags, + "files": file_states, + } + ) + _write_restart_state(state_file, state_data, create=False) + + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700 if purpose == "shields-mutable" else 0o755) + current_hermes = os.stat(hermes_name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_inode(current_hermes, hermes_meta): + raise UnsafePathError("refusing raced Hermes directory before restart seal") + _set_inode_flags(hermes_fd, hermes_flags & ~FS_IMMUTABLE_FL) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o755) + try: + os.stat( + RESTART_ORPHAN_MARKER_NAME, + dir_fd=hermes_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + pass + else: + raise UnsafePathError("refusing pre-existing Hermes restart orphan marker") + _ensure_restart_orphan_marker(hermes_fd) + + # The agent could rename either file between the pre-token snapshot and + # the parent freeze. Require the same inode before hashing or replacing. + for name in SEALED_FILE_NAMES: + current = os.stat(name, dir_fd=hermes_fd, follow_symlinks=False) + original = file_states[name]["original"] + if not isinstance(original, dict) or not _same_inode(current, original): + raise UnsafePathError(f"refusing raced Hermes restart path: {name}") + + # Validate before creating replacement inodes. On mismatch the recovery + # token restores both directory modes and leaves file paths untouched. + compat_hash_path = os.path.join(hermes_dir, ".config-hash") + try: + _verify_strict_hash(hermes_dir, hash_file) + except StrictHashMismatchError: + if purpose != "config-write" or expected_config_sha256 is None: + raise + _reconcile_nonroot_startup_api_key_hash( + hermes_dir, + hash_file, + expected_config_sha256, + hermes_meta, + file_states, + ) + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash(hash_file, compat_hash_path) + + for name in SEALED_FILE_NAMES: + path = os.path.join(hermes_dir, name) + opened = _open_regular(path) + try: + flags = int(file_states[name]["flags"]) + _set_inode_flags(opened.fd, flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL)) + finally: + opened.close() + text, snapshot = _read_text(path, _sealed_file_limit(name)) + if name == ".config-hash": + strict_hash_text = _read_hash_file(hash_file) + if text != strict_hash_text: + raise UnsafePathError( + "compat hash changed during Hermes restart seal" + ) + # Publish trusted anchor bytes, not bytes copied from a path for + # which a sandbox process may retain a pre-seal descriptor. + text = strict_hash_text + file_states[name]["trusted_base64"] = base64.b64encode( + text.encode("utf-8") + ).decode("ascii") + _atomic_replace( + path, + text.encode("utf-8"), + expected=snapshot, + mode=0o444, + uid=os.geteuid(), + gid=os.getegid(), + ) + sealed_st = os.stat(name, dir_fd=hermes_fd, follow_symlinks=False) + if not stat.S_ISREG(sealed_st.st_mode) or sealed_st.st_nlink != 1: + raise UnsafePathError(f"refusing unsafe sealed Hermes path: {name}") + file_states[name]["sealed"] = _inode_metadata(sealed_st) + + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash(hash_file, compat_hash_path) + state_data["phase"] = "sealed" + state_data["files"] = file_states + _write_restart_state(state_file, state_data, create=False) + + # Mutable Hermes normally needs to create top-level runtime state while + # a short restart seal is active. A shields transition is different: + # the host is about to mutate a recursive state tree, so never reopen a + # writable root between seal_restart() returning and begin publishing + # its pending phase. + if purpose == "shields-mutable": + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o700) + elif purpose == "shields-locked": + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o755) + elif hermes_meta["uid"] != os.geteuid() or hermes_meta["mode"] & 0o022: + os.fchown(hermes_fd, os.geteuid(), hermes_meta["gid"]) + os.fchmod(hermes_fd, 0o3770) + except Exception: + if state_created: + try: + _restore_restart_seal(state_file, verify_hash=False) + except Exception: + # Preserve the frozen root-owned state for explicit recovery + # and propagate the original seal failure. + pass + raise + finally: + if hermes_fd is not None: + os.close(hermes_fd) + if parent_fd is not None: + os.close(parent_fd) + return _restart_state_was_locked(state_data) + + +def unseal_restart(hermes_dir: str, state_file: str) -> None: + if not os.path.exists(state_file): + return + state_data = _load_restart_state(state_file) + if os.path.normpath(str(state_data.get("hermes_dir", ""))) != os.path.normpath( + hermes_dir + ): + raise UnsafePathError( + "refusing restart unseal for a different Hermes directory" + ) + if str(state_data.get("phase", "")).startswith("config-write"): + _recover_config_write_transaction(hermes_dir, state_file) + _restore_restart_seal(state_file, verify_hash=True) + + +def _record_current_sealed_inodes( + state_file: str, hermes_dir: str, names: tuple[str, ...] +) -> None: + state_data = _load_restart_state(state_file) + files = state_data.get("files") + if not isinstance(files, dict): + raise UnsafePathError("refusing malformed Hermes restart file metadata") + # Resolve through an opened directory so state publication cannot be + # redirected through a pathname swap. + hermes_fd = _open_directory(hermes_dir) + try: + for name in names: + file_state = files.get(name) + if not isinstance(file_state, dict): + raise UnsafePathError( + f"refusing missing Hermes restart metadata for {name}" + ) + current_st = os.stat(name, dir_fd=hermes_fd, follow_symlinks=False) + if not stat.S_ISREG(current_st.st_mode) or current_st.st_nlink != 1: + raise UnsafePathError(f"refusing unsafe sealed Hermes path: {name}") + file_state["sealed"] = _inode_metadata(current_st) + finally: + os.close(hermes_fd) + state_data["files"] = files + _write_restart_state(state_file, state_data, create=False) + + +def _restart_state_was_locked(state_data: dict[str, object]) -> bool: + recorded = state_data.get("original_locked") + if isinstance(recorded, bool): + return recorded + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if not isinstance(hermes_meta, dict) or not isinstance(files, dict): + raise UnsafePathError("refusing malformed Hermes restart seal metadata") + if ( + hermes_meta.get("uid") != os.geteuid() + or hermes_meta.get("gid") != os.getegid() + or hermes_meta.get("mode") != 0o755 + ): + return False + for name in ("config.yaml", ".env"): + file_state = files.get(name) + original = file_state.get("original") if isinstance(file_state, dict) else None + if not isinstance(original, dict): + raise UnsafePathError( + f"refusing missing Hermes restart metadata for {name}" + ) + if original.get("uid") != os.geteuid() or original.get("mode") != 0o444: + return False + return True + + +def _make_private_quarantine(parent_fd: int) -> tuple[int, str]: + name = f".nemoclaw-hermes-quarantine.{os.getpid()}.{secrets.token_hex(8)}" + os.mkdir(name, 0o700, dir_fd=parent_fd) + fd = _open_child_directory(parent_fd, name, name) + try: + os.fchown(fd, os.geteuid(), os.getegid()) + os.fchmod(fd, 0o700) + except Exception: + os.close(fd) + raise + return fd, name + + +def _quarantine_entry(parent_fd: int, name: str) -> None: + quarantine_fd, _quarantine_name = _make_private_quarantine(parent_fd) + try: + os.rename( + name, + f"entry.{secrets.token_hex(8)}", + src_dir_fd=parent_fd, + dst_dir_fd=quarantine_fd, + ) + os.fsync(quarantine_fd) + os.fsync(parent_fd) + finally: + os.close(quarantine_fd) + + +def _clear_entry_mutation_flags(parent_fd: int, name: str) -> None: + try: + fd = os.open( + name, + os.O_RDONLY + | os.O_NONBLOCK + | _no_follow_flag() + | _cloexec_flag(), + dir_fd=parent_fd, + ) + except OSError as exc: + if exc.errno in (errno.ELOOP, errno.ENOENT, errno.ENXIO): + return + raise + try: + flags = _get_inode_flags(fd) + _set_inode_flags(fd, flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL)) + finally: + os.close(fd) + + +def _fresh_replace_at( + parent_fd: int, + name: str, + data: bytes, + *, + mode: int, +) -> os.stat_result: + temp_name = f".{name}.nemoclaw.{os.getpid()}.{secrets.token_hex(8)}" + temp_fd = os.open( + temp_name, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | _no_follow_flag() + | _cloexec_flag(), + 0o600, + dir_fd=parent_fd, + ) + published = False + try: + os.fchown(temp_fd, os.geteuid(), os.getegid()) + os.fchmod(temp_fd, mode) + view = memoryview(data) + while view: + written = os.write(temp_fd, view) + if written <= 0: + raise OSError(errno.EIO, f"short write while sealing {name}") + view = view[written:] + os.fsync(temp_fd) + os.close(temp_fd) + temp_fd = -1 + + try: + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + current = None + if current is not None: + if stat.S_ISDIR(current.st_mode): + _clear_entry_mutation_flags(parent_fd, name) + _quarantine_entry(parent_fd, name) + else: + _clear_entry_mutation_flags(parent_fd, name) + os.replace(temp_name, name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + published = True + os.fsync(parent_fd) + replacement = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(replacement.st_mode) + or replacement.st_nlink != 1 + or replacement.st_uid != os.geteuid() + or replacement.st_gid != os.getegid() + or stat.S_IMODE(replacement.st_mode) != mode + ): + raise UnsafePathError(f"fresh Hermes seal verification failed for {name}") + return replacement + finally: + if temp_fd >= 0: + os.close(temp_fd) + if not published: + try: + os.unlink(temp_name, dir_fd=parent_fd) + except FileNotFoundError: + pass + + +def _read_hardening_input( + hermes_fd: int, name: str, hermes_dev: int +) -> tuple[bytes | None, os.stat_result | None, str | None]: + path = f"Hermes {name}" + try: + fd = os.open( + name, + os.O_RDONLY + | os.O_NONBLOCK + | _no_follow_flag() + | _cloexec_flag(), + dir_fd=hermes_fd, + ) + except FileNotFoundError: + return None, None, f"{path} is missing" + except OSError as exc: + return None, None, f"{path} is unsafe: {exc}" + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + return None, st, f"{path} is not a regular file" + if st.st_dev != hermes_dev: + return None, st, f"{path} crosses a filesystem boundary" + snapshot = FileSnapshot.from_stat(st) + opened = OpenFile(path, fd, snapshot) + try: + data = opened.read_bytes(_sealed_file_limit(name)) + except UnsafePathError as exc: + return None, st, str(exc) + return data, st, None + finally: + os.close(fd) + + +def _seal_shields_locked( + hermes_dir: str, + hash_file: str, + state_file: str, + rollback_mode: str, +) -> tuple[str, bool]: + """Monotonically contain a mutable Hermes namespace. + + Unlike restart/config-write preflight, deadline hardening never grants a + mutable file, stale digest, or hostile entry veto power over containment. + It freezes the outer namespace first, then either publishes fresh bounded + inputs or leaves a root-only unavailable posture. + """ + + if os.path.exists(state_file): + raise UnsafePathError("Hermes restart seal is already active") + lock_token = secrets.token_hex(32) + lock_path = os.path.join( + os.path.dirname(state_file), "hermes-config-mutation.lock" + ) + _acquire_mutation_lock(lock_path, lock_token, "shields-locked", state_file) + state_data: dict[str, object] = { + "version": 1, + "phase": "acquired", + "mutation_lock_token": lock_token, + "mutation_lock_path": lock_path, + "hermes_dir": hermes_dir, + "hash_file": hash_file, + } + try: + _write_restart_state(state_file, state_data, create=True) + except Exception: + _release_mutation_lock(lock_path, lock_token) + raise + + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + parent_st = os.fstat(parent_fd) + parent_meta = _inode_metadata(parent_st) + parent_flags = _get_inode_flags(parent_fd) + state_data.update( + { + "phase": "shields-transition-hardening", + "parent": parent_meta, + "parent_flags": parent_flags, + "shields_transition": { + "mode": "locked", + "rollback_mode": rollback_mode, + "lease_expires_ns": time.time_ns() + + SHIELDS_TRANSITION_LEASE_SECONDS * 1_000_000_000, + }, + } + ) + _write_restart_state(state_file, state_data, create=False) + + # This is the outer namespace containment boundary. No .hermes lookup + # occurs until pre-open directory descriptors lose sandbox write access. + _set_inode_flags( + parent_fd, parent_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + os.fsync(parent_fd) + + unavailable_reasons: list[str] = [] + original_locked = False + try: + hermes_lstat = os.stat( + hermes_name, dir_fd=parent_fd, follow_symlinks=False + ) + except FileNotFoundError: + hermes_lstat = None + + if hermes_lstat is not None and stat.S_ISDIR(hermes_lstat.st_mode): + if hermes_lstat.st_dev != parent_st.st_dev: + state_data["phase"] = "shields-transition-cross-device" + _write_restart_state(state_file, state_data, create=False) + raise UnsafePathError( + "refusing cross-device Hermes config root; /sandbox remains frozen" + ) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + else: + if hermes_lstat is not None: + unavailable_reasons.append("Hermes config root was not a directory") + _clear_entry_mutation_flags(parent_fd, hermes_name) + _quarantine_entry(parent_fd, hermes_name) + else: + unavailable_reasons.append("Hermes config root was missing") + os.mkdir(hermes_name, 0o700, dir_fd=parent_fd) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o700) + + hermes_st = os.fstat(hermes_fd) + if hermes_st.st_dev != parent_st.st_dev: + state_data["phase"] = "shields-transition-cross-device" + _write_restart_state(state_file, state_data, create=False) + raise UnsafePathError( + "refusing cross-device Hermes config root; /sandbox remains frozen" + ) + hermes_meta = _inode_metadata(hermes_st) + hermes_flags = _get_inode_flags(hermes_fd) + _set_inode_flags( + hermes_fd, hermes_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o700) + + inputs: dict[str, bytes] = {} + initial_stats: dict[str, os.stat_result | None] = {} + for name in ("config.yaml", ".env"): + data, input_st, reason = _read_hardening_input( + hermes_fd, name, hermes_st.st_dev + ) + initial_stats[name] = input_st + if reason is not None or data is None: + unavailable_reasons.append(reason or f"Hermes {name} is unavailable") + inputs[name] = b"NEMOCLAW_HERMES_CONFIG_UNAVAILABLE\n" + else: + inputs[name] = data + + original_locked = ( + not unavailable_reasons + and hermes_meta["uid"] == os.geteuid() + and hermes_meta["gid"] == os.getegid() + and hermes_meta["mode"] == 0o755 + and all( + initial_stats[name] is not None + and initial_stats[name].st_uid == os.geteuid() + and initial_stats[name].st_gid == os.getegid() + and stat.S_IMODE(initial_stats[name].st_mode) == 0o444 + and initial_stats[name].st_nlink == 1 + for name in ("config.yaml", ".env") + ) + ) + unavailable = bool(unavailable_reasons) + file_mode = 0o400 if unavailable else 0o444 + hash_text = ( + f"{hashlib.sha256(inputs['config.yaml']).hexdigest()} " + f"{os.path.join(hermes_dir, 'config.yaml')}\n" + f"{hashlib.sha256(inputs['.env']).hexdigest()} " + f"{os.path.join(hermes_dir, '.env')}\n" + ) + if len(hash_text.encode("utf-8")) > MAX_HASH_BYTES: + raise UnsafePathError("refusing oversized synthesized Hermes hash") + + file_states: dict[str, dict[str, object]] = {} + for name in ("config.yaml", ".env"): + replacement = _fresh_replace_at( + hermes_fd, name, inputs[name], mode=file_mode + ) + file_states[name] = { + "original": _inode_metadata(replacement), + "sealed": _inode_metadata(replacement), + "flags": 0, + } + + compat_bytes = hash_text.encode("utf-8") + compat_st = _fresh_replace_at( + hermes_fd, ".config-hash", compat_bytes, mode=file_mode + ) + file_states[".config-hash"] = { + "original": _inode_metadata(compat_st), + "sealed": _inode_metadata(compat_st), + "flags": 0, + } + _write_hash(hash_file, hash_text) + _fresh_replace_at( + hermes_fd, RESTART_ORPHAN_MARKER_NAME, b"", mode=0o400 + ) + + state_data.update( + { + "phase": "shields-transition-pending", + "parent": parent_meta, + "parent_flags": parent_flags, + "hermes": hermes_meta, + "hermes_flags": hermes_flags, + "files": file_states, + "original_locked": original_locked, + } + ) + transition = state_data["shields_transition"] + if not isinstance(transition, dict): + raise UnsafePathError("refusing malformed Hermes hardening transition") + transition["original_locked"] = original_locked + transition["unavailable"] = unavailable + transition["unavailable_reasons"] = unavailable_reasons + state_data["shields_transition"] = transition + _write_restart_state(state_file, state_data, create=False) + + # The recursive state guard recognizes this root-only 0500 clamp and + # may restore 0755 only after its independent verification pass. + os.fchmod(hermes_fd, 0o500) + os.fsync(hermes_fd) + return lock_token, original_locked + finally: + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + + +def _resume_shields_locked( + hermes_dir: str, + hash_file: str, + state_file: str, +) -> tuple[str, bool] | None: + if not os.path.exists(state_file): + return None + state_data = _load_restart_state(state_file) + transition = state_data.get("shields_transition") + if ( + state_data.get("phase") + not in ("shields-transition-pending", "shields-transition-applied") + or not isinstance(transition, dict) + or transition.get("mode") != "locked" + ): + raise UnsafePathError( + "Hermes config mutation is already sealed in a non-resumable phase" + ) + if os.path.normpath(str(state_data.get("hermes_dir", ""))) != os.path.normpath( + hermes_dir + ) or os.path.normpath(str(state_data.get("hash_file", ""))) != os.path.normpath( + hash_file + ): + raise UnsafePathError("refusing to resume a different Hermes transition") + token = state_data.get("mutation_lock_token") + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if ( + not isinstance(token, str) + or not re.fullmatch(r"[0-9a-f]{64}", token) + or not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or not isinstance(files, dict) + ): + raise UnsafePathError("refusing malformed resumable Hermes transition") + + # A resumed begin must atomically replace the dead prior owner before it + # mutates the clamped namespace. Otherwise two recovery callers can both + # observe the same dead worker and race the recursive pass. + state_data = _claim_transition_worker( + state_file, token, "begin-shields-transition" + ) + transition = state_data.get("shields_transition") + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if ( + not isinstance(transition, dict) + or transition.get("mode") != "locked" + or not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or not isinstance(files, dict) + ): + raise UnsafePathError("refusing raced resumable Hermes transition") + + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError("refusing resume because /sandbox changed") + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + if not _same_inode(os.fstat(hermes_fd), hermes_meta): + raise UnsafePathError("refusing resume because .hermes changed") + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o500) + _ensure_restart_orphan_marker(hermes_fd) + expected_mode = 0o400 if transition.get("unavailable") is True else 0o444 + for name in SEALED_FILE_NAMES: + file_state = files.get(name) + sealed = file_state.get("sealed") if isinstance(file_state, dict) else None + if not isinstance(sealed, dict): + raise UnsafePathError( + f"refusing resume without sealed metadata for {name}" + ) + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + current = os.fstat(fd) + if ( + not stat.S_ISREG(current.st_mode) + or current.st_nlink != 1 + or not _same_inode(current, sealed) + or current.st_uid != os.geteuid() + or current.st_gid != os.getegid() + or stat.S_IMODE(current.st_mode) != expected_mode + ): + raise UnsafePathError( + f"refusing resume because sealed {name} changed" + ) + finally: + os.close(fd) + if transition.get("unavailable") is not True: + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash( + hash_file, os.path.join(hermes_dir, ".config-hash") + ) + transition["lease_expires_ns"] = ( + time.time_ns() + SHIELDS_TRANSITION_LEASE_SECONDS * 1_000_000_000 + ) + state_data["shields_transition"] = transition + _write_restart_state(state_file, state_data, create=False) + os.fsync(hermes_fd) + os.fsync(parent_fd) + finally: + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + return token, _restart_state_was_locked(state_data) + + +def _takeover_expired_mutable_transition( + hermes_dir: str, hash_file: str, state_file: str +) -> bool: + if not os.path.exists(state_file): + return False + state_data = _load_restart_state(state_file) + transition = state_data.get("shields_transition") + if not isinstance(transition, dict) or transition.get("mode") != "mutable": + return False + if state_data.get("phase") not in ( + "shields-transition-pending", + "shields-transition-applied", + ): + raise UnsafePathError( + "mutable Hermes transition is sealed in a non-takeover phase" + ) + if os.path.normpath(str(state_data.get("hermes_dir", ""))) != os.path.normpath( + hermes_dir + ) or os.path.normpath(str(state_data.get("hash_file", ""))) != os.path.normpath( + hash_file + ): + raise UnsafePathError("refusing takeover of a different Hermes transition") + token = state_data.get("mutation_lock_token") + lock_path = state_data.get("mutation_lock_path") + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + if ( + not isinstance(token, str) + or not re.fullmatch(r"[0-9a-f]{64}", token) + or not isinstance(lock_path, str) + or not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + ): + raise UnsafePathError("refusing malformed mutable transition takeover") + lock_parent_fd, owner = _read_mutation_lock(lock_path) + os.close(lock_parent_fd) + owner_token = owner.get("token") + if not isinstance(owner_token, str) or not secrets.compare_digest( + owner_token, token + ): + raise UnsafePathError("refusing mutable takeover with mismatched owner token") + if _mutation_lock_owner_is_live(owner): + raise UnsafePathError( + "Hermes mutable transition worker is still active; retry locked takeover" + ) + lease_expires_ns = transition.get("lease_expires_ns") + if not isinstance(lease_expires_ns, int) or time.time_ns() < lease_expires_ns: + raise UnsafePathError( + "Hermes mutable transition lease has not expired; retry locked takeover" + ) + + # Take ownership with a compare-and-replace of the exact dead lock inode + # before freezing anything. A delayed state-dir worker using the old token + # must either win this claim first (and remain live) or lose without being + # able to race the fresh locked namespace. + state_data = _claim_transition_worker( + state_file, token, "begin-shields-transition" + ) + transition = state_data.get("shields_transition") + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + if ( + state_data.get("phase") + not in ("shields-transition-pending", "shields-transition-applied") + or not isinstance(transition, dict) + or transition.get("mode") != "mutable" + or not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or os.path.normpath(str(state_data.get("hermes_dir", ""))) + != os.path.normpath(hermes_dir) + or os.path.normpath(str(state_data.get("hash_file", ""))) + != os.path.normpath(hash_file) + ): + raise UnsafePathError("refusing raced mutable transition takeover") + + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + parent_st = os.fstat(parent_fd) + if not _same_inode(parent_st, parent_meta): + raise UnsafePathError("refusing mutable takeover because /sandbox changed") + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + hermes_st = os.fstat(hermes_fd) + if not _same_inode(hermes_st, hermes_meta): + raise UnsafePathError("refusing mutable takeover because .hermes changed") + if hermes_st.st_dev != parent_st.st_dev: + raise UnsafePathError( + "refusing cross-device mutable transition takeover" + ) + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o700) + os.fsync(hermes_fd) + os.fsync(parent_fd) + finally: + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + + # The namespace is now monotonically root-only. Remove the obsolete state + # first; a kill before lock release becomes the safe pre-state-lock recovery + # case, and a kill afterward remains recognizable by the persistent marker. + os.unlink(state_file) + _release_mutation_lock(lock_path, token) + return True + + +def begin_shields_transition( + hermes_dir: str, + hash_file: str, + state_file: str, + mode: str, + rollback_mode: str = "", +) -> tuple[str, bool]: + if mode not in ("locked", "mutable"): + raise UnsafePathError(f"refusing unsupported Hermes shields transition: {mode}") + if rollback_mode and rollback_mode not in ("locked", "mutable"): + raise UnsafePathError( + f"refusing unsupported Hermes shields rollback posture: {rollback_mode}" + ) + + if mode == "locked": + if _takeover_expired_mutable_transition( + hermes_dir, hash_file, state_file + ): + return _seal_shields_locked( + hermes_dir, + hash_file, + state_file, + rollback_mode or "mutable", + ) + resumed = _resume_shields_locked(hermes_dir, hash_file, state_file) + if resumed is not None: + return resumed + return _seal_shields_locked( + hermes_dir, + hash_file, + state_file, + rollback_mode or "mutable", + ) + + original_locked = seal_restart( + hermes_dir, hash_file, state_file, purpose="shields-mutable" + ) + try: + state_data = _load_restart_state(state_file) + lock_token = state_data.get("mutation_lock_token") + if not isinstance(lock_token, str): + raise UnsafePathError( + "refusing malformed Hermes shields transition metadata" + ) + + # A mutable target weakens nested state directories, so keep the config + # root inaccessible throughout that fan-out: 0755 would expose a + # partially unlocked tree if the host were killed mid-pass. A locked + # target is monotonic hardening and can remain readable by the gateway. + # The exact original/desired metadata remains in the root-only state. + hermes_fd = _open_directory(hermes_dir) + try: + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o700 if mode == "mutable" else 0o755) + finally: + os.close(hermes_fd) + + state_data["phase"] = "shields-transition-pending" + state_data["shields_transition"] = { + "mode": mode, + "original_locked": original_locked, + "rollback_mode": rollback_mode + or ("locked" if original_locked else "mutable"), + "lease_expires_ns": time.time_ns() + + SHIELDS_TRANSITION_LEASE_SECONDS * 1_000_000_000, + } + _write_restart_state(state_file, state_data, create=False) + return lock_token, original_locked + except Exception: + try: + unseal_restart(hermes_dir, state_file) + except Exception: + # Retain the root-owned token and frozen tree for PID 1 recovery; + # the original transition failure remains authoritative. + pass + raise + + +def _load_owned_shields_transition( + state_file: str, lock_token: str, phases: tuple[str, ...] +) -> tuple[dict[str, object], dict[str, object], str]: + state_data = _load_restart_state(state_file) + recorded_token = state_data.get("mutation_lock_token") + transition = state_data.get("shields_transition") + if ( + state_data.get("phase") not in phases + or not isinstance(recorded_token, str) + or not isinstance(transition, dict) + ): + raise UnsafePathError("refusing operation without an owned shields transition") + if not secrets.compare_digest(recorded_token, lock_token): + raise UnsafePathError("refusing shields transition lock token mismatch") + mode = transition.get("mode") + if mode not in ("locked", "mutable"): + raise UnsafePathError("refusing malformed Hermes shields transition mode") + return state_data, transition, str(mode) + + +def _sandbox_identity() -> tuple[int, int]: + if os.geteuid() != 0: + # Unit fixtures and rootless fallbacks can only use their own identity. + return os.geteuid(), os.getegid() + try: + return pwd.getpwnam("sandbox").pw_uid, grp.getgrnam("sandbox").gr_gid + except KeyError as exc: + raise UnsafePathError("sandbox account lookup failed") from exc + + +def _configure_shields_target_metadata( + state_data: dict[str, object], + transition: dict[str, object], + hermes_dir: str, + mode: str, + *, + capture_original: bool, +) -> bool: + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if ( + not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or not isinstance(files, dict) + ): + raise UnsafePathError("refusing malformed Hermes shields transition metadata") + + if capture_original: + transition["original_metadata"] = { + "parent": copy.deepcopy(parent_meta), + "parent_flags": state_data.get("parent_flags", 0), + "hermes": copy.deepcopy(hermes_meta), + "hermes_flags": state_data.get("hermes_flags", 0), + "files": { + name: { + "original": copy.deepcopy(files[name]["original"]), + "flags": files[name].get("flags", 0), + } + for name in SEALED_FILE_NAMES + if isinstance(files.get(name), dict) + and isinstance(files[name].get("original"), dict) + }, + } + original_metadata = transition["original_metadata"] + original_files = ( + original_metadata.get("files") + if isinstance(original_metadata, dict) + else None + ) + if not isinstance(original_files, dict) or len(original_files) != len( + SEALED_FILE_NAMES + ): + raise UnsafePathError( + "refusing incomplete Hermes shields rollback metadata" + ) + + sandbox_uid, sandbox_gid = _sandbox_identity() + if mode == "locked": + desired_uid = os.geteuid() + desired_gid = os.getegid() + desired_dir_mode = 0o755 + desired_file_mode = 0o444 + # `/sandbox` must remain a usable home, but its sticky root-owned entry + # prevents the sandbox identity from renaming the root-owned `.hermes` + # lock root out from under the protected files. + parent_meta.update({"uid": os.geteuid(), "gid": sandbox_gid, "mode": 0o1775}) + elif mode == "mutable": + desired_uid = sandbox_uid + desired_gid = sandbox_gid + desired_dir_mode = 0o3770 + desired_file_mode = 0o640 + parent_meta.update({"uid": sandbox_uid, "gid": sandbox_gid, "mode": 0o755}) + else: + raise UnsafePathError(f"refusing unsupported Hermes shields target: {mode}") + + state_data["parent"] = parent_meta + state_data["parent_flags"] = int(state_data.get("parent_flags", 0)) & ~( + FS_IMMUTABLE_FL | FS_APPEND_FL + ) + hermes_meta.update( + {"uid": desired_uid, "gid": desired_gid, "mode": desired_dir_mode} + ) + state_data["hermes"] = hermes_meta + state_data["hermes_flags"] = int(state_data.get("hermes_flags", 0)) & ~( + FS_IMMUTABLE_FL | FS_APPEND_FL + ) + + chattr_applied = mode == "locked" + hermes_fd = _open_directory(hermes_dir) + try: + for name in SEALED_FILE_NAMES: + file_state = files.get(name) + original = ( + file_state.get("original") if isinstance(file_state, dict) else None + ) + if not isinstance(file_state, dict) or not isinstance(original, dict): + raise UnsafePathError( + f"refusing missing Hermes shields transition metadata for {name}" + ) + original.update( + {"uid": desired_uid, "gid": desired_gid, "mode": desired_file_mode} + ) + file_state["original"] = original + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + current_flags = _get_inode_flags(fd) + desired_flags = current_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + if mode == "locked": + try: + _set_inode_flags(fd, desired_flags | FS_IMMUTABLE_FL) + desired_flags = _get_inode_flags(fd) + except (OSError, UnsafePathError): + chattr_applied = False + desired_flags = _get_inode_flags(fd) & ~FS_IMMUTABLE_FL + file_state["flags"] = desired_flags + finally: + os.close(fd) + finally: + os.close(hermes_fd) + + state_data["files"] = files + transition["chattr_applied"] = chattr_applied + state_data["shields_transition"] = transition + return chattr_applied + + +def _enforce_unavailable_shields_posture( + state_data: dict[str, object], hermes_dir: str +) -> None: + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + if not isinstance(parent_meta, dict) or not isinstance(hermes_meta, dict): + raise UnsafePathError("refusing malformed Hermes unavailable metadata") + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError( + "refusing unavailable clamp because /sandbox changed" + ) + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + if not _same_inode(os.fstat(hermes_fd), hermes_meta): + raise UnsafePathError( + "refusing unavailable clamp because .hermes changed" + ) + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + os.fchmod(hermes_fd, 0o500) + for name in SEALED_FILE_NAMES: + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: + raise UnsafePathError( + f"refusing unsafe unavailable Hermes path: {name}" + ) + _set_inode_flags( + fd, + _get_inode_flags(fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(fd, os.geteuid(), os.getegid()) + os.fchmod(fd, 0o400) + finally: + os.close(fd) + os.fsync(hermes_fd) + os.fsync(parent_fd) + finally: + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + + +def apply_shields_transition( + hermes_dir: str, state_file: str, lock_token: str +) -> tuple[str, bool]: + _claim_transition_worker(state_file, lock_token, "apply-shields-transition") + state_data, transition, mode = _load_owned_shields_transition( + state_file, + lock_token, + ("shields-transition-pending", "shields-transition-applied"), + ) + if mode == "locked" and transition.get("unavailable") is True: + _enforce_unavailable_shields_posture(state_data, hermes_dir) + reasons = transition.get("unavailable_reasons") + detail = "; ".join(str(value) for value in reasons) if isinstance(reasons, list) else "unsafe Hermes config entries" + raise UnsafePathError( + "Hermes config was sealed root-only and is unavailable: " + detail + ) + if mode == "locked": + hermes_fd = _open_directory(hermes_dir) + try: + hermes_st = os.fstat(hermes_fd) + if ( + hermes_st.st_uid == os.geteuid() + and hermes_st.st_gid == os.getegid() + and stat.S_IMODE(hermes_st.st_mode) == 0o500 + ): + raise UnsafePathError( + "Hermes recursive shields lock has not completed; retaining root-only 0500 clamp for retry" + ) + finally: + os.close(hermes_fd) + if state_data.get("phase") == "shields-transition-applied": + parent_meta = state_data.get("parent") + if not isinstance(parent_meta, dict): + raise UnsafePathError("refusing applied shields resume without parent metadata") + parent_fd = _open_directory(_split_path(hermes_dir)[0]) + try: + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError( + "refusing applied shields resume because /sandbox changed" + ) + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o755) + finally: + os.close(parent_fd) + hash_file = str(state_data.get("hash_file", "")) + if not hash_file: + raise UnsafePathError("refusing applied shields resume without hash path") + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash( + hash_file, os.path.join(hermes_dir, ".config-hash") + ) + transition["lease_expires_ns"] = ( + time.time_ns() + SHIELDS_TRANSITION_LEASE_SECONDS * 1_000_000_000 + ) + state_data["shields_transition"] = transition + _write_restart_state(state_file, state_data, create=False) + return mode, transition.get("chattr_applied") is True + chattr_applied = _configure_shields_target_metadata( + state_data, + transition, + hermes_dir, + mode, + capture_original=True, + ) + transition["lease_expires_ns"] = ( + time.time_ns() + SHIELDS_TRANSITION_LEASE_SECONDS * 1_000_000_000 + ) + state_data["shields_transition"] = transition + state_data["phase"] = "shields-transition-applied" + _write_restart_state(state_file, state_data, create=False) + _restore_restart_seal(state_file, verify_hash=True, retain_transaction=True) + return mode, chattr_applied + + +def _replace_applied_mutable_inodes( + state_data: dict[str, object], hermes_dir: str, hash_file: str +) -> None: + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if ( + not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or not isinstance(files, dict) + ): + raise UnsafePathError("refusing malformed Hermes mutable rollback metadata") + + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError( + "refusing mutable rollback because the sandbox directory changed" + ) + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + if not _same_inode(os.fstat(hermes_fd), hermes_meta): + raise UnsafePathError( + "refusing mutable rollback because the Hermes directory changed" + ) + + # Revoke the sandbox identity's directory mutation authority before + # inspecting names. Fresh replacement inodes below invalidate every + # writable descriptor opened after `apply mutable`. + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + # Host state-dir rollback runs as root. Keep the tree inaccessible to + # sandbox processes until that rollback is complete and abort commits. + os.fchmod(hermes_fd, 0o700) + + for name in SEALED_FILE_NAMES: + file_state = files.get(name) + trusted_text = ( + file_state.get("trusted_base64") + if isinstance(file_state, dict) + else None + ) + if not isinstance(file_state, dict) or not isinstance(trusted_text, str): + raise UnsafePathError( + f"refusing mutable rollback without trusted bytes for {name}" + ) + trusted = _decode_bounded_base64( + trusted_text, + _sealed_file_limit(name), + f"trusted rollback bytes for {name}", + ) + path = os.path.join(hermes_dir, name) + opened = _open_regular(path) + try: + _set_inode_flags( + opened.fd, + _get_inode_flags(opened.fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + snapshot = FileSnapshot.from_stat(os.fstat(opened.fd)) + finally: + opened.close() + _atomic_replace( + path, + trusted, + expected=snapshot, + mode=0o444, + uid=os.geteuid(), + gid=os.getegid(), + ) + replacement = os.stat(name, dir_fd=hermes_fd, follow_symlinks=False) + if not stat.S_ISREG(replacement.st_mode) or replacement.st_nlink != 1: + raise UnsafePathError(f"refusing unsafe rollback replacement: {name}") + file_state["sealed"] = _inode_metadata(replacement) -def _open_regular(path: str, mode: int = os.O_RDONLY) -> OpenFile: - dir_fd, basename = _open_parent_dir(path) - try: - flags = mode | _no_follow_flag() | _cloexec_flag() - fd = os.open(basename, flags, dir_fd=dir_fd) - try: - snapshot = _validate_regular(path, os.fstat(fd)) - except Exception: - os.close(fd) - raise - return OpenFile(path, fd, snapshot) + state_data["files"] = files + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash(hash_file, os.path.join(hermes_dir, ".config-hash")) finally: - os.close(dir_fd) + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) -def _stat_path_at(dir_fd: int, basename: str) -> os.stat_result: - return os.stat(basename, dir_fd=dir_fd, follow_symlinks=False) +def _freeze_shields_directories(state_data: dict[str, object], hermes_dir: str) -> None: + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + if not isinstance(parent_meta, dict) or not isinstance(hermes_meta, dict): + raise UnsafePathError("refusing malformed Hermes rollback directory metadata") + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + if not _same_inode(os.fstat(parent_fd), parent_meta): + raise UnsafePathError( + "refusing rollback freeze because the sandbox directory changed" + ) + _set_inode_flags( + parent_fd, + _get_inode_flags(parent_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(parent_fd, os.geteuid(), os.getegid()) + os.fchmod(parent_fd, 0o700) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + if not _same_inode(os.fstat(hermes_fd), hermes_meta): + raise UnsafePathError( + "refusing rollback freeze because the Hermes directory changed" + ) + _set_inode_flags( + hermes_fd, + _get_inode_flags(hermes_fd) & ~(FS_IMMUTABLE_FL | FS_APPEND_FL), + ) + os.fchown(hermes_fd, os.geteuid(), os.getegid()) + # Host state-dir rollback runs as root. Keep the tree inaccessible to + # sandbox processes until that rollback is complete and abort commits. + os.fchmod(hermes_fd, 0o700) + finally: + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) -def _same_snapshot(st: os.stat_result, snapshot: FileSnapshot) -> bool: - return ( - st.st_dev == snapshot.dev - and st.st_ino == snapshot.ino - and stat.S_IMODE(st.st_mode) == snapshot.mode - and st.st_uid == snapshot.uid - and st.st_gid == snapshot.gid - and st.st_nlink == snapshot.nlink - and stat.S_ISREG(st.st_mode) - ) +def finish_shields_transition( + hermes_dir: str, hash_file: str, state_file: str, lock_token: str +) -> tuple[str, bool]: + _claim_transition_worker(state_file, lock_token, "finish-shields-transition") + state_data, transition, mode = _load_owned_shields_transition( + state_file, lock_token, ("shields-transition-applied",) + ) + parent_meta = state_data.get("parent") + hermes_meta = state_data.get("hermes") + files = state_data.get("files") + if ( + not isinstance(parent_meta, dict) + or not isinstance(hermes_meta, dict) + or not isinstance(files, dict) + ): + raise UnsafePathError("refusing malformed Hermes shields finish metadata") -def _assert_current_snapshot(dir_fd: int, basename: str, path: str, snapshot: FileSnapshot) -> None: - current = _stat_path_at(dir_fd, basename) - if not _same_snapshot(current, snapshot): - raise UnsafePathError(f"refusing raced runtime config path: {path}") + parent_path, hermes_name = _split_path(hermes_dir) + parent_fd = _open_directory(parent_path) + hermes_fd: int | None = None + try: + parent_st = os.fstat(parent_fd) + if not _same_inode(parent_st, parent_meta): + raise UnsafePathError("refusing shields finish because /sandbox changed") + if ( + parent_st.st_uid != os.geteuid() + or parent_st.st_gid != os.getegid() + or stat.S_IMODE(parent_st.st_mode) != 0o755 + ): + raise UnsafePathError( + "refusing shields finish because /sandbox is not frozen" + ) + hermes_fd = _open_child_directory(parent_fd, hermes_name, hermes_dir) + hermes_st = os.fstat(hermes_fd) + if not _same_inode(hermes_st, hermes_meta): + raise UnsafePathError("refusing shields finish because .hermes changed") + if ( + hermes_st.st_uid != hermes_meta.get("uid") + or hermes_st.st_gid != hermes_meta.get("gid") + or stat.S_IMODE(hermes_st.st_mode) != hermes_meta.get("mode") + ): + raise UnsafePathError( + "refusing shields finish because .hermes metadata drifted" + ) -def _atomic_replace( - path: str, - data: bytes, - *, - expected: FileSnapshot | None, - mode: int, - uid: int, - gid: int, -) -> None: - dir_fd, basename = _open_parent_dir(path) - tmp_name = f".{basename}.nemoclaw.{os.getpid()}.{secrets.token_hex(8)}" - tmp_fd: int | None = None - try: - if expected is not None: - _assert_current_snapshot(dir_fd, basename, path, expected) - else: + for name in SEALED_FILE_NAMES: + file_state = files.get(name) + if not isinstance(file_state, dict): + raise UnsafePathError(f"refusing missing shields metadata for {name}") + sealed = file_state.get("sealed") + desired = file_state.get("original") + if not isinstance(sealed, dict) or not isinstance(desired, dict): + raise UnsafePathError(f"refusing malformed shields metadata for {name}") + fd = os.open( + name, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, + ) try: - _stat_path_at(dir_fd, basename) - except FileNotFoundError: - pass - else: - raise UnsafePathError(f"refusing raced runtime config create: {path}") + current = os.fstat(fd) + if ( + not stat.S_ISREG(current.st_mode) + or current.st_nlink != 1 + or not _same_inode(current, sealed) + or current.st_uid != desired.get("uid") + or current.st_gid != desired.get("gid") + or stat.S_IMODE(current.st_mode) != desired.get("mode") + or _get_inode_flags(fd) != int(file_state.get("flags", 0)) + ): + raise UnsafePathError( + f"refusing shields finish because {name} metadata drifted" + ) + finally: + os.close(fd) - tmp_fd = os.open( - tmp_name, - os.O_WRONLY | os.O_CREAT | os.O_EXCL | _no_follow_flag() | _cloexec_flag(), - 0o600, - dir_fd=dir_fd, + marker_fd = os.open( + RESTART_ORPHAN_MARKER_NAME, + os.O_RDONLY | _no_follow_flag() | _cloexec_flag(), + dir_fd=hermes_fd, ) try: - os.fchown(tmp_fd, uid, gid) - except PermissionError: - if os.geteuid() == 0: - raise - os.fchmod(tmp_fd, mode) - with os.fdopen(tmp_fd, "wb", closefd=True) as handle: - tmp_fd = None - handle.write(data) - handle.flush() - os.fsync(handle.fileno()) + marker_st = os.fstat(marker_fd) + if ( + not stat.S_ISREG(marker_st.st_mode) + or marker_st.st_uid != os.geteuid() + or marker_st.st_gid != os.getegid() + or stat.S_IMODE(marker_st.st_mode) != 0o400 + or marker_st.st_nlink != 1 + ): + raise UnsafePathError("refusing unsafe Hermes restart orphan marker") + finally: + os.close(marker_fd) - if expected is not None: - _assert_current_snapshot(dir_fd, basename, path, expected) - os.replace(tmp_name, basename, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) - try: - os.fsync(dir_fd) - except OSError: - # Directory fsync is best-effort; some container filesystems reject - # it even after the atomic replace has succeeded. - pass - except Exception: - try: - os.unlink(tmp_name, dir_fd=dir_fd) - except FileNotFoundError: - # The temp file may not exist yet, or may already have been removed - # by the failing operation path. - pass - except OSError: - # Cleanup must not mask the original atomic-write failure. - pass - raise + _verify_strict_hash(hermes_dir, hash_file) + _verify_compat_hash(hash_file, os.path.join(hermes_dir, ".config-hash")) + os.fchmod(parent_fd, parent_meta["mode"]) + _set_inode_flags(parent_fd, int(state_data.get("parent_flags", 0))) + _remove_restart_orphan_marker(hermes_fd) + # Parent ownership is the last persistent metadata change. Seal rejects + # set-id parent modes, so this chown cannot clear a prepared mode bit. + # A crash before it leaves root ownership as the orphan discriminator; + # a successful chown means the persistent metadata is exact. + os.fchown(parent_fd, parent_meta["uid"], parent_meta["gid"]) finally: - if tmp_fd is not None: - os.close(tmp_fd) - os.close(dir_fd) + if hermes_fd is not None: + os.close(hermes_fd) + os.close(parent_fd) + recorded_token = state_data["mutation_lock_token"] + lock_path = state_data["mutation_lock_path"] + if not isinstance(recorded_token, str) or not isinstance(lock_path, str): + raise UnsafePathError("refusing malformed Hermes shields lock metadata") + _release_mutation_lock(lock_path, recorded_token) + os.unlink(state_file) + return mode, transition.get("chattr_applied") is True -def _read_text(path: str) -> tuple[str, FileSnapshot]: - opened = _open_regular(path) - try: - return opened.read_bytes().decode("utf-8"), opened.snapshot - finally: - opened.close() +def prepare_shields_abort(hermes_dir: str, state_file: str, lock_token: str) -> None: + _claim_transition_worker(state_file, lock_token, "prepare-shields-abort") + state_data, transition, mode = _load_owned_shields_transition( + state_file, + lock_token, + ("shields-transition-pending", "shields-transition-applied"), + ) + rollback_mode = transition.get("rollback_mode") + if rollback_mode not in ("locked", "mutable"): + raise UnsafePathError( + "refusing shields abort without a trusted rollback posture" + ) + hash_file = state_data.get("hash_file") + if not isinstance(hash_file, str) or not hash_file: + raise UnsafePathError("refusing shields abort without a strict hash path") + if state_data.get("phase") == "shields-transition-applied": + original_metadata = transition.get("original_metadata") + if not isinstance(original_metadata, dict): + raise UnsafePathError("refusing shields abort without rollback metadata") + if not isinstance(original_metadata.get("parent"), dict): + raise UnsafePathError("refusing malformed shields rollback metadata") + if mode == "mutable": + _replace_applied_mutable_inodes(state_data, hermes_dir, hash_file) + else: + _freeze_shields_directories(state_data, hermes_dir) + else: + _freeze_shields_directories(state_data, hermes_dir) -def _sha256_entry(path: str) -> tuple[str, FileSnapshot]: - opened = _open_regular(path) - try: - digest = hashlib.sha256(opened.read_bytes()).hexdigest() - return f"{digest} {path}\n", opened.snapshot - finally: - opened.close() + _configure_shields_target_metadata( + state_data, + transition, + hermes_dir, + str(rollback_mode), + capture_original=False, + ) + # The token-bound recursive worker validates its action against this mode. + # Once abort preparation has committed rollback metadata, the remaining + # recursive pass is the rollback posture, not the failed forward posture. + transition["mode"] = rollback_mode + state_data["phase"] = "shields-transition-aborting" + state_data["shields_transition"] = transition + _write_restart_state(state_file, state_data, create=False) -def _write_existing(path: str, text: str, snapshot: FileSnapshot, mode: int | None = None) -> None: - _atomic_replace( - path, - text.encode("utf-8"), - expected=snapshot, - mode=snapshot.mode if mode is None else mode, - uid=snapshot.uid, - gid=snapshot.gid, + +def abort_shields_transition(hermes_dir: str, state_file: str, lock_token: str) -> None: + _claim_transition_worker(state_file, lock_token, "abort-shields-transition") + state_data, _transition, _mode = _load_owned_shields_transition( + state_file, + lock_token, + ("shields-transition-aborting",), ) + state_data["phase"] = "sealed" + state_data.pop("shields_transition", None) + _write_restart_state(state_file, state_data, create=False) + _restore_restart_seal(state_file, verify_hash=True) -def _write_hash(path: str, text: str) -> None: - try: - opened = _open_regular(path) - except FileNotFoundError: + +def run_state_dir_transition( + hermes_dir: str, state_file: str, lock_token: str, action: str +) -> None: + if action not in ("lock", "unlock"): + raise UnsafePathError("refusing unsupported Hermes state-dir action") + state_data = _claim_transition_worker( + state_file, lock_token, f"state-dir-{action}" + ) + transition = state_data.get("shields_transition") + expected_mode = "locked" if action == "lock" else "mutable" + if not isinstance(transition, dict) or transition.get("mode") != expected_mode: + raise UnsafePathError( + "Hermes state-dir action does not match the owned shields transition" + ) + installed = "/usr/local/lib/nemoclaw/state-dir-guard.py" + checkout = os.path.realpath( + os.path.join( + os.path.dirname(__file__), "..", "..", "scripts", "state-dir-guard.py" + ) + ) + helper = installed if os.path.isfile(installed) else checkout + if not os.path.isfile(helper): + raise UnsafePathError("Hermes state-dir guard is unavailable") + # Preserve this exact PID/start identity as GNU timeout while it owns and + # waits for the recursive worker. Cancel the Python alarm before exec so + # timeout alone owns TERM/KILL tree cleanup and no orphan child survives. + signal.alarm(0) + os.execvp( + "timeout", + [ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "12m", + sys.executable, + helper, + action, + "--config-dir", + hermes_dir, + ], + ) + + +def _recover_config_write_transaction(hermes_dir: str, state_file: str) -> None: + state_data = _load_restart_state(state_file) + phase = str(state_data.get("phase", "")) + write_state = state_data.get("config_write") + if not isinstance(write_state, dict): + raise UnsafePathError( + "refusing config-write recovery without rollback metadata" + ) + encoded_original = write_state.get("original_base64") + if not isinstance(encoded_original, str): + files = state_data.get("files") + config_state = files.get("config.yaml") if isinstance(files, dict) else None + encoded_original = ( + config_state.get("trusted_base64") + if isinstance(config_state, dict) + else None + ) + original_digest = write_state.get("original_sha256") + if not isinstance(encoded_original, str) or not isinstance(original_digest, str): + raise UnsafePathError( + "refusing malformed Hermes config-write rollback metadata" + ) + original_bytes = _decode_bounded_base64( + encoded_original, + MAX_CONFIG_INPUT_BYTES, + "Hermes config-write rollback bytes", + ) + if not secrets.compare_digest( + hashlib.sha256(original_bytes).hexdigest(), original_digest + ): + raise UnsafePathError("refusing invalid Hermes config-write rollback digest") + + config_path = os.path.join(hermes_dir, "config.yaml") + if phase == "config-write-prepared": + current = _open_regular(config_path) + try: + current_snapshot = current.snapshot + finally: + current.close() _atomic_replace( - path, - text.encode("utf-8"), - expected=None, - mode=0o600, + config_path, + original_bytes, + expected=current_snapshot, + mode=0o444, uid=os.geteuid(), gid=os.getegid(), ) - return - try: - snapshot = opened.snapshot - finally: - opened.close() - _atomic_replace( - path, - text.encode("utf-8"), - expected=snapshot, - mode=snapshot.mode, - uid=snapshot.uid, - gid=snapshot.gid, - ) + refresh_hashes(hermes_dir, str(state_data["hash_file"]), "both") + _record_current_sealed_inodes( + state_file, hermes_dir, ("config.yaml", ".config-hash") + ) + elif phase == "config-write-committed": + # The committed phase is published only after config + both hashes are + # durable. Re-verify the strict anchor, but do not repeat the write. + _verify_strict_hash(hermes_dir, str(state_data["hash_file"])) + else: + raise UnsafePathError( + f"refusing unsupported Hermes config-write phase: {phase}" + ) + state_data = _load_restart_state(state_file) + state_data["phase"] = "sealed" + state_data.pop("config_write", None) + _write_restart_state(state_file, state_data, create=False) -def _hash_text(config_path: str, env_path: str) -> tuple[str, FileSnapshot, FileSnapshot]: - config_entry, config_snapshot = _sha256_entry(config_path) - env_entry, env_snapshot = _sha256_entry(env_path) - return config_entry + env_entry, config_snapshot, env_snapshot +def write_config_transaction( + hermes_dir: str, + hash_file: str, + state_file: str, + expected_config_sha256: str, + config_bytes: bytes, +) -> None: + if not re.fullmatch(r"[0-9a-f]{64}", expected_config_sha256): + raise UnsafePathError("write-config requires a valid expected config SHA-256") + if len(config_bytes) > MAX_CONFIG_INPUT_BYTES: + raise UnsafePathError("refusing oversized Hermes config input") -def refresh_hashes(hermes_dir: str, hash_file: str, mode: str) -> None: + seal_restart( + hermes_dir, + hash_file, + state_file, + purpose="config-write", + expected_config_sha256=expected_config_sha256, + ) + committed = False config_path = os.path.join(hermes_dir, "config.yaml") - env_path = os.path.join(hermes_dir, ".env") - compat_hash = os.path.join(hermes_dir, ".config-hash") - hash_text, config_snapshot, env_snapshot = _hash_text(config_path, env_path) - - def assert_inputs_stable() -> None: - config = _open_regular(config_path) - env = _open_regular(env_path) + try: + state_data = _load_restart_state(state_file) + if _restart_state_was_locked(state_data): + raise UnsafePathError( + "Hermes config writes are unavailable while shields are up; run shields down first" + ) + opened = _open_regular(config_path) try: - if config.snapshot != config_snapshot or env.snapshot != env_snapshot: - raise UnsafePathError("refusing raced Hermes config/env path before hash refresh") + original_bytes = opened.read_bytes(MAX_CONFIG_INPUT_BYTES) + original_snapshot = opened.snapshot finally: - config.close() - env.close() + opened.close() + if not secrets.compare_digest( + hashlib.sha256(original_bytes).hexdigest(), expected_config_sha256 + ): + raise UnsafePathError( + "Hermes config changed after the host read it; retry the command" + ) - if mode == "strict": - assert_inputs_stable() - _write_hash(hash_file, hash_text) + state_data["phase"] = "config-write-prepared" + state_data["config_write"] = { + "original_sha256": hashlib.sha256(original_bytes).hexdigest(), + } + _write_restart_state(state_file, state_data, create=False) - compat_exists = os.path.exists(compat_hash) - compat_writable = os.access(compat_hash, os.W_OK) if compat_exists else os.access(hermes_dir, os.W_OK) - if mode == "compat" and compat_writable: - assert_inputs_stable() - _write_hash(compat_hash, hash_text) + _atomic_replace( + config_path, + config_bytes, + expected=original_snapshot, + mode=0o444, + uid=os.geteuid(), + gid=os.getegid(), + ) + refresh_hashes(hermes_dir, hash_file, "both") + _record_current_sealed_inodes( + state_file, hermes_dir, ("config.yaml", ".config-hash") + ) + state_data = _load_restart_state(state_file) + state_data["phase"] = "config-write-committed" + _write_restart_state(state_file, state_data, create=False) + committed = True + unseal_restart(hermes_dir, state_file) + except Exception: + try: + unseal_restart(hermes_dir, state_file) + if committed: + return + except Exception: + # Retain the root-only token, frozen parent, and mutation lock. + # PID 1 can retry recovery; it must never guess at metadata. + pass + raise def _parse_env_assignment(line: str) -> tuple[str, str, str] | None: @@ -342,7 +3956,9 @@ def _parse_env_assignment(line: str) -> tuple[str, str, str] | None: return prefix, key, value -def _upsert_env_assignments(text: str, assignments: dict[str, str]) -> tuple[str, bool, set[str]]: +def _upsert_env_assignments( + text: str, assignments: dict[str, str] +) -> tuple[str, bool, set[str]]: if not assignments: return text, False, set() @@ -410,7 +4026,11 @@ def _env_assignment_keys(text: str) -> set[str]: def _is_generated_api_server_key(value: str) -> bool: candidate = value.strip() - if len(candidate) >= 2 and candidate[0] == candidate[-1] and candidate[0] in ("'", '"'): + if ( + len(candidate) >= 2 + and candidate[0] == candidate[-1] + and candidate[0] in ("'", '"') + ): candidate = candidate[1:-1] return API_SERVER_KEY_RE.fullmatch(candidate) is not None @@ -441,9 +4061,13 @@ def _validate_runtime_plan_env_key(value: object, label: str) -> str: return value -def _validate_env_text_with_boundary(text: str, boundary_validator_path: str | None) -> None: +def _validate_env_text_with_boundary( + text: str, boundary_validator_path: str | None +) -> None: if not boundary_validator_path: - raise UnsafePathError("Hermes provider placeholder refresh requires the secret-boundary validator") + raise UnsafePathError( + "Hermes provider placeholder refresh requires the secret-boundary validator" + ) fd, temp_path = tempfile.mkstemp(prefix="hermes-env-boundary-", text=True) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: @@ -458,7 +4082,9 @@ def _validate_env_text_with_boundary(text: str, boundary_validator_path: str | N except subprocess.TimeoutExpired as exc: raise UnsafePathError("Hermes secret-boundary validator timed out") from exc except OSError as exc: - raise UnsafePathError(f"Hermes secret-boundary validator failed: {exc}") from exc + raise UnsafePathError( + f"Hermes secret-boundary validator failed: {exc}" + ) from exc if result.returncode != 0: raise UnsafePathError( "Hermes provider placeholder refresh would violate the secret boundary" @@ -479,7 +4105,9 @@ def _runtime_plan_replacements_and_provider_keys( if not runtime_plan_path: return {}, set(), False try: - runtime_plan_text, _runtime_plan_snapshot = _read_text(runtime_plan_path) + runtime_plan_text, _runtime_plan_snapshot = _read_text( + runtime_plan_path, MAX_RUNTIME_PLAN_BYTES + ) except FileNotFoundError: return {}, set(), False try: @@ -510,15 +4138,21 @@ def _runtime_plan_replacements_and_provider_keys( provider_env_keys: set[str] = set() bindings = plan.get("credentialBindings", []) if not isinstance(bindings, list): - raise UnsafePathError("messaging runtime plan credentialBindings must be a list") + raise UnsafePathError( + "messaging runtime plan credentialBindings must be a list" + ) for binding in bindings: if not isinstance(binding, dict): - raise UnsafePathError("messaging runtime plan credentialBindings entries must be objects") + raise UnsafePathError( + "messaging runtime plan credentialBindings entries must be objects" + ) channel_id = binding.get("channelId") provider_env_key = binding.get("providerEnvKey") if isinstance(channel_id, str) and channel_id in active_channel_ids: provider_env_keys.add( - _validate_runtime_plan_env_key(provider_env_key, "credentialBindings.providerEnvKey") + _validate_runtime_plan_env_key( + provider_env_key, "credentialBindings.providerEnvKey" + ) ) runtime_setup = plan.get("runtimeSetup") or {} @@ -526,12 +4160,16 @@ def _runtime_plan_replacements_and_provider_keys( raise UnsafePathError("messaging runtime plan runtimeSetup must be an object") aliases = runtime_setup.get("envAliases", []) if not isinstance(aliases, list): - raise UnsafePathError("messaging runtime plan runtimeSetup.envAliases must be a list") + raise UnsafePathError( + "messaging runtime plan runtimeSetup.envAliases must be a list" + ) replacements: dict[str, tuple[str, str]] = {} for alias in aliases: if not isinstance(alias, dict): - raise UnsafePathError("messaging runtime plan envAliases entries must be objects") + raise UnsafePathError( + "messaging runtime plan envAliases entries must be objects" + ) channel_id = alias.get("channelId") if not isinstance(channel_id, str) or channel_id not in active_channel_ids: continue @@ -539,17 +4177,27 @@ def _runtime_plan_replacements_and_provider_keys( pattern = alias.get("match") value = alias.get("value") message = alias.get("message") or "" - if not isinstance(pattern, str) or not isinstance(value, str) or not isinstance(message, str): + if ( + not isinstance(pattern, str) + or not isinstance(value, str) + or not isinstance(message, str) + ): continue - env_key = _validate_runtime_plan_env_key(env_key, "runtimeSetup.envAliases.envKey") + env_key = _validate_runtime_plan_env_key( + env_key, "runtimeSetup.envAliases.envKey" + ) if env_key in replacements: continue if _has_env_control_chars(value) or _has_env_control_chars(message): - raise UnsafePathError("messaging runtime plan env alias contains unsafe characters") + raise UnsafePathError( + "messaging runtime plan env alias contains unsafe characters" + ) try: compiled = re.compile(pattern) except re.error as exc: - raise UnsafePathError(f"messaging runtime plan env alias regex is invalid: {exc}") from exc + raise UnsafePathError( + f"messaging runtime plan env alias regex is invalid: {exc}" + ) from exc if compiled.search(os.environ.get(env_key, "")): replacements[env_key] = (value, message) return replacements, provider_env_keys, True @@ -559,17 +4207,25 @@ def ensure_api_key(hermes_dir: str, hash_file: str, mode: str) -> None: env_path = os.path.join(hermes_dir, ".env") if not os.path.exists(env_path): return - text, snapshot = _read_text(env_path) + text, snapshot = _read_text(env_path, MAX_ENV_BYTES) existing_value = _first_env_assignment_value(text, "API_SERVER_KEY") minted = existing_value is None or not _is_generated_api_server_key(existing_value) api_server_key = secrets.token_hex(32) if minted else existing_value - updated_text, changed, _changed_keys = _upsert_env_assignments(text, {"API_SERVER_KEY": api_server_key}) + updated_text, changed, _changed_keys = _upsert_env_assignments( + text, {"API_SERVER_KEY": api_server_key} + ) if not changed: print("minted=0") return - _write_existing(env_path, updated_text, snapshot, mode=0o640) + if snapshot.mode & 0o222 == 0: + raise UnsafePathError( + "Hermes startup cannot update .env while shields are up; rebuild or recreate the sandbox" + ) + # Preserve the active posture: mutable images are 0640, while shields-up + # startup must keep the root-owned 0444 contract after a generated update. + _write_existing(env_path, updated_text, snapshot) refresh_hashes(hermes_dir, hash_file, mode) print("minted=1" if minted else "updated=1") @@ -585,34 +4241,47 @@ def provider_placeholders( if not os.path.exists(env_path): return - replacements, runtime_plan_provider_keys, runtime_plan_loaded = _runtime_plan_replacements_and_provider_keys( - runtime_plan_path + replacements, runtime_plan_provider_keys, runtime_plan_loaded = ( + _runtime_plan_replacements_and_provider_keys(runtime_plan_path) ) - text, snapshot = _read_text(env_path) + text, snapshot = _read_text(env_path, MAX_ENV_BYTES) allowed_fallback_keys = ( runtime_plan_provider_keys if runtime_plan_loaded - else set(LEGACY_PROVIDER_PLACEHOLDER_KEYS).intersection(_env_assignment_keys(text)) + else set(LEGACY_PROVIDER_PLACEHOLDER_KEYS).intersection( + _env_assignment_keys(text) + ) ) for key in allowed_fallback_keys: if key in replacements: continue - normalized = _normalize_provider_placeholder_for_env_key(os.environ.get(key, ""), key) + normalized = _normalize_provider_placeholder_for_env_key( + os.environ.get(key, ""), key + ) if normalized: replacements[key] = (normalized, "") if not replacements: return - assignment_values = {key: replacement for key, (replacement, _message) in replacements.items()} - updated_text, changed, changed_keys = _upsert_env_assignments(text, assignment_values) + assignment_values = { + key: replacement for key, (replacement, _message) in replacements.items() + } + updated_text, changed, changed_keys = _upsert_env_assignments( + text, assignment_values + ) if not changed: return _validate_env_text_with_boundary(updated_text, boundary_validator_path) + if snapshot.mode & 0o222 == 0: + raise UnsafePathError( + "Hermes startup cannot update provider placeholders while shields are up; rebuild or recreate the sandbox" + ) + try: - _write_existing(env_path, updated_text, snapshot, mode=0o640) + _write_existing(env_path, updated_text, snapshot) refresh_hashes(hermes_dir, hash_file, mode) except PermissionError: if os.geteuid() != 0: @@ -623,32 +4292,75 @@ def provider_placeholders( ) return raise - refreshed_messages = { - message - for key, (_replacement, message) in replacements.items() - if key in changed_keys and message - } - for message in sorted(refreshed_messages): - print(message, file=sys.stderr) - print("[config] Refreshed Hermes provider placeholders from OpenShell runtime env", file=sys.stderr) + refreshed_keys = sorted(key for key in replacements if key in changed_keys) + for key in refreshed_keys: + # Runtime-plan diagnostics are data, not trusted format strings. Emit + # only the validated environment key so a crafted plan cannot copy + # secret-shaped message content into startup logs. + print( + f"[config] Refreshed Hermes provider placeholder for {key}", file=sys.stderr + ) + print( + "[config] Refreshed Hermes provider placeholders from OpenShell runtime env", + file=sys.stderr, + ) def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("action", choices=("ensure-api-key", "refresh-hashes", "provider-placeholders")) + parser.add_argument( + "action", + choices=( + "ensure-api-key", + "refresh-hashes", + "provider-placeholders", + "publish-startup-ready", + "seal-restart", + "unseal-restart", + "inspect-mutation-owner", + "begin-shields-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "write-config", + "recover-prestate-lock", + "run-state-dir-transition", + ), + ) parser.add_argument("--hermes-dir", required=True) - parser.add_argument("--hash-file", required=True) + parser.add_argument("--hash-file", default="") parser.add_argument("--runtime-plan", default="") parser.add_argument("--boundary-validator", default="") - parser.add_argument("--mode", choices=("strict", "compat"), default="strict") + parser.add_argument( + "--mode", choices=("strict", "compat", "both"), default="strict" + ) + parser.add_argument("--state-file", default="") + parser.add_argument("--expected-config-sha256", default="") + parser.add_argument("--lock-token", default="") + parser.add_argument("--state-action", choices=("lock", "unlock"), default="") + parser.add_argument("--shields-mode", choices=("locked", "mutable"), default="") + parser.add_argument( + "--rollback-shields-mode", choices=("locked", "mutable"), default="" + ) + parser.add_argument("--startup-owner", action="store_true") args = parser.parse_args() + previous_alarm_handler = signal.signal(signal.SIGALRM, _deadline_expired) + signal.alarm(GUARD_DEADLINE_SECONDS) try: + _validate_action_readiness(args.action, args.startup_owner) if args.action == "ensure-api-key": + if not args.hash_file: + raise UnsafePathError("ensure-api-key requires --hash-file") ensure_api_key(args.hermes_dir, args.hash_file, args.mode) elif args.action == "refresh-hashes": + if not args.hash_file: + raise UnsafePathError("refresh-hashes requires --hash-file") refresh_hashes(args.hermes_dir, args.hash_file, args.mode) elif args.action == "provider-placeholders": + if not args.hash_file: + raise UnsafePathError("provider-placeholders requires --hash-file") provider_placeholders( args.hermes_dir, args.hash_file, @@ -656,12 +4368,140 @@ def main() -> int: args.runtime_plan, args.boundary_validator, ) + elif args.action == "publish-startup-ready": + publish_startup_ready() + print("ready=1") + elif args.action == "seal-restart": + if not args.hash_file or not args.state_file: + raise UnsafePathError( + "seal-restart requires --hash-file and --state-file" + ) + if args.lock_token and not re.fullmatch(r"[0-9a-f]{64}", args.lock_token): + raise UnsafePathError("seal-restart requires a valid lock token") + original_locked = seal_restart( + args.hermes_dir, + args.hash_file, + args.state_file, + mutation_lock_token=args.lock_token or None, + ) + print(f"sealed=1 original_locked={int(original_locked)}") + elif args.action == "unseal-restart": + if not args.state_file: + raise UnsafePathError("unseal-restart requires --state-file") + unseal_restart(args.hermes_dir, args.state_file) + print("unsealed=1") + elif args.action == "inspect-mutation-owner": + if not args.state_file: + raise UnsafePathError("inspect-mutation-owner requires --state-file") + if args.lock_token and not re.fullmatch(r"[0-9a-f]{64}", args.lock_token): + raise UnsafePathError( + "inspect-mutation-owner requires a valid lock token" + ) + print(inspect_mutation_owner(args.state_file, args.lock_token)) + elif args.action == "begin-shields-transition": + if not args.hash_file or not args.state_file or not args.shields_mode: + raise UnsafePathError( + "begin-shields-transition requires --hash-file, --state-file, and --shields-mode" + ) + lock_token, original_locked = begin_shields_transition( + args.hermes_dir, + args.hash_file, + args.state_file, + args.shields_mode, + args.rollback_shields_mode, + ) + print(f"lock_token={lock_token} original_locked={int(original_locked)}") + elif args.action == "apply-shields-transition": + if not args.state_file or not re.fullmatch( + r"[0-9a-f]{64}", args.lock_token + ): + raise UnsafePathError( + "apply-shields-transition requires --state-file and a valid --lock-token" + ) + mode, chattr_applied = apply_shields_transition( + args.hermes_dir, args.state_file, args.lock_token + ) + print(f"shields_mode={mode} chattr_applied={int(chattr_applied)}") + elif args.action == "finish-shields-transition": + if ( + not args.hash_file + or not args.state_file + or not re.fullmatch(r"[0-9a-f]{64}", args.lock_token) + ): + raise UnsafePathError( + "finish-shields-transition requires --hash-file, --state-file, and a valid --lock-token" + ) + mode, chattr_applied = finish_shields_transition( + args.hermes_dir, args.hash_file, args.state_file, args.lock_token + ) + print(f"shields_mode={mode} chattr_applied={int(chattr_applied)}") + elif args.action == "prepare-shields-abort": + if not args.state_file or not re.fullmatch( + r"[0-9a-f]{64}", args.lock_token + ): + raise UnsafePathError( + "prepare-shields-abort requires --state-file and a valid --lock-token" + ) + prepare_shields_abort(args.hermes_dir, args.state_file, args.lock_token) + print("abort_prepared=1") + elif args.action == "abort-shields-transition": + if not args.state_file or not re.fullmatch( + r"[0-9a-f]{64}", args.lock_token + ): + raise UnsafePathError( + "abort-shields-transition requires --state-file and a valid --lock-token" + ) + abort_shields_transition(args.hermes_dir, args.state_file, args.lock_token) + print("aborted=1") + elif args.action == "write-config": + if ( + not args.hash_file + or not args.state_file + or not args.expected_config_sha256 + ): + raise UnsafePathError( + "write-config requires --hash-file, --state-file, and --expected-config-sha256" + ) + config_bytes = sys.stdin.buffer.read(MAX_CONFIG_INPUT_BYTES + 1) + write_config_transaction( + args.hermes_dir, + args.hash_file, + args.state_file, + args.expected_config_sha256, + config_bytes, + ) + print("updated=1") + elif args.action == "recover-prestate-lock": + if not args.state_file: + raise UnsafePathError( + "recover-prestate-lock requires --state-file" + ) + recovered = recover_dead_prestate_mutation_lock(args.state_file) + print(f"recovered={int(recovered)}") + elif args.action == "run-state-dir-transition": + if ( + not args.state_file + or not args.state_action + or not re.fullmatch(r"[0-9a-f]{64}", args.lock_token) + ): + raise UnsafePathError( + "run-state-dir-transition requires --state-file, --state-action, and a valid --lock-token" + ) + run_state_dir_transition( + args.hermes_dir, + args.state_file, + args.lock_token, + args.state_action, + ) except UnsafePathError as exc: _die(str(exc)) except OSError as exc: if exc.errno in (errno.ELOOP, errno.EPERM, errno.EACCES): _die(f"refusing unsafe Hermes runtime config path: {exc}") raise + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, previous_alarm_handler) return 0 diff --git a/agents/hermes/start.sh b/agents/hermes/start.sh index cf1125971fc..d729fb10746 100755 --- a/agents/hermes/start.sh +++ b/agents/hermes/start.sh @@ -38,6 +38,13 @@ fi # shellcheck source=scripts/lib/sandbox-init.sh source "$_SANDBOX_INIT" +_GATEWAY_SUPERVISOR="/usr/local/lib/nemoclaw/gateway-supervisor.sh" +if [ ! -f "$_GATEWAY_SUPERVISOR" ]; then + _GATEWAY_SUPERVISOR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../../scripts/lib/gateway-supervisor.sh" +fi +# shellcheck source=scripts/lib/gateway-supervisor.sh +source "$_GATEWAY_SUPERVISOR" + # Harden RLIMITs (nproc #809 + nofile #4527) as root PID 1, before any step-down. harden_resource_limits @@ -225,6 +232,24 @@ _HERMES_RUNTIME_CONFIG_GUARD="/usr/local/lib/nemoclaw/hermes-runtime-config-guar if [ ! -f "$_HERMES_RUNTIME_CONFIG_GUARD" ]; then _HERMES_RUNTIME_CONFIG_GUARD="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/runtime-config-guard.py" fi +_HERMES_GUARD_TIMEOUT=(timeout --signal=TERM --kill-after=5s 12m) +_HERMES_BOUNDARY_TIMEOUT=(timeout --signal=TERM --kill-after=2s 15s) +HERMES_RESTART_SEAL_STATE="/run/nemoclaw/hermes-restart-seal.json" +HERMES_CONFIG_MUTATION_LOCK="/run/nemoclaw/hermes-config-mutation.lock" +HERMES_RESTART_ORPHAN_MARKER="/sandbox/.hermes/.nemoclaw-hermes-restart-seal" +HERMES_STARTUP_READY_FILE="/run/nemoclaw/hermes-startup-ready" +HERMES_RESTART_SEALED=0 +HERMES_RESTART_ORIGINAL_LOCKED=0 +HERMES_RESTART_UNSEALING=0 +HERMES_RESTART_SIGNAL_PENDING=0 + +# A same-container PID 1 restart can retain /run. Revoke the prior readiness +# lease before any startup migration or mutable config read; host mutations are +# admitted again only after the root supervisor is fully initialized. +if [ -e "$HERMES_STARTUP_READY_FILE" ] && ! rm -f "$HERMES_STARTUP_READY_FILE"; then + echo "[SECURITY] Refusing Hermes startup because the stale readiness marker could not be removed" >&2 + exit 1 +fi # The seeder imports PyYAML, which ships ONLY in the Hermes venv — not in the # base-image python3 that is first on PATH at container boot. (An interactive @@ -318,14 +343,54 @@ print_dashboard_urls() { echo "[gateway] Connect any OpenAI-compatible frontend to this endpoint." >&2 } +hermes_fatal_unproven_child() { + local role="$1" + local pid="$2" + if [ "${HERMES_STARTUP_SUPERVISOR_PID:-$$}" -eq 1 ]; then + echo "[CRITICAL] Newly launched Hermes ${role} pid ${pid} failed exact role identity capture; exiting PID 1 for whole-container cleanup without signaling or waiting on the unproven PID" >&2 + exit 1 + fi + + # In managed OpenShell, exiting this non-root supervisor would leave PID 1 + # and the unproven child alive. Bash's job table can still wait for the exact + # `$!` child without treating a reused numeric PID as authority to signal it. + # Quarantine the supervisor after that child exits; only sandbox destruction + # may tear down a process tree whose identities could not be established. + echo "[CRITICAL] Newly launched Hermes ${role} pid ${pid} failed exact role identity capture; quarantining the managed startup supervisor without signaling the unproven child" >&2 + trap ':' TERM INT + wait "$pid" 2>/dev/null || true + echo "[CRITICAL] Unproven Hermes ${role} child exited; managed supervisor remains quarantined until sandbox recreation" >&2 + while :; do + sleep 60 || true + done +} + start_gateway_log_stream() { - { tail -n +1 -F /tmp/gateway.log 2>/dev/null | sed -u 's/^/[gateway-log:] /' >&2; } & + tail -n +1 -F /tmp/gateway.log 2>/dev/null | sed -u 's/^/[gateway-log:] /' >&2 & GATEWAY_LOG_TAIL_PID=$! + if ! hermes_capture_tracked_role gateway-log "$GATEWAY_LOG_TAIL_PID" current; then + hermes_fatal_unproven_child gateway-log "$GATEWAY_LOG_TAIL_PID" + fi } start_dashboard_log_stream() { - { tail -n +1 -F /tmp/dashboard.log 2>/dev/null | sed -u 's/^/[dashboard-log:] /' >&2; } & + tail -n +1 -F /tmp/dashboard.log 2>/dev/null | sed -u 's/^/[dashboard-log:] /' >&2 & DASHBOARD_LOG_TAIL_PID=$! + if ! hermes_capture_tracked_role dashboard-log "$DASHBOARD_LOG_TAIL_PID" current; then + hermes_fatal_unproven_child dashboard-log "$DASHBOARD_LOG_TAIL_PID" + fi +} + +ensure_dashboard_log_stream() { + if ! hermes_tracked_role_is_current dashboard-log "${DASHBOARD_LOG_TAIL_PID:-}" current; then + start_dashboard_log_stream + fi +} + +ensure_gateway_log_stream() { + if ! hermes_tracked_role_is_current gateway-log "${GATEWAY_LOG_TAIL_PID:-}" current; then + start_gateway_log_stream + fi } retry_tirith_marker_if_needed() { @@ -361,10 +426,21 @@ cmdline_is_hermes_gateway() { has_live_hermes_gateway() { local proc_root="${NEMOCLAW_PROC_ROOT:-/proc}" - local cmdline_file cmdline + local expected_uid cmdline_file pid process_uid cmdline + + expected_uid="$(id -u)" + if [ "$expected_uid" -eq 0 ]; then + expected_uid="$(id -u gateway 2>/dev/null || true)" + fi + case "$expected_uid" in + '' | *[!0-9]*) return 1 ;; + esac for cmdline_file in "${proc_root}"/[0-9]*/cmdline; do [ -r "$cmdline_file" ] || continue + pid="${cmdline_file%/cmdline}" + process_uid="$(awk '$1 == "Uid:" { print $2; exit }' "${pid}/status" 2>/dev/null || true)" + [ "$process_uid" = "$expected_uid" ] || continue cmdline="$(tr '\0' ' ' <"$cmdline_file" 2>/dev/null || true)" if cmdline_is_hermes_gateway "$cmdline"; then return 0 @@ -445,11 +521,36 @@ hermes_config_root_is_locked() { && hermes_config_path_is_locked "${HERMES_DIR}/.env" } +hermes_locked_parent_is_protected() { + local owner mode + owner="$(stat -c '%U:%G' /sandbox 2>/dev/null || stat -f '%Su:%Sg' /sandbox 2>/dev/null || true)" + mode="$(stat -c '%a' /sandbox 2>/dev/null || stat -f '%Lp' /sandbox 2>/dev/null || true)" + case "${owner} ${mode}" in + "root:sandbox 1775" | "root:sandbox 01775") return 0 ;; + *) return 1 ;; + esac +} + apply_shields_up_runtime_env() { - hermes_config_root_is_locked || return 0 - if [ -z "${HERMES_KANBAN_DISPATCH_IN_GATEWAY:-}" ]; then - export HERMES_KANBAN_DISPATCH_IN_GATEWAY=0 - echo "[gateway] Shields-up: HERMES_KANBAN_DISPATCH_IN_GATEWAY=0 (embedded kanban dispatcher suspended; kanban.db on locked config root is read-only)" >&2 + local config_locked=0 + if [ "${HERMES_RESTART_SEALED:-0}" -eq 1 ]; then + config_locked="${HERMES_RESTART_ORIGINAL_LOCKED:-0}" + elif hermes_config_root_is_locked; then + config_locked=1 + fi + + if [ "$config_locked" -eq 1 ]; then + if [ -z "${HERMES_KANBAN_DISPATCH_IN_GATEWAY:-}" ]; then + export HERMES_KANBAN_DISPATCH_IN_GATEWAY=0 + _NEMOCLAW_SET_KANBAN_DISPATCH=1 + echo "[gateway] Shields-up: HERMES_KANBAN_DISPATCH_IN_GATEWAY=0 (embedded kanban dispatcher suspended; kanban.db on locked config root is read-only)" >&2 + fi + return 0 + fi + + if [ "${_NEMOCLAW_SET_KANBAN_DISPATCH:-0}" -eq 1 ]; then + unset HERMES_KANBAN_DISPATCH_IN_GATEWAY + _NEMOCLAW_SET_KANBAN_DISPATCH=0 fi } @@ -465,7 +566,7 @@ ensure_hermes_config_root_mode() { fi if [ "$(id -u)" -eq 0 ]; then - chown sandbox:sandbox "$HERMES_DIR" + chown sandbox:sandbox "$HERMES_DIR" || return 1 fi chmod 3770 "$HERMES_DIR" } @@ -483,7 +584,7 @@ ensure_hermes_state_dir() { return 1 fi - mkdir -p "$dir" + mkdir -p "$dir" || return 1 if [ -L "$dir" ] || [ ! -d "$dir" ]; then echo "[SECURITY] Refusing Hermes layout repair because ${dir} did not resolve to a safe directory" >&2 @@ -491,14 +592,14 @@ ensure_hermes_state_dir() { fi if [ "$(id -u)" -eq 0 ]; then - chown sandbox:sandbox "$dir" + chown sandbox:sandbox "$dir" || return 1 fi chmod "$mode" "$dir" } repair_hermes_log_permissions() { - ensure_hermes_state_dir "${HERMES_DIR}/logs" 2770 - ensure_hermes_state_dir "${HERMES_DIR}/logs/curator" 2770 + ensure_hermes_state_dir "${HERMES_DIR}/logs" 2770 || return 1 + ensure_hermes_state_dir "${HERMES_DIR}/logs/curator" 2770 || return 1 NEMOCLAW_HERMES_LOG_DIR="${HERMES_DIR}/logs" \ python3 - <<'PYLOGS' @@ -709,16 +810,16 @@ repair_hermes_startup_layout() { # either let the TUI clobber an attacker-pointed path or repeat the # original keypress traceback. echo "[gateway] Hermes layout repair limited to history file because config root is locked" >&2 - ensure_hermes_history_file "${HERMES_DIR}/.hermes_history" 660 + ensure_hermes_history_file "${HERMES_DIR}/.hermes_history" 660 || return 1 return 0 fi - ensure_hermes_config_root_mode - repair_hermes_log_permissions - ensure_hermes_state_dir "${HERMES_DIR}/hooks" 770 - ensure_hermes_state_dir "${HERMES_DIR}/image_cache" 770 - ensure_hermes_state_dir "${HERMES_DIR}/audio_cache" 770 - ensure_hermes_history_file "${HERMES_DIR}/.hermes_history" 660 + ensure_hermes_config_root_mode || return 1 + repair_hermes_log_permissions || return 1 + ensure_hermes_state_dir "${HERMES_DIR}/hooks" 770 || return 1 + ensure_hermes_state_dir "${HERMES_DIR}/image_cache" 770 || return 1 + ensure_hermes_state_dir "${HERMES_DIR}/audio_cache" 770 || return 1 + ensure_hermes_history_file "${HERMES_DIR}/.hermes_history" 660 || return 1 } cleanup_stale_hermes_gateway_runtime() { @@ -729,7 +830,7 @@ cleanup_stale_hermes_gateway_runtime() { return 0 fi - repair_hermes_startup_layout + repair_hermes_startup_layout || return 1 # Hermes can leave gateway.lock behind after Docker GPU recreation kills the # old process namespace. Clear it only after confirming no gateway is alive. @@ -745,28 +846,347 @@ cleanup_stale_hermes_gateway_runtime() { # socat bridges 0.0.0.0: to 127.0.0.1:. SOCAT_PID="" DASHBOARD_SOCAT_PID="" +_HERMES_PROC_ROOT="/proc" +# OpenShell owns container PID 1 and starts this script as the sandbox user in +# its managed topology. Bind every child identity to this immutable supervisor +# process rather than assuming the script itself is PID 1. Direct-container +# root entrypoints still capture 1 here. +readonly HERMES_STARTUP_SUPERVISOR_PID="$$" +GATEWAY_PID_START_IDENTITY="" +DASHBOARD_PID_START_IDENTITY="" +SOCAT_PID_START_IDENTITY="" +DASHBOARD_SOCAT_PID_START_IDENTITY="" +GATEWAY_LOG_TAIL_PID_START_IDENTITY="" +DASHBOARD_LOG_TAIL_PID_START_IDENTITY="" + +hermes_role_identity_value() { + case "$1" in + gateway) printf '%s' "${GATEWAY_PID_START_IDENTITY:-}" ;; + dashboard) printf '%s' "${DASHBOARD_PID_START_IDENTITY:-}" ;; + api-socat) printf '%s' "${SOCAT_PID_START_IDENTITY:-}" ;; + dashboard-socat) printf '%s' "${DASHBOARD_SOCAT_PID_START_IDENTITY:-}" ;; + gateway-log) printf '%s' "${GATEWAY_LOG_TAIL_PID_START_IDENTITY:-}" ;; + dashboard-log) printf '%s' "${DASHBOARD_LOG_TAIL_PID_START_IDENTITY:-}" ;; + *) return 1 ;; + esac +} + +hermes_set_role_identity() { + local role="$1" + local value="$2" + case "$role" in + gateway) GATEWAY_PID_START_IDENTITY="$value" ;; + dashboard) DASHBOARD_PID_START_IDENTITY="$value" ;; + api-socat) SOCAT_PID_START_IDENTITY="$value" ;; + dashboard-socat) DASHBOARD_SOCAT_PID_START_IDENTITY="$value" ;; + gateway-log) GATEWAY_LOG_TAIL_PID_START_IDENTITY="$value" ;; + dashboard-log) DASHBOARD_LOG_TAIL_PID_START_IDENTITY="$value" ;; + *) return 1 ;; + esac +} + +hermes_expected_service_uid() { + case "$1" in + current) id -u ;; + gateway) id -u gateway ;; + sandbox) id -u sandbox ;; + *) return 1 ;; + esac +} + +hermes_process_start_identity() { + local pid="$1" + local proc_stat + local stat_suffix + local expected_parent_pid="${HERMES_STARTUP_SUPERVISOR_PID:-$$}" + local process_ppid + local process_start + + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + [ -r "${_HERMES_PROC_ROOT}/${pid}/stat" ] || return 1 + IFS= read -r proc_stat <"${_HERMES_PROC_ROOT}/${pid}/stat" || return 1 + stat_suffix="${proc_stat##*) }" + process_ppid="$(awk '{print $2}' <<<"$stat_suffix")" + process_start="$(awk '{print $20}' <<<"$stat_suffix")" + [ "$process_ppid" = "$expected_parent_pid" ] || return 1 + case "$process_start" in + '' | *[!0-9]*) return 1 ;; + esac + printf '%s' "$process_start" +} + +hermes_process_role_identity() { + local role="$1" + local pid="$2" + local service_user="$3" + local port="${4:-}" + local process_start + local expected_uid + local effective_uid + local cmdline + + gateway_control_pid_is_live "$pid" || return 1 + [ -r "${_HERMES_PROC_ROOT}/${pid}/status" ] \ + && [ -r "${_HERMES_PROC_ROOT}/${pid}/cmdline" ] || return 1 + process_start="$(hermes_process_start_identity "$pid")" || return 1 + expected_uid="$(hermes_expected_service_uid "$service_user")" || return 1 + effective_uid="$(awk '/^Uid:/ { print $3; exit }' "${_HERMES_PROC_ROOT}/${pid}/status")" + [ "$effective_uid" = "$expected_uid" ] || return 1 + cmdline="$(tr '\0' ' ' <"${_HERMES_PROC_ROOT}/${pid}/cmdline")" || return 1 + case "$role" in + gateway) + case "$cmdline" in + *hermes*gateway*run*) ;; + *) return 1 ;; + esac + ;; + dashboard) + case "$cmdline" in + *hermes*dashboard*) ;; + *) return 1 ;; + esac + ;; + api-socat | dashboard-socat) + case "$port" in + '' | *[!0-9]*) return 1 ;; + esac + case "$cmdline" in + *socat*"TCP-LISTEN:${port},"*) ;; + *) return 1 ;; + esac + ;; + gateway-log) + case "$cmdline" in + *sed*gateway-log*) ;; + *) return 1 ;; + esac + ;; + dashboard-log) + case "$cmdline" in + *sed*dashboard-log*) ;; + *) return 1 ;; + esac + ;; + *) return 1 ;; + esac + printf '%s' "$process_start" +} + +hermes_capture_tracked_role() { + local role="$1" + local pid="$2" + local service_user="$3" + local port="${4:-}" + local identity + local attempts=0 + while [ "$attempts" -lt 50 ]; do + if identity="$(hermes_process_role_identity "$role" "$pid" "$service_user" "$port")"; then + hermes_set_role_identity "$role" "$identity" + return 0 + fi + gateway_control_pid_is_live "$pid" || return 1 + sleep 0.1 + attempts=$((attempts + 1)) + done + return 1 +} + +hermes_tracked_role_is_current() { + local role="$1" + local pid="$2" + local service_user="$3" + local port="${4:-}" + local expected + local current + expected="$(hermes_role_identity_value "$role")" || return 1 + [ -n "$expected" ] || return 1 + current="$(hermes_process_role_identity "$role" "$pid" "$service_user" "$port")" || return 1 + [ "$current" = "$expected" ] +} + +hermes_stop_tracked_role() { + local role="$1" + local pid="$2" + local service_user="$3" + local port="${4:-}" + local expected_start_identity + local current_start_identity + local state + expected_start_identity="$(hermes_role_identity_value "$role")" || return 1 + + case "$pid" in + '' | 0 | 1 | *[!0-9]*) + # An empty role has never owned a process and is a safe no-op. A stored + # identity paired with an invalid PID is inconsistent and must not be + # reported as a successful stop. + [ -z "$expected_start_identity" ] && return 0 + return 1 + ;; + esac + [ -n "$expected_start_identity" ] || return 1 + + if ! hermes_tracked_role_is_current "$role" "$pid" "$service_user" "$port"; then + # Distinguish a child that is definitely gone from a live/reused/unreadable + # numeric PID. Only the former is a successful no-op. A matching zombie is + # still the exact tracked child and the shared helper can reap it safely. + current_start_identity="$(hermes_process_start_identity "$pid" 2>/dev/null || true)" + if [ -n "$current_start_identity" ]; then + if [ "$current_start_identity" != "$expected_start_identity" ]; then + echo "[SECURITY] Hermes ${role} pid ${pid} was reused; refusing to signal or treat it as stopped" >&2 + return 1 + fi + state="$(gateway_control_pid_state "$pid" 2>/dev/null || true)" + case "$state" in + Z*) ;; + *) + echo "[SECURITY] Hermes ${role} pid ${pid} still has its captured start identity but its role cannot be proven; refusing to signal or treat it as stopped" >&2 + return 1 + ;; + esac + elif kill -0 "$pid" 2>/dev/null; then + echo "[SECURITY] Hermes ${role} pid ${pid} is live but its start identity cannot be proven; refusing to signal or treat it as stopped" >&2 + return 1 + else + hermes_set_role_identity "$role" "" + return 0 + fi + fi + + gateway_control_stop_tracked_pid "$pid" "$expected_start_identity" || return 1 + if kill -0 "$pid" 2>/dev/null; then + # The shared helper may return success when its final identity read says + # the numeric PID was replaced. That is sufficient for ordinary cleanup, + # but not for a gateway revocation that is about to mark the role stopped + # and relaunch. Require the numeric PID to be absent as a postcondition. + echo "[SECURITY] Hermes ${role} pid ${pid} remains live after tracked stop; refusing to treat it as stopped" >&2 + return 1 + fi + hermes_set_role_identity "$role" "" +} + +hermes_tracked_service_owns_listener() { + local pid="$1" + local port="$2" + local service_user="$3" + + if [ "$(id -u)" -ne 0 ] || [ "$service_user" = "current" ]; then + gateway_control_pid_owns_tcp_listener "$pid" "$port" + return $? + fi + case "$service_user" in + gateway) + # shellcheck disable=SC2016 # positional args expand in the stepped-down shell + "${STEP_DOWN_PREFIX_GATEWAY[@]}" env -u BASH_ENV \ + bash --noprofile --norc -c \ + 'source "$1"; gateway_control_pid_owns_tcp_listener "$2" "$3"' \ + bash "$_GATEWAY_SUPERVISOR" "$pid" "$port" + ;; + sandbox) + # shellcheck disable=SC2016 # positional args expand in the stepped-down shell + "${STEP_DOWN_PREFIX_SANDBOX[@]}" env -u BASH_ENV \ + bash --noprofile --norc -c \ + 'source "$1"; gateway_control_pid_owns_tcp_listener "$2" "$3"' \ + bash "$_GATEWAY_SUPERVISOR" "$pid" "$port" + ;; + *) return 1 ;; + esac +} + start_socat_forwarder() { local public_port="$1" local internal_port="$2" local label="$3" local pid_var="${4:-SOCAT_PID}" + local owner_pid="${5:-}" + local owner_user="${6:-current}" local _socat_pid + local _socat_role="" + local owner_role="" + + case "$owner_user" in + gateway) owner_role=gateway ;; + sandbox) owner_role=dashboard ;; + current) + if [ "$internal_port" = "$INTERNAL_PORT" ]; then + owner_role=gateway + elif [ "$internal_port" = "$DASHBOARD_INTERNAL_PORT" ]; then + owner_role=dashboard + fi + ;; + esac if ! command -v socat >/dev/null 2>&1; then echo "[gateway] socat not available - ${label} port forwarding from host may not work" >&2 return fi local attempts=0 + local internal_ready=0 while [ "$attempts" -lt 30 ]; do - if ss -tln 2>/dev/null | grep -q "127.0.0.1:${internal_port}"; then + if [ -n "$owner_pid" ]; then + if [ -z "$owner_role" ] \ + || ! hermes_tracked_role_is_current \ + "$owner_role" "$owner_pid" "$owner_user" "$internal_port"; then + echo "[gateway] ${label} service owner pid ${owner_pid} exited before binding 127.0.0.1:${internal_port}" >&2 + return 1 + fi + if hermes_tracked_service_owns_listener "$owner_pid" "$internal_port" "$owner_user"; then + internal_ready=1 + break + fi + elif ss -tln 2>/dev/null | grep -q "127.0.0.1:${internal_port}"; then + # Compatibility for non-supervised callers; PID 1 production paths pass + # an exact owner PID and never rely on this transport-only fallback. + internal_ready=1 break fi sleep 1 attempts=$((attempts + 1)) done + if [ "$internal_ready" -ne 1 ]; then + echo "[gateway] ${label} service did not bind 127.0.0.1:${internal_port}; refusing to publish an empty forward" >&2 + return 1 + fi nohup socat TCP-LISTEN:"${public_port}",bind=0.0.0.0,fork,reuseaddr \ TCP:127.0.0.1:"${internal_port}" >/dev/null 2>&1 & _socat_pid=$! + sleep 0.1 + if ! gateway_control_pid_is_live "$_socat_pid"; then + wait "$_socat_pid" 2>/dev/null || true + echo "[gateway] ${label} socat forwarder failed to stay running on 0.0.0.0:${public_port}" >&2 + return 1 + fi + case "$pid_var" in + SOCAT_PID) + _socat_role=api-socat + if ! hermes_capture_tracked_role api-socat "$_socat_pid" current "$public_port"; then + hermes_set_role_identity api-socat "" + hermes_fatal_unproven_child api-socat "$_socat_pid" + fi + ;; + DASHBOARD_SOCAT_PID) + _socat_role=dashboard-socat + if ! hermes_capture_tracked_role dashboard-socat "$_socat_pid" current "$public_port"; then + hermes_set_role_identity dashboard-socat "" + hermes_fatal_unproven_child dashboard-socat "$_socat_pid" + fi + ;; + esac + attempts=0 + while [ "$attempts" -lt 30 ]; do + gateway_control_pid_owns_tcp_listener "$_socat_pid" "$public_port" && break + gateway_control_pid_is_live "$_socat_pid" || break + sleep 0.1 + attempts=$((attempts + 1)) + done + if ! gateway_control_pid_owns_tcp_listener "$_socat_pid" "$public_port"; then + if [ -n "$_socat_role" ]; then + hermes_stop_tracked_role "$_socat_role" "$_socat_pid" current "$public_port" || true + fi + echo "[gateway] ${label} socat process did not own 0.0.0.0:${public_port}" >&2 + return 1 + fi printf -v "$pid_var" '%s' "$_socat_pid" echo "[gateway] ${label} socat forwarder 0.0.0.0:${public_port} -> 127.0.0.1:${internal_port} (pid ${_socat_pid})" >&2 } @@ -805,12 +1225,12 @@ prepare_hermes_dashboard_home() { echo "[SECURITY] Refusing Hermes dashboard startup because ${HERMES_DASHBOARD_HOME} is a symlink" >&2 exit 1 fi - mkdir -p "$HERMES_DASHBOARD_HOME" + mkdir -p "$HERMES_DASHBOARD_HOME" || exit 1 if [ -L "$HERMES_DASHBOARD_HOME" ] || [ ! -d "$HERMES_DASHBOARD_HOME" ]; then echo "[SECURITY] Refusing Hermes dashboard startup because ${HERMES_DASHBOARD_HOME} is not a safe directory" >&2 exit 1 fi - chmod 700 "$HERMES_DASHBOARD_HOME" + chmod 700 "$HERMES_DASHBOARD_HOME" || exit 1 # The dashboard can attempt a gateway restart from its isolated # HERMES_HOME. In NemoClaw the real gateway lives under /sandbox/.hermes, # so a failed dashboard-scoped restart can leave stale startup_failed @@ -831,12 +1251,12 @@ prepare_hermes_dashboard_home() { echo "[SECURITY] Refusing Hermes dashboard startup because ${HERMES_DASHBOARD_HOME} is a symlink" >&2 return 1 fi - mkdir -p "$HERMES_DASHBOARD_HOME" + mkdir -p "$HERMES_DASHBOARD_HOME" || return 1 if [ -L "$HERMES_DASHBOARD_HOME" ] || [ ! -d "$HERMES_DASHBOARD_HOME" ]; then echo "[SECURITY] Refusing Hermes dashboard startup because ${HERMES_DASHBOARD_HOME} is not a safe directory" >&2 return 1 fi - chmod 700 "$HERMES_DASHBOARD_HOME" + chmod 700 "$HERMES_DASHBOARD_HOME" || return 1 seed_hermes_dashboard_config } @@ -867,50 +1287,64 @@ seed_hermes_dashboard_config() { } start_hermes_dashboard_current_user() { - build_hermes_dashboard_args - prepare_hermes_dashboard_home "" - prepare_restricted_log /tmp/dashboard.log "" 600 + build_hermes_dashboard_args || return 1 + prepare_hermes_dashboard_home "" || return 1 + prepare_restricted_log /tmp/dashboard.log "" 600 || return 1 HERMES_HOME="${HERMES_DASHBOARD_HOME}" \ GATEWAY_HEALTH_URL="http://127.0.0.1:${INTERNAL_PORT}" \ nohup "$HERMES" "${HERMES_DASHBOARD_ARGS[@]}" >/tmp/dashboard.log 2>&1 & DASHBOARD_PID=$! echo "[gateway] hermes dashboard launched (pid $DASHBOARD_PID)" >&2 - start_dashboard_log_stream - start_socat_forwarder "$DASHBOARD_PUBLIC_PORT" "$DASHBOARD_INTERNAL_PORT" "dashboard" DASHBOARD_SOCAT_PID + if ! hermes_capture_tracked_role dashboard "$DASHBOARD_PID" current "$DASHBOARD_INTERNAL_PORT"; then + hermes_fatal_unproven_child dashboard "$DASHBOARD_PID" + fi + ensure_dashboard_log_stream || return 1 + start_socat_forwarder \ + "$DASHBOARD_PUBLIC_PORT" "$DASHBOARD_INTERNAL_PORT" "dashboard" DASHBOARD_SOCAT_PID \ + "$DASHBOARD_PID" current } start_hermes_dashboard_sandbox_user() { - build_hermes_dashboard_args - prepare_hermes_dashboard_home sandbox:sandbox - prepare_restricted_log /tmp/dashboard.log sandbox:sandbox 600 + build_hermes_dashboard_args || return 1 + prepare_hermes_dashboard_home sandbox:sandbox || return 1 + prepare_restricted_log /tmp/dashboard.log sandbox:sandbox 600 || return 1 HERMES_HOME="${HERMES_DASHBOARD_HOME}" \ GATEWAY_HEALTH_URL="http://127.0.0.1:${INTERNAL_PORT}" \ nohup "${STEP_DOWN_PREFIX_SANDBOX[@]}" sh -c 'umask 0077; exec "$@" >/tmp/dashboard.log 2>&1' sh "$HERMES" "${HERMES_DASHBOARD_ARGS[@]}" & DASHBOARD_PID=$! echo "[gateway] hermes dashboard launched as 'sandbox' user (pid $DASHBOARD_PID)" >&2 - start_dashboard_log_stream - start_socat_forwarder "$DASHBOARD_PUBLIC_PORT" "$DASHBOARD_INTERNAL_PORT" "dashboard" DASHBOARD_SOCAT_PID + if ! hermes_capture_tracked_role dashboard "$DASHBOARD_PID" sandbox "$DASHBOARD_INTERNAL_PORT"; then + hermes_fatal_unproven_child dashboard "$DASHBOARD_PID" + fi + ensure_dashboard_log_stream || return 1 + start_socat_forwarder \ + "$DASHBOARD_PUBLIC_PORT" "$DASHBOARD_INTERNAL_PORT" "dashboard" DASHBOARD_SOCAT_PID \ + "$DASHBOARD_PID" sandbox } wait_for_hermes_gateway_internal() { local gateway_pid="$1" - local attempts=0 + local deadline=$((SECONDS + 90)) local code - while [ "$attempts" -lt 60 ]; do + local service_user=current + [ "$(id -u)" -eq 0 ] && service_user=gateway + while [ "$SECONDS" -lt "$deadline" ]; do # Status-code extraction (not curl -sf) so a 401 counts as alive: Hermes # v0.16.0+ may guard the api_server with API_SERVER_KEY, and the probe is # unauthenticated. A 401 still proves the gateway is bound and serving. # Mirrors GATEWAY_ALIVE_CODES in src/lib/verify-deployment.ts. - code=$(curl -so /dev/null -w '%{http_code}' --max-time 2 \ - "http://127.0.0.1:${INTERNAL_PORT}/health" 2>/dev/null || echo 000) - case "$code" in - 200 | 401) return 0 ;; - esac - if ! kill -0 "$gateway_pid" 2>/dev/null; then + if hermes_tracked_role_is_current gateway "$gateway_pid" "$service_user" "$INTERNAL_PORT" \ + && hermes_tracked_service_owns_listener "$gateway_pid" "$INTERNAL_PORT" "$service_user"; then + code=$(curl -so /dev/null -w '%{http_code}' --max-time 2 \ + "http://127.0.0.1:${INTERNAL_PORT}/health" 2>/dev/null || echo 000) + case "$code" in + 200 | 401) return 0 ;; + esac + fi + if ! hermes_tracked_role_is_current gateway "$gateway_pid" "$service_user" "$INTERNAL_PORT"; then wait "$gateway_pid" return $? fi - attempts=$((attempts + 1)) sleep 1 done echo "[gateway] Hermes gateway did not become healthy on internal port ${INTERNAL_PORT}" >&2 @@ -1190,21 +1624,23 @@ refresh_hermes_provider_placeholders() { --hash-file "$HERMES_HASH_FILE" --boundary-validator "$_HERMES_BOUNDARY_VALIDATOR" --mode "$mode" + --startup-owner ) if [ -f "$runtime_plan" ]; then args+=(--runtime-plan "$runtime_plan") fi - "$_HERMES_PYTHON" "${args[@]}" + "$_HERMES_PYTHON" -I "${args[@]}" validate_hermes_env_secret_boundary } refresh_hermes_runtime_config_hashes() { local mode="${1:-strict}" local cmd=( - "$_HERMES_PYTHON" "$_HERMES_RUNTIME_CONFIG_GUARD" refresh-hashes + "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" refresh-hashes --hermes-dir "$HERMES_DIR" --hash-file "$HERMES_HASH_FILE" --mode "$mode" + --startup-owner ) if [ "$mode" = "compat" ] && [ "$(id -u)" -eq 0 ]; then "${STEP_DOWN_PREFIX_SANDBOX[@]}" "${cmd[@]}" @@ -1216,15 +1652,35 @@ refresh_hermes_runtime_config_hashes() { ensure_hermes_runtime_api_server_key() { local mode="${1:-strict}" local env_file="${HERMES_DIR}/.env" + local result_file + local guard_status [ -f "$env_file" ] || return 0 local result - result="$( - "$_HERMES_PYTHON" "$_HERMES_RUNTIME_CONFIG_GUARD" ensure-api-key \ - --hermes-dir "$HERMES_DIR" \ - --hash-file "$HERMES_HASH_FILE" \ - --mode "$mode" - )" || return $? + if [ "$EUID" -eq 0 ] && [ -d /run/nemoclaw ] && [ -w /run/nemoclaw ]; then + result_file="$(mktemp /run/nemoclaw/hermes-api-key-result.XXXXXX)" || return 1 + else + result_file="$(mktemp "${TMPDIR:-/tmp}/hermes-api-key-result.XXXXXX")" || return 1 + fi + chmod 600 "$result_file" || { + rm -f "$result_file" + return 1 + } + # Keep the guard as PID 1's direct child: --startup-owner is authenticated by + # exact parent identity. The guard's own alarm bounds this startup-only call; + # wrapping it in `timeout` would interpose a different parent process. + if "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" ensure-api-key \ + --hermes-dir "$HERMES_DIR" \ + --hash-file "$HERMES_HASH_FILE" \ + --mode "$mode" \ + --startup-owner >"$result_file"; then + guard_status=0 + else + guard_status=$? + fi + IFS= read -r result <"$result_file" || result="" + rm -f "$result_file" + [ "$guard_status" -eq 0 ] || return "$guard_status" case "$result" in minted=0) return 0 ;; @@ -1249,20 +1705,995 @@ ensure_hermes_runtime_api_server_key() { validate_hermes_env_secret_boundary() { local env_file="${HERMES_DIR}/.env" - [ -e "$env_file" ] || return 0 if [ -L "$env_file" ]; then echo "[SECURITY] Refusing Hermes startup because ${env_file} is a symlink" >&2 return 1 fi - python3 "$_HERMES_BOUNDARY_VALIDATOR" env-file "$env_file" + "${_HERMES_BOUNDARY_TIMEOUT[@]}" \ + python3 "$_HERMES_BOUNDARY_VALIDATOR" env-file "$env_file" } validate_hermes_runtime_env_secret_boundary() { - python3 "$_HERMES_BOUNDARY_VALIDATOR" runtime-env + "${_HERMES_BOUNDARY_TIMEOUT[@]}" \ + python3 "$_HERMES_BOUNDARY_VALIDATOR" runtime-env +} + +hermes_gateway_healthy() { + local pid="$1" + local code + local service_user=current + [ "$(id -u)" -eq 0 ] && service_user=gateway + hermes_tracked_role_is_current gateway "$pid" "$service_user" "$INTERNAL_PORT" || return 1 + code="$(curl -so /dev/null -w '%{http_code}' --max-time 2 \ + "http://127.0.0.1:${INTERNAL_PORT}/health" 2>/dev/null || echo 000)" + case "$code" in + 200 | 401) hermes_tracked_service_owns_listener "$pid" "$INTERNAL_PORT" gateway ;; + *) return 1 ;; + esac +} + +HERMES_RESTART_FAILURE_CODE=internal + +validate_running_hermes_boundary() { + HERMES_RESTART_FAILURE_CODE=validator-missing + [ -f "$_HERMES_BOUNDARY_VALIDATOR" ] || return 1 + HERMES_RESTART_FAILURE_CODE=secret-boundary-refusal + validate_hermes_env_secret_boundary || return 1 + validate_hermes_runtime_env_secret_boundary || return 1 + HERMES_RESTART_FAILURE_CODE=preload-missing + # shellcheck disable=SC2119 + validate_tmp_permissions || return 1 +} + +prepare_hermes_gateway_restart() { + if ! validate_running_hermes_boundary; then + return 1 + fi + + # A restart is a lifecycle action, not authority to bless arbitrary bytes + # written by the sandbox user. Supported host config commands refresh the + # root-owned strict hash when they make a change; direct in-sandbox edits do + # not. Require that trusted anchor for both mutable-default and shields-up + # sandboxes instead of chowning attacker-controlled paths or adopting a new + # hash here. + HERMES_RESTART_FAILURE_CODE=hash-mismatch + verify_hermes_config_integrity +} + +hermes_restart_unseal_on_exit() { + [ "$HERMES_RESTART_SEALED" -eq 1 ] || return 0 + [ "$HERMES_RESTART_UNSEALING" -eq 0 ] || return 1 + unseal_hermes_restart_inputs || true +} + +hermes_restart_cleanup_on_signal() { + if [ "$HERMES_RESTART_UNSEALING" -eq 1 ]; then + HERMES_RESTART_SIGNAL_PENDING=1 + return 0 + fi + stop_hermes_gateway_fail_closed + if [ "$HERMES_RESTART_SEALED" -eq 1 ]; then + unseal_hermes_restart_inputs || true + fi + refresh_hermes_supervised_child_pids + hermes_cleanup_on_signal +} + +install_hermes_restart_seal_traps() { + trap hermes_restart_unseal_on_exit EXIT + trap hermes_restart_cleanup_on_signal SIGTERM SIGINT HUP +} + +restore_hermes_runtime_traps() { + trap - EXIT HUP + trap hermes_cleanup_on_signal SIGTERM SIGINT +} + +seal_hermes_restart_inputs() { + local output + local owner_output + local original_failure_code + HERMES_RESTART_FAILURE_CODE=unsafe-config + HERMES_RESTART_SEALED=0 + install_hermes_restart_seal_traps + if ! output="$( + "${_HERMES_GUARD_TIMEOUT[@]}" "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" seal-restart \ + --hermes-dir "$HERMES_DIR" \ + --hash-file "$HERMES_HASH_FILE" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --lock-token "$GATEWAY_CONTROL_NONCE" 2>&1 + )"; then + printf '%s\n' "$output" >&2 + case "$output" in + *"strict hash verification failed"*) HERMES_RESTART_FAILURE_CODE=hash-mismatch ;; + esac + # The guard normally rolls back failures it owns. If rollback itself was + # interrupted, recover only a state whose cryptographic token is this + # request nonce. A concurrent config/shields transaction has a different + # token and must never be unsealed or used as authority to stop the healthy + # gateway. + original_failure_code="$HERMES_RESTART_FAILURE_CODE" + if owner_output="$( + "${_HERMES_GUARD_TIMEOUT[@]}" "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" inspect-mutation-owner \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --lock-token "$GATEWAY_CONTROL_NONCE" 2>&1 + )"; then + case "$owner_output" in + *"token_match=1"*) + case "$owner_output" in + *"original_locked=1"*) HERMES_RESTART_ORIGINAL_LOCKED=1 ;; + *) HERMES_RESTART_ORIGINAL_LOCKED=0 ;; + esac + HERMES_RESTART_SEALED=1 + if unseal_hermes_restart_inputs; then + HERMES_RESTART_FAILURE_CODE="$original_failure_code" + fi + return 1 + ;; + esac + else + printf '%s\n' "$owner_output" >&2 + fi + restore_hermes_runtime_traps + return 1 + fi + case "$output" in + *"original_locked=1"*) HERMES_RESTART_ORIGINAL_LOCKED=1 ;; + *) HERMES_RESTART_ORIGINAL_LOCKED=0 ;; + esac + HERMES_RESTART_SEALED=1 +} + +unseal_hermes_restart_inputs() { + local output + if [ "$HERMES_RESTART_SEALED" -ne 1 ] && [ ! -e "$HERMES_RESTART_SEAL_STATE" ]; then + return 0 + fi + if [ "$HERMES_RESTART_UNSEALING" -eq 1 ]; then + HERMES_RESTART_FAILURE_CODE=unsafe-config + return 1 + fi + HERMES_RESTART_UNSEALING=1 + trap 'HERMES_RESTART_SIGNAL_PENDING=1' SIGTERM SIGINT HUP + if ! output="$( + "${_HERMES_GUARD_TIMEOUT[@]}" "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" unseal-restart \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" 2>&1 + )"; then + printf '%s\n' "$output" >&2 + HERMES_RESTART_FAILURE_CODE=unsafe-config + HERMES_RESTART_UNSEALING=0 + trap hermes_restart_cleanup_on_signal SIGTERM SIGINT HUP + if [ "$HERMES_RESTART_SIGNAL_PENDING" -eq 1 ]; then + # Do not recursively retry an unseal that just failed. Retain the token, + # clear the EXIT retry, and honor the deferred stop signal fail-closed. + HERMES_RESTART_SIGNAL_PENDING=0 + trap - EXIT HUP TERM INT + refresh_hermes_supervised_child_pids + hermes_cleanup_on_signal + fi + return 1 + fi + HERMES_RESTART_SEALED=0 + HERMES_RESTART_UNSEALING=0 + restore_hermes_runtime_traps + if [ "$HERMES_RESTART_SIGNAL_PENDING" -eq 1 ]; then + HERMES_RESTART_SIGNAL_PENDING=0 + hermes_cleanup_on_signal + fi +} + +stop_hermes_gateway_fail_closed() { + if ! hermes_stop_tracked_role gateway "${GATEWAY_PID:-0}" gateway "$INTERNAL_PORT"; then + echo "[CRITICAL] Hermes gateway revocation could not prove and stop the tracked child; exiting PID 1 for whole-container cleanup without signaling the unproven PID" >&2 + exit 1 + fi + mark_hermes_gateway_stopped +} + +hermes_restart_seal_orphaned() { + local marker_meta + local sandbox_meta + + [ ! -e "$HERMES_RESTART_SEAL_STATE" ] || return 1 + marker_meta="$(stat -c '%u:%g %a' "$HERMES_RESTART_ORPHAN_MARKER" 2>/dev/null || true)" + sandbox_meta="$(stat -c '%u:%g %a' /sandbox 2>/dev/null || true)" + # Mutable mode keeps /sandbox sandbox-owned. Locked mode deliberately uses + # root:sandbox with the sticky bit so the sandbox user cannot rename the + # root-owned .hermes entry. Only an in-flight transaction uses root:root; + # that remains the durable discriminator when `/run` recovery state is lost. + case "$marker_meta" in + "0:0 400") ;; + *) + case "$sandbox_meta" in + "0:0 "*) ;; + *) return 1 ;; + esac + ;; + esac + + # Hash validation only enriches the diagnostic. Never let missing/partial + # child seal state turn the recognized orphan transaction into normal start. + if ! verify_hermes_config_integrity; then + echo "[SECURITY] Orphaned Hermes restart seal also failed strict hash validation" >&2 + fi + return 0 +} + +resume_startup_hermes_shields_lock() { + local result_file + local begin_output + local lock_token + + result_file="$(mktemp "$(dirname "$HERMES_RESTART_SEAL_STATE")/hermes-shields-resume.XXXXXX")" || return 1 + chmod 600 "$result_file" || { + rm -f "$result_file" + return 1 + } + # These guard calls must remain direct PID 1 children. The internal Python + # alarm is their deadline; the recursive helper is separately wrapped by the + # container-side timeout because it has no startup-owner parent contract. + if ! "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" begin-shields-transition \ + --hermes-dir "$HERMES_DIR" \ + --hash-file "$HERMES_HASH_FILE" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --shields-mode locked \ + --startup-owner >"$result_file"; then + rm -f "$result_file" + return 1 + fi + IFS= read -r begin_output <"$result_file" || begin_output="" + rm -f "$result_file" + case "$begin_output" in + lock_token=*" original_locked="[01]) + lock_token="${begin_output#lock_token=}" + lock_token="${lock_token%% *}" + ;; + *) + echo "[SECURITY] Invalid Hermes shields resume response" >&2 + return 1 + ;; + esac + if [ "${#lock_token}" -ne 64 ]; then + echo "[SECURITY] Invalid Hermes shields resume token" >&2 + return 1 + fi + case "$lock_token" in + *[!0-9a-f]*) + echo "[SECURITY] Invalid Hermes shields resume token" >&2 + return 1 + ;; + esac + + "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" run-state-dir-transition \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --state-action lock \ + --lock-token "$lock_token" \ + --startup-owner || return 1 + "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" apply-shields-transition \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --lock-token "$lock_token" \ + --startup-owner >/dev/null || return 1 + "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" finish-shields-transition \ + --hermes-dir "$HERMES_DIR" \ + --hash-file "$HERMES_HASH_FILE" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --lock-token "$lock_token" \ + --startup-owner >/dev/null +} + +recover_startup_hermes_mutation() { + local attempts=0 + local owner_output + + while [ -e "$HERMES_CONFIG_MUTATION_LOCK" ] || [ -e "$HERMES_RESTART_SEAL_STATE" ]; do + if ! owner_output="$( + "${_HERMES_GUARD_TIMEOUT[@]}" "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" inspect-mutation-owner \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" 2>&1 + )"; then + printf '%s\n' "$owner_output" >&2 + return 1 + fi + + case "$owner_output" in + *"resumable_lock=1"*) + if resume_startup_hermes_shields_lock; then + echo "[security] Resumed interrupted Hermes shields lock before startup" >&2 + attempts=0 + continue + fi + echo "[SECURITY] HERMES_SHIELDS_RESUME_PENDING: the root-only shields clamp remains active; retry sandbox startup after the recursive guard can complete" >&2 + return 1 + ;; + esac + + case "$owner_output" in + *"owner_active=1"*) + attempts=$((attempts + 1)) + if [ "$attempts" -ge 300 ]; then + echo "[SECURITY] HERMES_CONFIG_MUTATION_BUSY: a root config transaction is still active; retry sandbox startup after it finishes" >&2 + return 1 + fi + sleep 0.1 + continue + ;; + esac + + case "$owner_output" in + *"state=1"*) + case "$owner_output" in + *"recovery_safe=0"*) + echo "[SECURITY] HERMES_CONFIG_MUTATION_ORPHANED: an interrupted shields transition is sealed fail-closed; restore from a trusted backup and recreate the sandbox (an in-place rebuild cannot read the sealed state)" >&2 + return 1 + ;; + esac + # The recorded owner is gone. Recovery is now exclusively owned by PID + # 1; restore the exact metadata/digest transaction before startup reads + # any mutable Hermes path. + HERMES_RESTART_SEALED=1 + install_hermes_restart_seal_traps + unseal_hermes_restart_inputs || return 1 + ;; + *"lock=1"*) + if "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" recover-prestate-lock \ + --hermes-dir "$HERMES_DIR" \ + --state-file "$HERMES_RESTART_SEAL_STATE" \ + --startup-owner >/dev/null; then + echo "[security] Removed a dead Hermes pre-state mutation lock" >&2 + attempts=0 + continue + fi + echo "[SECURITY] HERMES_CONFIG_MUTATION_ORPHANED: mutation lock recovery failed; retry startup or restore from a trusted backup" >&2 + return 1 + ;; + *) return 0 ;; + esac + done +} + +hermes_socat_bridge_healthy() { + local role="$1" + local pid="$2" + local port="$3" + hermes_tracked_role_is_current "$role" "$pid" current "$port" || return 1 + gateway_control_pid_owns_tcp_listener "$pid" "$port" +} + +hermes_dashboard_healthy() { + local pid="$1" + local code + local service_user=current + [ "$(id -u)" -eq 0 ] && service_user=sandbox + hermes_tracked_role_is_current dashboard "$pid" "$service_user" "$DASHBOARD_INTERNAL_PORT" || return 1 + hermes_tracked_service_owns_listener "$pid" "$DASHBOARD_INTERNAL_PORT" sandbox || return 1 + code="$(curl -so /dev/null -w '%{http_code}' --max-time 3 \ + "http://127.0.0.1:${DASHBOARD_INTERNAL_PORT}/" 2>/dev/null || true)" + case "$code" in + 200 | 301 | 302 | 307 | 308) return 0 ;; + *) return 1 ;; + esac +} + +hermes_auxiliaries_need_recovery() { + hermes_socat_bridge_healthy api-socat "${SOCAT_PID:-}" "$PUBLIC_PORT" || return 0 + hermes_dashboard_healthy "${DASHBOARD_PID:-}" || return 0 + hermes_socat_bridge_healthy dashboard-socat "${DASHBOARD_SOCAT_PID:-}" "$DASHBOARD_PUBLIC_PORT" || return 0 + return 1 +} + +cleanup_sealed_hermes_gateway_runtime() { + # shellcheck disable=SC2016 # positional args expand in the stepped-down shell + "${STEP_DOWN_PREFIX_GATEWAY[@]}" sh -c ' + rm -f "$1/runtime/gateway.pid" "$1/runtime/gateway.lock" + ' sh "$HERMES_DIR" +} + +launch_hermes_gateway() { + # This function is called from an `if ! ...` recovery branch, where Bash + # disables errexit throughout the function call. Propagate every security- + # sensitive preparation failure explicitly before creating a child. + apply_shields_up_runtime_env || return 1 + if [ "$HERMES_RESTART_SEALED" -ne 1 ]; then + cleanup_stale_hermes_gateway_runtime || return 1 + fi + HERMES_HOME="${HERMES_DIR}" \ + nohup "${STEP_DOWN_PREFIX_GATEWAY[@]}" sh -c \ + 'umask 0007; exec "$@" >>/tmp/gateway.log 2>&1' sh "$HERMES" gateway run & + GATEWAY_PID=$! + if ! hermes_capture_tracked_role gateway "$GATEWAY_PID" gateway "$INTERNAL_PORT"; then + hermes_fatal_unproven_child gateway "$GATEWAY_PID" + fi + # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh + SANDBOX_WAIT_PID="$GATEWAY_PID" + echo "[gateway] hermes gateway launched as 'gateway' user (pid $GATEWAY_PID)" >&2 +} + +ensure_hermes_supervised_auxiliaries() { + local gateway_user=current + local dashboard_user=current + if [ "$(id -u)" -eq 0 ]; then + gateway_user=gateway + dashboard_user=sandbox + fi + + if ! hermes_socat_bridge_healthy api-socat "${SOCAT_PID:-}" "$PUBLIC_PORT"; then + hermes_stop_tracked_role api-socat "${SOCAT_PID:-0}" current "$PUBLIC_PORT" || return 1 + SOCAT_PID="" + start_socat_forwarder \ + "$PUBLIC_PORT" "$INTERNAL_PORT" "API" SOCAT_PID "$GATEWAY_PID" "$gateway_user" || return 1 + fi + if ! hermes_dashboard_healthy "${DASHBOARD_PID:-}"; then + # A live PID is not sufficient: it may be reused, alive without the exact + # dashboard listener, or serving a wedged HTTP process. Stop both tracked + # children before relaunch so the replacement cannot lose either bind race. + hermes_stop_tracked_role dashboard-socat "${DASHBOARD_SOCAT_PID:-0}" current "$DASHBOARD_PUBLIC_PORT" || return 1 + DASHBOARD_SOCAT_PID="" + hermes_stop_tracked_role dashboard "${DASHBOARD_PID:-0}" "$dashboard_user" "$DASHBOARD_INTERNAL_PORT" || return 1 + DASHBOARD_PID="" + if [ "$(id -u)" -eq 0 ]; then + start_hermes_dashboard_sandbox_user || return 1 + else + start_hermes_dashboard_current_user || return 1 + fi + elif ! hermes_socat_bridge_healthy dashboard-socat "${DASHBOARD_SOCAT_PID:-}" "$DASHBOARD_PUBLIC_PORT"; then + hermes_stop_tracked_role dashboard-socat "${DASHBOARD_SOCAT_PID:-0}" current "$DASHBOARD_PUBLIC_PORT" || return 1 + DASHBOARD_SOCAT_PID="" + start_socat_forwarder \ + "$DASHBOARD_PUBLIC_PORT" "$DASHBOARD_INTERNAL_PORT" "dashboard" DASHBOARD_SOCAT_PID \ + "$DASHBOARD_PID" "$dashboard_user" || return 1 + fi + ensure_gateway_log_stream || return 1 +} + +refresh_hermes_supervised_child_pids() { + local gateway_user=current + local dashboard_user=current + SANDBOX_CHILD_PIDS=() + if [ "$(id -u)" -eq 0 ]; then + gateway_user=gateway + dashboard_user=sandbox + fi + hermes_tracked_role_is_current gateway "${GATEWAY_PID:-}" "$gateway_user" "$INTERNAL_PORT" \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_PID") + hermes_tracked_role_is_current dashboard "${DASHBOARD_PID:-}" "$dashboard_user" "$DASHBOARD_INTERNAL_PORT" \ + && SANDBOX_CHILD_PIDS+=("$DASHBOARD_PID") + hermes_tracked_role_is_current api-socat "${SOCAT_PID:-}" current "$PUBLIC_PORT" \ + && SANDBOX_CHILD_PIDS+=("$SOCAT_PID") + hermes_tracked_role_is_current dashboard-socat "${DASHBOARD_SOCAT_PID:-}" current "$DASHBOARD_PUBLIC_PORT" \ + && SANDBOX_CHILD_PIDS+=("$DASHBOARD_SOCAT_PID") + hermes_tracked_role_is_current gateway-log "${GATEWAY_LOG_TAIL_PID:-}" current \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") + hermes_tracked_role_is_current dashboard-log "${DASHBOARD_LOG_TAIL_PID:-}" current \ + && SANDBOX_CHILD_PIDS+=("$DASHBOARD_LOG_TAIL_PID") +} + +hermes_cleanup_on_signal() { + local gateway_user=current + [ "$(id -u)" -eq 0 ] && gateway_user=gateway + refresh_hermes_supervised_child_pids + if ! hermes_tracked_role_is_current gateway "${GATEWAY_PID:-}" "$gateway_user" "$INTERNAL_PORT"; then + # The shared cleanup helper must never wait on or signal a PID that has + # been reused/adopted since NemoClaw captured the gateway start identity. + SANDBOX_WAIT_PID="" + fi + cleanup_on_signal +} + +mark_hermes_gateway_stopped() { + GATEWAY_PID=0 + GATEWAY_PID_START_IDENTITY="" + # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh + SANDBOX_WAIT_PID="" + refresh_hermes_supervised_child_pids +} + +hermes_reap_exited_gateway() { + local pid="${GATEWAY_PID:-0}" + local expected_start_identity="${GATEWAY_PID_START_IDENTITY:-}" + local current_start_identity state + local rc=0 + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + [ -n "$expected_start_identity" ] || return 1 + + current_start_identity="$(hermes_process_start_identity "$pid" 2>/dev/null || true)" + if [ -n "$current_start_identity" ] \ + && [ "$current_start_identity" != "$expected_start_identity" ]; then + echo "[SECURITY] Hermes gateway pid $pid no longer matches its captured start identity; refusing to poll or reap it" >&2 + return 2 + fi + + # kill -0 also succeeds for zombies. Only the exact matching zombie is safe + # to reap. A live process, or one whose state/identity cannot be proven, must + # not send PID 1 into an unbounded wait or let an interrupted wait forget a + # still-running gateway. + if kill -0 "$pid" 2>/dev/null; then + state="$(gateway_control_pid_state "$pid" 2>/dev/null || true)" + case "$state" in + Z*) [ "$current_start_identity" = "$expected_start_identity" ] || return 2 ;; + *) + if [ "${GATEWAY_CONTROL_SIGNAL_PENDING:-0}" -eq 1 ] \ + && hermes_tracked_role_is_current gateway "$pid" gateway "$INTERNAL_PORT"; then + return 3 + fi + echo "[SECURITY] Hermes gateway pid $pid cannot be proven exited with its captured role identity; refusing to reap it" >&2 + return 2 + ;; + esac + fi + + # If the proc entry is already gone, Bash's child-status table keeps this + # wait scoped to the original direct child rather than an unrelated PID. + wait "$pid" 2>/dev/null || rc=$? + # USR1 may interrupt wait before it reaps the exact child. Preserve the + # tracked identity and let the authenticated request handler own the child. + if [ "${GATEWAY_CONTROL_SIGNAL_PENDING:-0}" -eq 1 ] \ + && hermes_tracked_role_is_current gateway "$pid" gateway "$INTERNAL_PORT"; then + return 3 + fi + echo "[gateway] Hermes gateway pid $pid exited (rc=$rc); awaiting host recovery" >&2 + mark_hermes_gateway_stopped +} + +handle_hermes_gateway_control_request() { + gateway_control_take_request || return 1 + local old_pid="${GATEWAY_PID:-0}" + local failure_code + + if [ "$GATEWAY_CONTROL_ACTION" = "probe" ]; then + if ! prepare_hermes_gateway_restart; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + if ! gateway_control_pid_is_live "$old_pid" \ + || ! hermes_gateway_healthy "$old_pid" \ + || hermes_auxiliaries_need_recovery; then + gateway_control_fail health-timeout "$old_pid" + return 1 + fi + gateway_control_complete already-running "$old_pid" "$old_pid" + return 0 + fi + + if [ "$GATEWAY_CONTROL_ACTION" = "recover" ] \ + && gateway_control_pid_is_live "$old_pid" \ + && hermes_gateway_healthy "$old_pid"; then + # Recovery may also recreate the dashboard from the shared Hermes config. + # Verify the root-owned trust anchor before any auxiliary consumes it; a + # healthy gateway is not authority to bless direct sandbox config drift. + if ! prepare_hermes_gateway_restart; then + if [ "$HERMES_RESTART_FAILURE_CODE" = "secret-boundary-refusal" ]; then + stop_hermes_gateway_fail_closed + fi + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + if hermes_auxiliaries_need_recovery; then + if ! seal_hermes_restart_inputs; then + if [ "$HERMES_RESTART_SEALED" -eq 1 ]; then + stop_hermes_gateway_fail_closed + fi + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + # Re-run boundary + hash validation against the fresh sealed inodes. A + # pre-open attacker fd cannot change these pathnames after this point. + if ! prepare_hermes_gateway_restart; then + failure_code="$HERMES_RESTART_FAILURE_CODE" + if [ "$failure_code" = "secret-boundary-refusal" ]; then + # A post-seal boundary refusal means the currently running service no + # longer has a boundary we can prove safe. Stop it even if metadata + # restoration subsequently fails. + stop_hermes_gateway_fail_closed + fi + if ! unseal_hermes_restart_inputs; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + gateway_control_fail "$failure_code" "$old_pid" + return 1 + fi + if ! ensure_hermes_supervised_auxiliaries; then + if ! unseal_hermes_restart_inputs; then + stop_hermes_gateway_fail_closed + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + else + gateway_control_fail launch-failed "$old_pid" + fi + refresh_hermes_supervised_child_pids + return 1 + fi + if ! unseal_hermes_restart_inputs; then + stop_hermes_gateway_fail_closed + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + fi + refresh_hermes_supervised_child_pids + gateway_control_complete already-running "$old_pid" "$old_pid" + return 0 + fi + + if ! prepare_hermes_gateway_restart; then + if [ "$HERMES_RESTART_FAILURE_CODE" = "secret-boundary-refusal" ]; then + stop_hermes_gateway_fail_closed + fi + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + + # Seal and revalidate while the old gateway is still healthy. A seal failure + # must not turn a rejected config into an avoidable outage. + if ! seal_hermes_restart_inputs; then + if [ "$HERMES_RESTART_SEALED" -eq 1 ]; then + stop_hermes_gateway_fail_closed + fi + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + if ! prepare_hermes_gateway_restart; then + failure_code="$HERMES_RESTART_FAILURE_CODE" + if [ "$failure_code" = "secret-boundary-refusal" ]; then + # Do not leave the old gateway alive after a boundary refusal merely + # because restoring the restart seal also fails. + stop_hermes_gateway_fail_closed + fi + if ! unseal_hermes_restart_inputs; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + gateway_control_fail "$failure_code" "$old_pid" + return 1 + fi + + if ! hermes_stop_tracked_role gateway "$old_pid" gateway "$INTERNAL_PORT"; then + if ! unseal_hermes_restart_inputs; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + else + gateway_control_fail internal "$old_pid" + fi + return 1 + fi + mark_hermes_gateway_stopped + + if ! cleanup_sealed_hermes_gateway_runtime; then + if ! unseal_hermes_restart_inputs; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + else + gateway_control_fail unsafe-config "$old_pid" + fi + return 1 + fi + + if ! launch_hermes_gateway || ! wait_for_hermes_gateway_internal "$GATEWAY_PID"; then + stop_hermes_gateway_fail_closed + if ! unseal_hermes_restart_inputs; then + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + else + gateway_control_fail health-timeout "$old_pid" + fi + return 1 + fi + if ! ensure_hermes_supervised_auxiliaries; then + refresh_hermes_supervised_child_pids + if ! unseal_hermes_restart_inputs; then + stop_hermes_gateway_fail_closed + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + else + gateway_control_fail launch-failed "$old_pid" + fi + return 1 + fi + if ! unseal_hermes_restart_inputs; then + stop_hermes_gateway_fail_closed + gateway_control_fail "$HERMES_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + refresh_hermes_supervised_child_pids + gateway_control_complete ok "$old_pid" "$GATEWAY_PID" +} + +prepare_hermes_nonroot_runtime() { + if ! verify_config_integrity_if_locked "${HERMES_DIR}"; then + echo "[SECURITY] Config integrity check failed — refusing to start (non-root mode)" >&2 + return 1 + fi + ensure_hermes_runtime_api_server_key compat || return 1 + apply_shields_up_runtime_env || return 1 + validate_hermes_env_secret_boundary || return 1 + validate_hermes_runtime_env_secret_boundary || return 1 + refresh_hermes_provider_placeholders compat || return 1 + refresh_hermes_runtime_config_hashes compat || return 1 + configure_messaging_channels || return 1 + retry_tirith_marker_if_needed || return 1 +} + +launch_hermes_gateway_current_user() { + cleanup_stale_hermes_gateway_runtime || return 1 + HERMES_HOME="${HERMES_DIR}" \ + nohup "$HERMES" gateway run >>/tmp/gateway.log 2>&1 & + GATEWAY_PID=$! + if ! hermes_capture_tracked_role gateway "$GATEWAY_PID" current "$INTERNAL_PORT"; then + hermes_fatal_unproven_child gateway "$GATEWAY_PID" + fi + # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh + SANDBOX_WAIT_PID="$GATEWAY_PID" + echo "[gateway] hermes gateway launched (pid $GATEWAY_PID)" >&2 +} + +HERMES_MANAGED_GATEWAY_EXIT_TIMES=() +HERMES_MANAGED_GATEWAY_EXIT_COUNT=0 +readonly HERMES_MANAGED_EXPECTED_EXIT_DIR="/run/nemoclaw" +readonly HERMES_MANAGED_EXPECTED_EXIT_MARKER="managed-gateway-expected-exit" +readonly HERMES_MANAGED_CONTROLLER_PATH="/usr/local/lib/nemoclaw/managed-gateway-control.py" + +quarantine_hermes_managed_gateway_relaunch() { + while :; do + sleep 60 || true + done +} + +hermes_managed_controller_argv_is_expected() { + [ "$#" -eq 5 ] || return 1 + case "${1##*/}" in + python3) ;; + *) return 1 ;; + esac + [ "$2" = "-I" ] && [ "$3" = "$HERMES_MANAGED_CONTROLLER_PATH" ] || return 1 + case "$4" in + restart | recover) ;; + *) return 1 ;; + esac + case "$5" in + '' | *[!0-9a-f]*) return 1 ;; + esac + [ "${#5}" -eq 64 ] +} + +hermes_managed_controller_is_live() { + local pid="$1" + local expected_start_identity="$2" + local proc_root="${_HERMES_PROC_ROOT:-/proc}" + local first_start second_start first_state second_state first_uids second_uids + local -a first_argv=() + local -a second_argv=() + + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + case "$expected_start_identity" in + '' | *[!0-9]*) return 1 ;; + esac + [ -r "${proc_root}/${pid}/status" ] \ + && [ -r "${proc_root}/${pid}/cmdline" ] || return 1 + + first_start="$(gateway_control_pid_start_identity "$pid")" || return 1 + first_state="$(gateway_control_pid_state "$pid")" || return 1 + first_uids="$(awk '/^Uid:/ { print $2 ":" $3 ":" $4 ":" $5; exit }' "${proc_root}/${pid}/status")" || return 1 + mapfile -d '' -t first_argv <"${proc_root}/${pid}/cmdline" || return 1 + hermes_managed_controller_argv_is_expected "${first_argv[@]}" || return 1 + + second_start="$(gateway_control_pid_start_identity "$pid")" || return 1 + second_state="$(gateway_control_pid_state "$pid")" || return 1 + second_uids="$(awk '/^Uid:/ { print $2 ":" $3 ":" $4 ":" $5; exit }' "${proc_root}/${pid}/status")" || return 1 + mapfile -d '' -t second_argv <"${proc_root}/${pid}/cmdline" || return 1 + hermes_managed_controller_argv_is_expected "${second_argv[@]}" || return 1 + + [ "$first_start" = "$expected_start_identity" ] \ + && [ "$second_start" = "$expected_start_identity" ] \ + && [ "$first_uids" = "0:0:0:0" ] \ + && [ "$second_uids" = "0:0:0:0" ] \ + && [ "$first_state" != "Z" ] \ + && [ "$second_state" != "Z" ] \ + && [ "${first_argv[*]}" = "${second_argv[*]}" ] +} + +hermes_managed_gateway_exit_was_host_authorized() { + local pid="$1" + local start_identity="$2" + local marker dir_metadata marker_metadata + local version marker_pid marker_start_identity controller_pid controller_start_identity extra + local trailing="" + local marker_fd + + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + case "$start_identity" in + '' | *[!0-9]*) return 1 ;; + esac + + [ -d "$HERMES_MANAGED_EXPECTED_EXIT_DIR" ] \ + && [ ! -L "$HERMES_MANAGED_EXPECTED_EXIT_DIR" ] || return 1 + dir_metadata="$(stat -c '%u:%g %a' "$HERMES_MANAGED_EXPECTED_EXIT_DIR" 2>/dev/null || true)" + [ "$dir_metadata" = "0:0 711" ] || return 1 + + marker="${HERMES_MANAGED_EXPECTED_EXIT_DIR}/${HERMES_MANAGED_EXPECTED_EXIT_MARKER}" + [ -f "$marker" ] && [ ! -L "$marker" ] || return 1 + marker_metadata="$(stat -c '%u:%g %a %h' "$marker" 2>/dev/null || true)" + [ "$marker_metadata" = "0:0 444 1" ] || return 1 + + exec {marker_fd}<"$marker" || return 1 + if ! IFS=' ' read -r \ + version marker_pid marker_start_identity controller_pid controller_start_identity extra \ + <&"$marker_fd"; then + exec {marker_fd}<&- + return 1 + fi + if IFS= read -r trailing <&"$marker_fd" || [ -n "$trailing" ]; then + exec {marker_fd}<&- + return 1 + fi + exec {marker_fd}<&- + + [ "$version" = "v1" ] \ + && [ "$marker_pid" = "$pid" ] \ + && [ "$marker_start_identity" = "$start_identity" ] \ + && [ -z "${extra:-}" ] || return 1 + case "$controller_pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + case "$controller_start_identity" in + '' | *[!0-9]*) return 1 ;; + esac + hermes_managed_controller_is_live "$controller_pid" "$controller_start_identity" +} + +record_hermes_managed_gateway_exit() { + local now timestamp + local -a retained=() + + now="$(date +%s)" + HERMES_MANAGED_GATEWAY_EXIT_TIMES+=("$now") + for timestamp in "${HERMES_MANAGED_GATEWAY_EXIT_TIMES[@]+"${HERMES_MANAGED_GATEWAY_EXIT_TIMES[@]}"}"; do + [ $((now - timestamp)) -le 60 ] && retained+=("$timestamp") + done + HERMES_MANAGED_GATEWAY_EXIT_TIMES=("${retained[@]+"${retained[@]}"}") + HERMES_MANAGED_GATEWAY_EXIT_COUNT=${#HERMES_MANAGED_GATEWAY_EXIT_TIMES[@]} + if [ "$HERMES_MANAGED_GATEWAY_EXIT_COUNT" -ge 5 ]; then + echo "[gateway] CRITICAL: $HERMES_MANAGED_GATEWAY_EXIT_COUNT exits in 60s window — Hermes relaunch is quarantined until sandbox recreation; check /tmp/gateway.log" >&2 + quarantine_hermes_managed_gateway_relaunch + return 1 + fi +} + +recover_hermes_gateway_current_user() { + while :; do + until prepare_hermes_nonroot_runtime; do + echo "[gateway] Hermes runtime preparation refused automatic respawn; retrying in 5s" >&2 + sleep 5 || true + done + if ! launch_hermes_gateway_current_user; then + echo "[gateway] Hermes gateway launch failed; retrying under the same supervisor" >&2 + sleep 5 || true + continue + fi + if wait_for_hermes_gateway_internal "$GATEWAY_PID" \ + && ensure_hermes_supervised_auxiliaries; then + refresh_hermes_supervised_child_pids + return 0 + fi + + echo "[gateway] Hermes replacement failed health or auxiliary validation; stopping the exact child" >&2 + if ! hermes_stop_tracked_role \ + gateway "$GATEWAY_PID" current "$INTERNAL_PORT"; then + echo "[gateway] CRITICAL: exact Hermes replacement could not be stopped; managed supervisor is quarantined without another launch" >&2 + quarantine_hermes_managed_gateway_relaunch + return 1 + fi + mark_hermes_gateway_stopped + record_hermes_managed_gateway_exit || return 1 + sleep 2 || true + done +} + +supervise_hermes_gateway_current_user() { + local exited_gateway_pid exited_gateway_start_identity rc respawn_count unhealthy_streak=0 + + while :; do + # Keep one exact supervisor alive for the full managed OpenShell process + # tree and continuously repair its dashboard and internal relays. + while hermes_tracked_role_is_current gateway "$GATEWAY_PID" current "$INTERNAL_PORT"; do + if hermes_gateway_healthy "$GATEWAY_PID"; then + unhealthy_streak=0 + if ! ensure_hermes_supervised_auxiliaries; then + echo "[gateway] Hermes auxiliary repair failed; retrying while the exact gateway remains supervised" >&2 + fi + else + unhealthy_streak=$((unhealthy_streak + 1)) + echo "[gateway] Hermes gateway failed health validation ($unhealthy_streak/4)" >&2 + if [ "$unhealthy_streak" -ge 4 ]; then + echo "[gateway] CRITICAL: Hermes gateway lost its listener or health endpoint; stopping the exact child for recovery" >&2 + if ! hermes_stop_tracked_role \ + gateway "$GATEWAY_PID" current "$INTERNAL_PORT"; then + echo "[gateway] CRITICAL: unhealthy Hermes gateway could not be stopped; managed supervisor is quarantined without another launch" >&2 + quarantine_hermes_managed_gateway_relaunch + return 1 + fi + break + fi + fi + refresh_hermes_supervised_child_pids + sleep 1 || true + done + + exited_gateway_pid="$GATEWAY_PID" + exited_gateway_start_identity="${GATEWAY_PID_START_IDENTITY:-}" + rc=0 + wait "$GATEWAY_PID" 2>/dev/null || rc=$? + mark_hermes_gateway_stopped + + if hermes_managed_gateway_exit_was_host_authorized \ + "$exited_gateway_pid" "$exited_gateway_start_identity"; then + echo "[gateway] Hermes gateway pid $exited_gateway_pid exited (rc=$rc; authenticated host authorization); respawning without charging crash quarantine in 2s" >&2 + else + record_hermes_managed_gateway_exit || return 1 + respawn_count="$HERMES_MANAGED_GATEWAY_EXIT_COUNT" + echo "[gateway] Hermes gateway pid $exited_gateway_pid exited (rc=$rc); respawning (#$respawn_count in 60s window) in 2s" >&2 + fi + sleep 2 || true + + recover_hermes_gateway_current_user || return 1 + echo "[gateway] Hermes gateway respawned (pid $GATEWAY_PID)" >&2 + done +} + +bootstrap_hermes_gateway_current_user() { + launch_hermes_gateway_current_user || return 1 + start_gateway_log_stream + refresh_hermes_supervised_child_pids + trap hermes_cleanup_on_signal SIGTERM SIGINT + + if wait_for_hermes_gateway_internal "$GATEWAY_PID" \ + && ensure_hermes_supervised_auxiliaries; then + refresh_hermes_supervised_child_pids + return 0 + fi + + echo "[gateway] Initial Hermes gateway failed health or auxiliary validation; stopping the exact child for supervised recovery" >&2 + if ! hermes_stop_tracked_role \ + gateway "$GATEWAY_PID" current "$INTERNAL_PORT"; then + echo "[gateway] CRITICAL: initial Hermes gateway could not be stopped; managed supervisor is quarantined without another launch" >&2 + quarantine_hermes_managed_gateway_relaunch + return 1 + fi + mark_hermes_gateway_stopped + record_hermes_managed_gateway_exit || return 1 + sleep 2 || true + recover_hermes_gateway_current_user || return 1 + refresh_hermes_supervised_child_pids } # ── Main ───────────────────────────────────────────────────────── +# A PID 1 interruption within the same container writable layer can leave the +# root-only seal token behind. Restore it before any startup migration or config +# read. `/run` is not persistent across container recreation, so recognize the +# distinctive frozen parent + sealed-file posture when the token is gone and +# require a rebuild instead of guessing the original ownership/mode/flags. +if [ "$(id -u)" -eq 0 ]; then + recover_startup_hermes_mutation || exit 1 + if hermes_restart_seal_orphaned; then + echo "[SECURITY] HERMES_RESTART_SEAL_ORPHANED: restart recovery metadata was lost; restore from a trusted backup and recreate the sandbox" >&2 + exit 1 + fi + if hermes_config_root_is_locked && ! hermes_locked_parent_is_protected; then + echo "[SECURITY] HERMES_LOCKED_PARENT_UNPROTECTED: /sandbox must be root:sandbox 1775 while Hermes shields are up; restore from a trusted backup and recreate the sandbox (shields up cannot run while PID 1 refuses startup)" >&2 + exit 1 + fi +elif [ -e "$HERMES_CONFIG_MUTATION_LOCK" ] \ + || [ -e "$HERMES_RESTART_SEAL_STATE" ] \ + || [ -e "$HERMES_RESTART_ORPHAN_MARKER" ] \ + || hermes_restart_seal_orphaned; then + echo "[SECURITY] HERMES_RESTART_SEAL_ORPHANED: non-root startup cannot safely recover an interrupted root config transaction; restore from a trusted backup and recreate the sandbox" >&2 + exit 1 +fi + # Migrate legacy symlink layout before anything else reads .hermes migrate_legacy_layout "/sandbox/.hermes" "/sandbox/.hermes-data" "hermes" || exit 1 @@ -1274,23 +2705,12 @@ if [ "$(id -u)" -ne 0 ]; then export HOME=/sandbox export HERMES_HOME="${HERMES_DIR}" - # macOS VM startup currently runs this entrypoint as the sandbox user and - # remaps rootfs ownership to the host uid. In that mode the strict /etc hash - # cannot remain a root-owned trust anchor, so use the same locked-aware - # mutable-default verifier as OpenClaw. The root path below keeps strict - # verification against /etc/nemoclaw/hermes.config-hash. - if ! verify_config_integrity_if_locked "${HERMES_DIR}"; then - echo "[SECURITY] Config integrity check failed — refusing to start (non-root mode)" >&2 - exit 1 - fi - ensure_hermes_runtime_api_server_key compat - apply_shields_up_runtime_env - validate_hermes_env_secret_boundary - validate_hermes_runtime_env_secret_boundary - refresh_hermes_provider_placeholders compat - refresh_hermes_runtime_config_hashes compat - configure_messaging_channels - retry_tirith_marker_if_needed + # macOS VM and OpenShell-managed startup run this entrypoint as the sandbox + # user. In that mode the strict /etc hash cannot remain a root-owned trust + # anchor, so use the same locked-aware mutable verifier as OpenClaw. Repeat + # this preparation before every automatic respawn so a stopped gateway never + # relaunches with stale or boundary-unsafe runtime inputs. + prepare_hermes_nonroot_runtime || exit 1 if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then exec "${NEMOCLAW_CMD[@]}" @@ -1306,28 +2726,10 @@ if [ "$(id -u)" -ne 0 ]; then # Start Hermes gateway. Messaging egress goes directly through OpenShell. umask 0007 - HERMES_HOME="${HERMES_DIR}" \ - nohup "$HERMES" gateway run >/tmp/gateway.log 2>&1 & - GATEWAY_PID=$! - echo "[gateway] hermes gateway launched (pid $GATEWAY_PID)" >&2 - start_gateway_log_stream - wait_for_hermes_gateway_internal "$GATEWAY_PID" - start_socat_forwarder "$PUBLIC_PORT" "$INTERNAL_PORT" "API" SOCAT_PID - start_hermes_dashboard_current_user - # NOTE: PIDs are collected after launch; a signal arriving between trap - # registration and the final append is a small race window (same as before - # the shared-library refactor). Acceptable for entrypoint-level cleanup. - SANDBOX_CHILD_PIDS=("$GATEWAY_PID" "$DASHBOARD_PID") - [ -n "${GATEWAY_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") - [ -n "${DASHBOARD_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$DASHBOARD_LOG_TAIL_PID") - # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh - SANDBOX_WAIT_PID="$GATEWAY_PID" - trap cleanup_on_signal SIGTERM SIGINT - [ -n "${SOCAT_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$SOCAT_PID") - [ -n "${DASHBOARD_SOCAT_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$DASHBOARD_SOCAT_PID") + bootstrap_hermes_gateway_current_user || exit 1 print_dashboard_urls - wait "$GATEWAY_PID" + supervise_hermes_gateway_current_user exit $? fi @@ -1336,12 +2738,11 @@ fi export HERMES_HOME="${HERMES_DIR}" verify_hermes_config_integrity ensure_hermes_config_root_mode -ensure_hermes_runtime_api_server_key strict +ensure_hermes_runtime_api_server_key both apply_shields_up_runtime_env validate_hermes_env_secret_boundary validate_hermes_runtime_env_secret_boundary -refresh_hermes_provider_placeholders strict -refresh_hermes_runtime_config_hashes compat +refresh_hermes_provider_placeholders both configure_messaging_channels retry_tirith_marker_if_needed @@ -1349,8 +2750,6 @@ if [ ${#NEMOCLAW_CMD[@]} -gt 0 ]; then exec "${STEP_DOWN_PREFIX_SANDBOX[@]}" "${NEMOCLAW_CMD[@]}" fi -cleanup_stale_hermes_gateway_runtime - # SECURITY: Protect gateway log from sandbox user tampering prepare_restricted_log /tmp/gateway.log gateway:gateway 600 @@ -1359,27 +2758,59 @@ prepare_restricted_log /tmp/gateway.log gateway:gateway 600 validate_tmp_permissions # Start Hermes gateway. Messaging egress goes directly through OpenShell. -HERMES_HOME="${HERMES_DIR}" \ - nohup "${STEP_DOWN_PREFIX_GATEWAY[@]}" sh -c 'umask 0007; exec "$@" >/tmp/gateway.log 2>&1' sh "$HERMES" gateway run & -GATEWAY_PID=$! -echo "[gateway] hermes gateway launched as 'gateway' user (pid $GATEWAY_PID)" >&2 +launch_hermes_gateway start_gateway_log_stream wait_for_hermes_gateway_internal "$GATEWAY_PID" -start_socat_forwarder "$PUBLIC_PORT" "$INTERNAL_PORT" "API" SOCAT_PID -start_hermes_dashboard_sandbox_user +ensure_hermes_supervised_auxiliaries restore_hermes_config_permissions_after_dashboard_start # NOTE: PIDs are collected after launch; a signal arriving between trap # registration and the final append is a small race window (same as before # the shared-library refactor). Acceptable for entrypoint-level cleanup. -SANDBOX_CHILD_PIDS=("$GATEWAY_PID" "$DASHBOARD_PID") -[ -n "${GATEWAY_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") -[ -n "${DASHBOARD_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$DASHBOARD_LOG_TAIL_PID") +refresh_hermes_supervised_child_pids # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" -trap cleanup_on_signal SIGTERM SIGINT -[ -n "${SOCAT_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$SOCAT_PID") -[ -n "${DASHBOARD_SOCAT_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$DASHBOARD_SOCAT_PID") +trap hermes_cleanup_on_signal SIGTERM SIGINT +if ! gateway_control_init; then + echo "[gateway-control] privileged gateway control unavailable" >&2 +fi +if ! "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" publish-startup-ready \ + --hermes-dir "$HERMES_DIR" \ + --startup-owner >/dev/null; then + echo "[gateway-control] failed to publish Hermes startup readiness" >&2 + exit 1 +fi print_dashboard_urls -# Keep container running by waiting on the gateway process. -wait "$GATEWAY_PID" +# PID 1 remains alive even when Hermes stops its gateway. Host recovery uses +# the authenticated control helper to validate and launch a replacement; no +# unrelated exec process owns or races the child lifecycle. +while :; do + while [ -n "${GATEWAY_PID:-}" ] \ + && [ "$GATEWAY_PID" -gt 1 ] \ + && hermes_tracked_role_is_current gateway "$GATEWAY_PID" gateway "$INTERNAL_PORT" \ + && [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 0 ]; do + sleep 1 || true + done + + if [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 1 ]; then + handle_hermes_gateway_control_request || true + continue + fi + + if [ -n "${GATEWAY_PID:-}" ] \ + && [ "$GATEWAY_PID" -gt 0 ] \ + && ! hermes_tracked_role_is_current gateway "$GATEWAY_PID" gateway "$INTERNAL_PORT"; then + reap_status=0 + hermes_reap_exited_gateway || reap_status=$? + case "$reap_status" in + 0) ;; + 3) + handle_hermes_gateway_control_request || true + continue + ;; + *) exit 1 ;; + esac + else + sleep 1 || true + fi +done diff --git a/agents/hermes/validate-env-secret-boundary.py b/agents/hermes/validate-env-secret-boundary.py index 33e5dabb428..e4930eec65c 100755 --- a/agents/hermes/validate-env-secret-boundary.py +++ b/agents/hermes/validate-env-secret-boundary.py @@ -4,11 +4,10 @@ """Validate the Hermes secret boundary on a .env file or the current process environment. This is the single source of truth for the documented Hermes secret-boundary -contract. ``start.sh`` invokes the ``env-file`` and ``runtime-env`` subcommands at -sandbox startup, and the host-side gateway recovery path -(``src/lib/agent/runtime.ts:buildRecoveryScript``) invokes the same script before -relaunching the Hermes gateway so the boundary survives ``sandbox recover`` / -``connect --probe-only``. +contract. ``start.sh`` invokes the ``env-file`` and ``runtime-env`` subcommands +at sandbox startup and again from its root-owned PID 1 lifecycle handler before +relaunching Hermes, so the boundary survives ``recover`` and probe-triggered +recovery. Exits 0 when the input passes the boundary, 1 when raw secret-shaped values are present (emitting ``[SECURITY]`` lines on stderr that match the rest of the @@ -19,10 +18,14 @@ import argparse import errno +import grp import os +import pwd import re import stat import sys +from collections.abc import Iterator +from contextlib import contextmanager from typing import Iterable SECRET_KEY_RE = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|API)(_|$)") @@ -50,6 +53,278 @@ ) RUNTIME_ALLOWED_RAW_SECRET_KEYS = frozenset({"OPENCLAW_GATEWAY_TOKEN"}) ALLOWED_LITERALS = frozenset({"", "[STRIPPED_BY_MIGRATION]"}) +MAX_ENV_BYTES = 4 * 1024 * 1024 +MAX_ENV_LINE_BYTES = 256 * 1024 +MAX_ENV_LINES = 65_536 +MAX_VIOLATIONS = 64 +INSTALLED_BOUNDARY_VALIDATOR = ( + "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py" +) +INSTALLED_ENV_ROOT = "/sandbox" +INSTALLED_ENV_PATH = "/sandbox/.hermes/.env" + + +class UnsafeEnvInputError(RuntimeError): + """An env path or payload cannot be validated without crossing trust bounds.""" + + +def _directory_identity(st: os.stat_result) -> tuple[int, int, int, int, int]: + return ( + st.st_dev, + st.st_ino, + stat.S_IMODE(st.st_mode), + st.st_uid, + st.st_gid, + ) + + +def _file_identity( + st: os.stat_result, +) -> tuple[int, int, int, int, int, int, int, int, int]: + return ( + st.st_dev, + st.st_ino, + stat.S_IMODE(st.st_mode), + st.st_uid, + st.st_gid, + st.st_nlink, + st.st_size, + st.st_mtime_ns, + st.st_ctime_ns, + ) + + +def _allowed_path_owner_uids() -> frozenset[int]: + allowed = {0, os.geteuid()} + try: + allowed.add(pwd.getpwnam("sandbox").pw_uid) + except KeyError: + # Minimal development images may not define the sandbox account. + pass + return frozenset(allowed) + + +def _sandbox_identity() -> tuple[int, int] | None: + try: + return pwd.getpwnam("sandbox").pw_uid, grp.getgrnam("sandbox").gr_gid + except KeyError: + return None + + +def _validate_env_file_metadata(path: str, st: os.stat_result) -> None: + if not stat.S_ISREG(st.st_mode): + raise UnsafeEnvInputError("Hermes env path is not a regular file") + if st.st_nlink != 1: + raise UnsafeEnvInputError("Hermes env path is hardlinked") + mode = stat.S_IMODE(st.st_mode) + if ( + os.path.abspath(__file__) == INSTALLED_BOUNDARY_VALIDATOR + and path == INSTALLED_ENV_PATH + ): + sandbox_identity = _sandbox_identity() + allowed = {(0, 0, 0o400), (0, 0, 0o444)} + if sandbox_identity is not None: + sandbox_uid, sandbox_gid = sandbox_identity + # 0640 is the current mutable top-level contract. Keep 0660 only + # for intentional legacy images whose state-dir unlock predates the + # top-level runtime guard split. + allowed.update( + { + (sandbox_uid, sandbox_gid, 0o640), + (sandbox_uid, sandbox_gid, 0o660), + } + ) + if (st.st_uid, st.st_gid, mode) not in allowed: + raise UnsafeEnvInputError( + "Hermes env path does not match a trusted owner/group/mode posture" + ) + return + + if st.st_uid not in _allowed_path_owner_uids(): + raise UnsafeEnvInputError("Hermes env path has an untrusted owner") + if mode & 0o022: + raise UnsafeEnvInputError("Hermes env path is group/world-writable") + + +def _validate_directory_descriptor(path: str, fd: int) -> tuple[int, int, int, int, int]: + st = os.fstat(fd) + if not stat.S_ISDIR(st.st_mode): + raise UnsafeEnvInputError(f"{path} is not a directory") + if st.st_uid not in _allowed_path_owner_uids(): + raise UnsafeEnvInputError(f"{path} has an untrusted owner") + mode = stat.S_IMODE(st.st_mode) + if os.path.abspath(__file__) == INSTALLED_BOUNDARY_VALIDATOR: + sandbox_identity = _sandbox_identity() + if path == INSTALLED_ENV_ROOT: + allowed = {(0, 0, 0o700), (0, 0, 0o755)} + if sandbox_identity is not None: + sandbox_uid, sandbox_gid = sandbox_identity + allowed.update( + { + (sandbox_uid, sandbox_gid, 0o755), + (sandbox_uid, sandbox_gid, 0o770), + (0, sandbox_gid, 0o1775), + } + ) + if (st.st_uid, st.st_gid, mode) not in allowed: + raise UnsafeEnvInputError( + "/sandbox does not match a trusted owner/group/mode posture" + ) + elif path == os.path.dirname(INSTALLED_ENV_PATH): + allowed = {(0, 0, 0o500), (0, 0, 0o700), (0, 0, 0o755)} + if sandbox_identity is not None: + sandbox_uid, sandbox_gid = sandbox_identity + allowed.update( + { + (sandbox_uid, sandbox_gid, 0o700), + (sandbox_uid, sandbox_gid, 0o3770), + } + ) + if (st.st_uid, st.st_gid, mode) not in allowed: + raise UnsafeEnvInputError( + "/sandbox/.hermes does not match a trusted owner/group/mode posture" + ) + if mode & 0o002 and not mode & stat.S_ISVTX: + raise UnsafeEnvInputError(f"{path} is world-writable without sticky protection") + return _directory_identity(st) + + +@contextmanager +def _open_env_path( + path: str, +) -> Iterator[ + tuple[ + int, + tuple[int, int, int, int, int, int, int, int, int], + list[int], + list[tuple[int, str, int, tuple[int, int, int, int, int]]], + str, + ] +]: + """Yield an env path opened without following any ancestor symlink.""" + + if not os.path.isabs(path): + raise UnsafeEnvInputError("Hermes env path must be absolute") + # macOS checkout tests commonly live below the root-owned /var -> + # /private/var compatibility symlink. Resolve that only for the explicit + # source/dev fallback. The installed root validator never resolves an + # ancestor symlink supplied as part of the sandbox path. + installed_mode = os.path.abspath(__file__) == INSTALLED_BOUNDARY_VALIDATOR + if installed_mode: + if path != INSTALLED_ENV_PATH: + raise UnsafeEnvInputError( + "the installed validator only accepts the canonical Hermes env path" + ) + normalized = path + relative = os.path.relpath(normalized, INSTALLED_ENV_ROOT) + if relative == os.pardir or relative.startswith(f"{os.pardir}{os.sep}"): + raise UnsafeEnvInputError("Hermes env path escapes the sandbox root") + components = [component for component in relative.split(os.sep) if component] + else: + normalized = os.path.join( + os.path.realpath(os.path.dirname(path)), os.path.basename(path) + ) + components = [component for component in normalized.split(os.sep) if component] + if not components: + raise UnsafeEnvInputError("Hermes env path has no file component") + + nofollow = getattr(os, "O_NOFOLLOW", 0) + cloexec = getattr(os, "O_CLOEXEC", 0) + directory_flags = os.O_RDONLY | os.O_DIRECTORY | nofollow | cloexec + file_flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | nofollow | cloexec + directory_fds: list[int] = [] + chain: list[tuple[int, str, int, tuple[int, int, int, int, int]]] = [] + file_fd = -1 + try: + # CodeQL cannot associate the dynamic descriptor stack with the close + # loop below. Register each descriptor immediately, and close it here + # too if list growth itself fails before ownership transfers. + root_path = INSTALLED_ENV_ROOT if installed_mode else os.sep + root_fd = os.open(root_path, directory_flags) # codeql[py/file-not-closed] + try: + directory_fds.append(root_fd) + except BaseException: + os.close(root_fd) + raise + root_identity = _validate_directory_descriptor(root_path, root_fd) + if installed_mode: + # Landlock intentionally prevents the sandbox user from opening + # `/`. Pin and revalidate the directly-opened `/sandbox` anchor; + # its parent is not writable from inside the sandbox, so the entry + # itself cannot be replaced by the caller. + chain.append((root_fd, ".", root_fd, root_identity)) + current_fd = root_fd + display = INSTALLED_ENV_ROOT if installed_mode else "" + for component in components[:-1]: + display = f"{display}/{component}" + child_fd = os.open( # codeql[py/file-not-closed] + component, directory_flags, dir_fd=current_fd + ) + try: + directory_fds.append(child_fd) + except BaseException: + os.close(child_fd) + raise + identity = _validate_directory_descriptor(display, child_fd) + chain.append((current_fd, component, child_fd, identity)) + current_fd = child_fd + + basename = components[-1] + file_fd = os.open(basename, file_flags, dir_fd=current_fd) + file_st = os.fstat(file_fd) + _validate_env_file_metadata(normalized, file_st) + if file_st.st_size > MAX_ENV_BYTES: + raise UnsafeEnvInputError( + f"Hermes env path exceeds the {MAX_ENV_BYTES}-byte limit" + ) + yield file_fd, _file_identity(file_st), directory_fds, chain, basename + finally: + if file_fd != -1: + os.close(file_fd) + for fd in reversed(directory_fds): + os.close(fd) + + +def _read_bounded_env(fd: int, expected_identity: tuple[int, ...]) -> bytes: + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(1024 * 1024, MAX_ENV_BYTES + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > MAX_ENV_BYTES: + raise UnsafeEnvInputError( + f"Hermes env path exceeds the {MAX_ENV_BYTES}-byte limit" + ) + chunks.append(chunk) + if _file_identity(os.fstat(fd)) != expected_identity: + raise UnsafeEnvInputError("Hermes env path changed while it was read") + return b"".join(chunks) + + +def _verify_env_path_chain( + file_fd: int, + expected_file_identity: tuple[int, ...], + final_directory_fd: int, + chain: list[tuple[int, str, int, tuple[int, int, int, int, int]]], + basename: str, +) -> None: + for parent_fd, component, child_fd, expected in chain: + if _directory_identity(os.fstat(child_fd)) != expected: + raise UnsafeEnvInputError("Hermes env ancestor metadata changed") + current = os.stat(component, dir_fd=parent_fd, follow_symlinks=False) + if not stat.S_ISDIR(current.st_mode) or _directory_identity(current) != expected: + raise UnsafeEnvInputError("Hermes env ancestor changed while it was read") + current_file = os.stat( + basename, dir_fd=final_directory_fd, follow_symlinks=False + ) + if ( + not stat.S_ISREG(current_file.st_mode) + or _file_identity(current_file) != expected_file_identity + or _file_identity(os.fstat(file_fd)) != expected_file_identity + ): + raise UnsafeEnvInputError("Hermes env path changed while it was read") def unquote(value: str) -> str: @@ -81,74 +356,107 @@ def is_allowed_raw_secret_value(key: str, value: str) -> bool: return False -def _emit_violations(prefix: str, violations: Iterable[str]) -> None: +def _emit_violations( + prefix: str, violations: Iterable[str], omitted_violations: int = 0 +) -> None: print(prefix, file=sys.stderr) for item in violations: print(f"[SECURITY] {item}", file=sys.stderr) + if omitted_violations > 0: + print( + f"[SECURITY] {omitted_violations} additional violation(s) omitted", + file=sys.stderr, + ) def validate_env_file(path: str) -> int: - # Open the file with O_NOFOLLOW so a symlink swapped in between any earlier - # lstat check and this read cannot redirect validation to an attacker-chosen - # target. fstat then confirms the descriptor still points at a regular file - # before we parse it, closing the static islink + open(path) TOCTOU gap. - flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) try: - fd = os.open(path, flags) - except FileNotFoundError: - return 0 - except OSError as exc: - if exc.errno in (errno.ELOOP, errno.EMLINK): - print( - f"[SECURITY] Refusing Hermes startup because {path} is a symlink", - file=sys.stderr, - ) - return 1 - raise - violations: list[str] = [] - try: - st = os.fstat(fd) - if not stat.S_ISREG(st.st_mode): - print( - f"[SECURITY] Refusing Hermes startup because {path} is not a regular file", - file=sys.stderr, - ) - return 1 - fh = os.fdopen(fd, encoding="utf-8") - fd = -1 - with fh: - for lineno, raw_line in enumerate(fh, 1): - stripped = raw_line.strip() - if not stripped or stripped.startswith("#") or "=" not in stripped: - continue - if stripped.startswith("export "): - stripped = stripped[len("export ") :].lstrip() - key, value = stripped.split("=", 1) - key = key.strip() - if not KEY_NAME_RE.fullmatch(key): - continue - if key in ENV_FILE_ALLOWED_NONSECRET_KEYS: - continue - if key in ENV_FILE_ALLOWED_RAW_SECRET_KEYS and is_allowed_raw_secret_value(key, value): - continue - if not SECRET_KEY_RE.search(key): - continue - if is_allowed_value(unquote(value)): - continue - violations.append(f"{key} (line {lineno})") - finally: - if fd != -1: - # Best-effort cleanup of a leaked descriptor when the body raised - # before os.fdopen took ownership. Surface a warning instead of - # silently swallowing so misuse stays diagnosable; the original - # exception (if any) still propagates because this runs in finally. + with _open_env_path(path) as ( + file_fd, + file_identity, + directory_fds, + chain, + basename, + ): try: - os.close(fd) - except OSError as exc: + raw = _read_bounded_env(file_fd, file_identity) + _verify_env_path_chain( + file_fd, file_identity, directory_fds[-1], chain, basename + ) + except (OSError, UnsafeEnvInputError) as exc: print( - f"[WARN] Failed to close {path}: {exc}", + f"[SECURITY] Refusing Hermes startup because the env path could not be read safely: {exc}", file=sys.stderr, ) + return 1 + except FileNotFoundError: + print( + "[SECURITY] Refusing Hermes startup because the expected env path disappeared", + file=sys.stderr, + ) + return 1 + except OSError as exc: + detail = ( + "a symlink or non-directory ancestor" + if exc.errno in (errno.ELOOP, errno.EMLINK, errno.ENOTDIR) + else "an unreadable path component" + ) + print( + f"[SECURITY] Refusing Hermes startup because the env path contains {detail}", + file=sys.stderr, + ) + return 1 + except UnsafeEnvInputError as exc: + print(f"[SECURITY] Refusing Hermes startup because {exc}", file=sys.stderr) + return 1 + + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + print( + "[SECURITY] Refusing Hermes startup because the env file is not valid UTF-8", + file=sys.stderr, + ) + return 1 + lines = text.splitlines() + if len(lines) > MAX_ENV_LINES: + print( + f"[SECURITY] Refusing Hermes startup because the env file exceeds the {MAX_ENV_LINES}-line limit", + file=sys.stderr, + ) + return 1 + if any(len(line.encode("utf-8")) > MAX_ENV_LINE_BYTES for line in lines): + print( + f"[SECURITY] Refusing Hermes startup because an env line exceeds the {MAX_ENV_LINE_BYTES}-byte limit", + file=sys.stderr, + ) + return 1 + + violations: list[str] = [] + violation_count = 0 + for lineno, raw_line in enumerate(lines, 1): + stripped = raw_line.strip() + if not stripped or stripped.startswith("#") or "=" not in stripped: + continue + if stripped.startswith("export "): + stripped = stripped[len("export ") :].lstrip() + key, value = stripped.split("=", 1) + key = key.strip() + if not KEY_NAME_RE.fullmatch(key): + continue + if key in ENV_FILE_ALLOWED_NONSECRET_KEYS: + continue + if key in ENV_FILE_ALLOWED_RAW_SECRET_KEYS and is_allowed_raw_secret_value( + key, value + ): + continue + if not SECRET_KEY_RE.search(key): + continue + if is_allowed_value(unquote(value)): + continue + violation_count += 1 + if len(violations) < MAX_VIOLATIONS: + violations.append(f"{key} (line {lineno})") if not violations: return 0 _emit_violations( @@ -156,6 +464,7 @@ def validate_env_file(path: str) -> int: "contains raw secret-shaped values. Store credentials in OpenShell " "providers and keep only openshell resolver placeholders in the sandbox.", violations, + violation_count - len(violations), ) return 1 @@ -163,10 +472,13 @@ def validate_env_file(path: str) -> int: def validate_runtime_env(env: dict[str, str] | None = None) -> int: source = os.environ if env is None else env violations: list[str] = [] + violation_count = 0 for key, value in sorted(source.items()): if key in RUNTIME_ALLOWED_NONSECRET_KEYS: continue - if key in RUNTIME_ALLOWED_RAW_SECRET_KEYS and is_allowed_raw_secret_value(key, value): + if key in RUNTIME_ALLOWED_RAW_SECRET_KEYS and is_allowed_raw_secret_value( + key, value + ): continue if not KEY_NAME_RE.fullmatch(key): continue @@ -174,7 +486,9 @@ def validate_runtime_env(env: dict[str, str] | None = None) -> int: continue if is_allowed_value(value): continue - violations.append(key) + violation_count += 1 + if len(violations) < MAX_VIOLATIONS: + violations.append(key) if not violations: return 0 _emit_violations( @@ -182,6 +496,7 @@ def validate_runtime_env(env: dict[str, str] | None = None) -> int: "contains raw secret-shaped values. Store credentials in OpenShell " "providers and keep only openshell resolver placeholders in the sandbox.", violations, + violation_count - len(violations), ) return 1 @@ -201,7 +516,9 @@ def main(argv: list[str]) -> int: args = parser.parse_args(argv) if args.mode == "env-file": return validate_env_file(args.path) - assert args.mode == "runtime-env", f"unreachable: argparse subparsers are required ({args.mode!r})" + assert args.mode == "runtime-env", ( + f"unreachable: argparse subparsers are required ({args.mode!r})" + ) return validate_runtime_env() diff --git a/ci/env-var-doc-allowlist.json b/ci/env-var-doc-allowlist.json index d01772bf503..659117cdd28 100644 --- a/ci/env-var-doc-allowlist.json +++ b/ci/env-var-doc-allowlist.json @@ -58,5 +58,9 @@ { "name": "NEMOCLAW_CLOUD_EXPERIMENTAL_MODEL", "reason": "Legacy E2E-only model override used by cloud and hosted-inference live test scripts. Not a supported production configuration knob." + }, + { + "name": "NEMOCLAW_FORWARD_RECOVERY_WAIT_MS", + "reason": "Internal Vitest-only override that shortens the bounded post-start forward-settle poll in subprocess fixtures. Production uses the built-in three-second window." } ] diff --git a/docs/about/release-notes.mdx b/docs/about/release-notes.mdx index d3e1c6d4e24..b4d7d82cdc8 100644 --- a/docs/about/release-notes.mdx +++ b/docs/about/release-notes.mdx @@ -23,7 +23,7 @@ NemoClaw v0.0.70 hardens OpenShell gateway auth and Hermes recovery behavior: - OpenShell `0.0.71` Docker-driver gateway setup now generates and validates the local mTLS/JWT auth bundle more defensively, keeps the older-glibc compatibility container behind an explicit opt-in, and limits the live gateway auth contract job to explicit workflow dispatches pinned to OpenShell `0.0.71`. For more information, refer to [OpenShell 0.0.71 Gateway Auth Review](../security/openshell-0.0.71-gateway-auth-review) and [Security Best Practices](../security/best-practices). - Hermes recovery now fails closed when an older sandbox image is missing the secret-boundary validator needed to re-check `/sandbox/.hermes/.env`. - The command refuses recovery, stops Hermes gateway/dashboard processes, prints a re-image instruction, and requires rebuilding the sandbox with a current Hermes image before retrying recovery. + The command refuses recovery, leaves an otherwise healthy gateway untouched, prints a re-image instruction, and requires rebuilding the sandbox with a current Hermes image before retrying recovery. For more information, refer to [Troubleshooting](../reference/troubleshooting) and [NemoClaw CLI Commands Reference](../reference/commands). ## v0.0.69 diff --git a/docs/index.yml b/docs/index.yml index 322f81abda3..5419ccd1541 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -137,6 +137,9 @@ navigation: - page: "Credential Storage" path: _build/agent-variants/security/credential-storage.openclaw.generated.mdx slug: credential-storage + - page: "Trusted Computing Base" + path: _build/agent-variants/security/tcb-boundary.openclaw.generated.mdx + slug: trusted-computing-base - page: "OpenShell 0.0.71 Review" path: _build/agent-variants/security/openshell-0.0.71-gateway-auth-review.openclaw.generated.mdx slug: openshell-0.0.71-gateway-auth-review @@ -286,6 +289,9 @@ navigation: - page: "Credential Storage" path: _build/agent-variants/security/credential-storage.hermes.generated.mdx slug: credential-storage + - page: "Trusted Computing Base" + path: _build/agent-variants/security/tcb-boundary.hermes.generated.mdx + slug: trusted-computing-base - page: "OpenShell 0.0.71 Review" path: _build/agent-variants/security/openshell-0.0.71-gateway-auth-review.hermes.generated.mdx slug: openshell-0.0.71-gateway-auth-review diff --git a/docs/manage-sandboxes/backup-restore.mdx b/docs/manage-sandboxes/backup-restore.mdx index 9a87c18cdf2..59b013adf75 100644 --- a/docs/manage-sandboxes/backup-restore.mdx +++ b/docs/manage-sandboxes/backup-restore.mdx @@ -54,6 +54,10 @@ $$nemoclaw my-assistant snapshot restore `snapshot list` prints a table of version, name, timestamp, and path. NemoClaw computes versions (`v1`, `v2`, ..., `vN`) from timestamp order, so `vN` is always the newest snapshot. +`snapshot create` requires shields to be down. +Snapshot creation and restore share the per-sandbox transition lock with the shields auto-restore timer. +If a timed shields-down window expires during snapshot work, auto-restore can interrupt the operation and restore lockdown instead of allowing state or policy changes to continue past the deadline. +Retry the snapshot in a new shields-down window if the deadline interrupts it. To tag a snapshot with a human-readable label, pass `--name`: @@ -77,6 +81,9 @@ $$nemoclaw my-assistant snapshot restore before-upgrade --to my-assistant-clone $$nemoclaw my-assistant snapshot restore before-upgrade --to my-assistant-clone --force --yes ``` +The force-overwrite path restores and verifies lockdown on a destination with an active shields timer, then revokes that timer before it deletes the destination. +It clears the remaining local shields state only after deletion succeeds, before a same-name replacement is created. + The `$$nemoclaw rebuild` command uses the same snapshot mechanism automatically. diff --git a/docs/manage-sandboxes/install-plugins-hermes.mdx b/docs/manage-sandboxes/install-plugins-hermes.mdx index 5ce81332c94..09dbc276a56 100644 --- a/docs/manage-sandboxes/install-plugins-hermes.mdx +++ b/docs/manage-sandboxes/install-plugins-hermes.mdx @@ -31,6 +31,23 @@ Use this path when the plugin adds Python code, runtime hooks, or dependencies t `nemohermes skill install ` is only for `SKILL.md` agent skills. It uploads skill instructions and refreshes skill discovery, but it does not install Hermes runtime plugins. +When you change plugin code or dependencies, update the custom image and rebuild the sandbox so the plugin remains reproducible. +When you change a supported startup-only setting with a NemoClaw host command, restart the Hermes gateway from the host: + +```bash +nemohermes gateway restart +``` + +The restart command sends an authenticated lifecycle request through registry-scoped privileged direct-container control. +In a direct root-entrypoint container, root PID 1 validates `/sandbox/.hermes/.env`, the runtime environment, and the strict root-owned config hash before it relaunches the gateway under the separate `gateway` user with the restart seal. +In an OpenShell-managed container, OpenShell is PID 1 and nonroot `nemoclaw-start`, the gateway, and the agent use the same sandbox UID. +The installed root controller preflights the Hermes secret boundary, verifies the strict hash when the config inputs are root-owned and locked, pidfd-targets the exact observed child, and proves the replacement listener and HTTP health. +Mutable config in that managed topology keeps the same trust and time-of-check/time-of-use limits as managed cold start, and same-UID malicious process provenance cannot be proven. +Use `nemohermes config set` or `nemohermes inference set` for supported configuration changes so NemoClaw updates the managed config metadata together. +The Hermes entrypoint supervisor owns and repairs the gateway, dashboard, internal API relay, dashboard relay, and gateway log stream; the host only checks or recovers the host-side OpenShell forwards after health passes. +`recover` re-evaluates the Hermes secret boundary on every run, including healthy gateways, and repairs stopped supervised processes or host forwards. +Use `gateway restart` when you need a forced runtime reload. + ## Prepare a Build Directory Put the custom Dockerfile and every file it needs to `COPY` in one directory. @@ -47,7 +64,7 @@ my-hermes-plugin-sandbox/ ``` If you start from the stock NemoClaw Hermes Dockerfile, keep the NemoClaw Hermes image contract intact. -The image must still include the generated Hermes config, NemoClaw Hermes plugin, blueprint files, and `nemoclaw-start` entrypoint. +The image must still include the generated Hermes config, NemoClaw Hermes plugin, blueprint files, `nemoclaw-start` entrypoint, root-only gateway control helper, root-only managed controller, and shared supervisor library. A custom `--from` Dockerfile replaces the normal NemoClaw Hermes Dockerfile. @@ -55,6 +72,11 @@ The image must still include the generated Hermes config, NemoClaw Hermes plugin Your Dockerfile must also preserve the NemoClaw Hermes layers from `agents/hermes/Dockerfile`. +If `gateway restart` or `recover` reports `privileged control unavailable` for an older custom image, update the Dockerfile to the current Hermes image contract and rebuild it with `nemohermes rebuild --yes`. +The current contract supports a direct root entrypoint and the OpenShell-managed topology where OpenShell is PID 1 and launches `nemoclaw-start` as nonroot. +An arbitrary nonroot entrypoint that does not match the supported OpenShell-managed process shape cannot use lifecycle control. +Kubernetes and other deployments without a matching direct container fail closed and do not fall back to ordinary `openshell sandbox exec` or an in-sandbox manual relaunch. + ## Install the Plugin in the Image Add your plugin after the Dockerfile has created `/sandbox/.hermes`. diff --git a/docs/manage-sandboxes/lifecycle.mdx b/docs/manage-sandboxes/lifecycle.mdx index 4e463598149..09d0118bf02 100644 --- a/docs/manage-sandboxes/lifecycle.mdx +++ b/docs/manage-sandboxes/lifecycle.mdx @@ -168,10 +168,39 @@ If `$$nemoclaw status` reports the sandbox is alive but the Hermes gatewa $$nemoclaw recover ``` -The command restarts the in-sandbox gateway and re-establishes the dashboard port-forward in one step. +The command repairs a stopped in-sandbox gateway and re-establishes the dashboard port-forward in one step. It is idempotent and safe to script. +If the gateway is already healthy, `recover` exits after the probe and does not restart it. +For built-in OpenClaw and Hermes sandboxes, recovery sends an authenticated request through registry-scoped privileged direct-container control. +The request reaches either the root PID 1 supervisor in a direct root-entrypoint container or the installed root controller in an OpenShell-managed container. +It does not fall back to ordinary `openshell sandbox exec` or a manual relaunch inside the sandbox. Refer to [`$$nemoclaw recover`](../reference/commands#$$nemoclaw-name-recover) for details. +Use `gateway restart` when you intentionally need a supported OpenClaw or Hermes gateway to reload runtime configuration or plugins. + +```bash +$$nemoclaw gateway restart +``` + +The restart command asks the topology-specific controller to stop the tracked gateway child, wait for the entrypoint to launch a replacement, and prove listener and HTTP health. +The host then checks or recovers host-side dashboard, messaging, and agent forwards. +For Hermes, the entrypoint supervisor owns the gateway, dashboard process, internal API relay, dashboard relay, and gateway log stream. +The nonroot managed supervisor repairs those processes continuously, stops an alive but deaf gateway after four consecutive failed health checks, and quarantines relaunch after five exits within 60 seconds until sandbox recreation. +The host does not start the in-sandbox processes independently. +Refer to [`$$nemoclaw gateway restart`](../reference/commands#$$nemoclaw-name-gateway-restart) for details. + +In the direct root-entrypoint topology, the gateway uses a separate `gateway` UID and restart receives the root-only seal. +In the OpenShell-managed topology, OpenShell is PID 1 and nonroot `nemoclaw-start`, the gateway, and the agent use the same sandbox UID. +The installed root controller validates the stable process shape, targets the exact observed child with a pidfd, preflights config, and proves replacement health. +That managed proof prevents PID reuse but cannot establish provenance against a malicious same-UID process, and mutable config retains managed cold-start trust and time-of-check/time-of-use limits. +Arbitrary nonroot entrypoints that do not match the supported OpenShell-managed process shape fail closed with `privileged control unavailable`. +Kubernetes and other deployments without a matching direct container also fail closed with `privileged control unavailable`. +If a direct-container sandbox uses an older image without the matching supervisor or managed controller helper, rebuild it before retrying: + +```bash +$$nemoclaw rebuild --yes +``` + ### Reset a Stored Credential If you entered a provider credential incorrectly during onboarding, clear the gateway-registered value and re-enter it on the next onboard run: @@ -199,6 +228,12 @@ $$nemoclaw rebuild The rebuild command preserves the mounted workspace and registered policies while recreating the container. If NemoClaw cannot archive any requested state path, it reports the backup failure and stops before deleting the original sandbox. +When rebuild starts with shields up, NemoClaw opens a 30-minute shields-down window for backup and recreation. +A detached auto-lock timer remains the recovery authority until NemoClaw commits a successful shields-up state, including when the host rebuild process exits unexpectedly. + +For an older Hermes image that predates sealed shields transitions, only the rebuild workflow may use the descriptor-safe compatibility transition needed to archive and replace the sandbox. +That transition verifies the strict and compatibility hashes and publishes fresh config inodes before changing their lock posture, while ordinary `shields up` and `shields down` commands continue to refuse the older protocol. + Refer to [`$$nemoclaw rebuild`](../reference/commands#$$nemoclaw-name-rebuild) for flag details. ### Add a Network Preset After Onboarding diff --git a/docs/manage-sandboxes/runtime-controls.mdx b/docs/manage-sandboxes/runtime-controls.mdx index 9b21d600116..56ef658cbf9 100644 --- a/docs/manage-sandboxes/runtime-controls.mdx +++ b/docs/manage-sandboxes/runtime-controls.mdx @@ -24,8 +24,8 @@ The following table maps each commonly changed item to the layer that owns it an | Item | When the change takes effect | How to change it | |---|---|---| -| Inference provider (cloud, NVIDIA Endpoints, local Ollama / vLLM, compatible-endpoint, …) | Rebuild required (`openclaw.json` is locked at sandbox creation) | `$$nemoclaw rebuild` after picking a different provider with `$$nemoclaw inference set` | -| Inference model on the current provider | Rebuild required for OpenClaw; hot-reloadable for managed routers | `$$nemoclaw rebuild` (OpenClaw) or `$$nemoclaw inference set` (router-based) | +| Inference provider (cloud, NVIDIA Endpoints, local Ollama / vLLM, compatible-endpoint, …) | Runtime route and config update while shields are down; rebuild only if you need to recreate the image | Run `$$nemoclaw shields down`, then `$$nemoclaw inference set`, then restore shields | +| Inference model on the current provider | Runtime route and config update while shields are down | Run `$$nemoclaw shields down`, then `$$nemoclaw inference set`, then restore shields | | Sub-agent (Hermes / OpenClaw / …) | Re-onboard required (the sub-agent and its workspace are baked at onboard) | `$$nemoclaw onboard --recreate-sandbox` | | Network policy preset (slack, discord, telegram, brave, …) | Runtime. Applies on the next request; rebuild only required if the preset adds bind-mounted secrets | `$$nemoclaw policy-add ` / `policy-remove ` | | Network allow-list (custom hosts) | Runtime. Picks up at next request | `openshell policy set` or interactive approval prompt at the gateway | @@ -33,15 +33,24 @@ The following table maps each commonly changed item to the layer that owns it an | Channel enable/disable (turn a configured channel off without removing the token) | Rebuild required (`openclaw.json` is the source of truth at runtime, refer to #3453) | `$$nemoclaw channels stop ` then rebuild | | Dashboard forward port | Runtime. Port is re-resolved on next `connect` | `NEMOCLAW_DASHBOARD_PORT= $$nemoclaw connect` | | Dashboard bind address (loopback compared to all interfaces) | Runtime. Applies on next `connect` | `NEMOCLAW_DASHBOARD_BIND=0.0.0.0 $$nemoclaw connect` (refer to #3259) | +| Gateway process environment or startup-only plugin state | Runtime after gateway restart | `$$nemoclaw gateway restart` | | Default OpenClaw workspace template seed (`AGENTS.md`, `SOUL.md`, `IDENTITY.md`, `USER.md`, `TOOLS.md`, `HEARTBEAT.md`) | Locked at first sandbox boot. Re-onboard required to change the bake-time choice. | Set `NEMOCLAW_MINIMAL_BOOTSTRAP=1` before `$$nemoclaw onboard` to skip default template seeding for new/pristine workspaces. **Does not delete files already present.** Partial mitigation for #2598 (cuts ~3k tokens of project-context overhead off OpenClaw's per-turn bootstrap injection). | | Web search backend (Brave, Tavily, and so on) | Runtime through `web.backend` config flag; rebuild only if `web.fetchEnabled` flips | `$$nemoclaw config set --key web.backend --value tavily` | | Filesystem layout (Landlock zones, read-only mounts, container caps) | **Locked at creation**. No runtime change | Re-onboard with `$$nemoclaw onboard --recreate-sandbox` | | Sandbox name | **Locked at creation** | Re-onboard with a different `--name` | | GPU passthrough enable / device selector | **Locked at creation** | Re-onboard with `--gpu` / `--sandbox-gpu-device` | | Agents allow-list (`agents.list` in `openclaw.json`) | Runtime. OpenClaw hot-reloads on config change | Prefer agent or NemoClaw commands that keep host and sandbox state aligned | -| `openclaw.json` keys (general: model, agents.list, web.backend, channel config, and so on) | Mixed. Individual keys still follow the rebuild rules in the rows above, such as provider switch requiring rebuild even after editing the JSON. | Prefer NemoClaw host commands so the host registry and rebuilt image stay aligned | - -If a row above conflicts with what you observe, the runtime source of truth inside the sandbox is `/opt/nemoclaw/openclaw.json`; the host registry caches metadata but the image and OpenClaw read from the in-sandbox file. +| `openclaw.json` keys (general: model, agents.list, web.backend, channel config, and so on) | Mixed. Supported config and inference updates run while shields are down; image, policy, and channel changes can still require rebuild. | Use `$$nemoclaw inference set` or `$$nemoclaw config set` so the config and integrity hash change together | + +If a row above conflicts with what you observe, the runtime source of truth inside the sandbox is `/sandbox/.openclaw/openclaw.json`; the host registry caches metadata but the image and OpenClaw read from the in-sandbox file. +OpenClaw config and inference changes are refused while shields are up. +Run `$$nemoclaw shields down` before the change, then restore lockdown with `$$nemoclaw shields up`. +Host-side OpenClaw config writes run under the per-sandbox transition lock and bind the replacement to the SHA-256 digest of the matching read. +The root-only config guard validates bounded JSON input, transactionally publishes fresh config and hash inodes, and restores the prior mutable posture without adopting concurrent path changes. +In the direct root-entrypoint topology, gateway restart performs a read-only config and hash preflight, temporarily seals fresh inodes while the root PID 1 supervisor replaces the gateway child, and then restores the prior shields posture. +In the OpenShell-managed topology, the installed root controller performs the config preflight while the nonroot `nemoclaw-start` supervisor replaces the gateway child. +Mutable config in the managed topology keeps the same trust and time-of-check/time-of-use limits as a managed cold start and does not receive the direct root-entrypoint restart seal. +If preflight detects an unsafe path, invalid config, invalid ownership posture, or locked hash drift, restart refuses while the old healthy gateway is still serving. @@ -55,17 +64,75 @@ If a row above conflicts with what you observe, the runtime source of truth insi | Network allow-list (custom hosts) | Runtime. Picks up at next request | `openshell policy set` or interactive approval prompt at the gateway | | Channel tokens (Slack / Discord / Telegram bot credentials) | Rebuild required (tokens are baked into the sandbox image at onboard so they never leave the host clear-text) | `$$nemoclaw channels add ` then accept the rebuild prompt | | Channel enable/disable (turn a configured channel off without removing the token) | Rebuild required (`/sandbox/.hermes/.env` and Hermes config are baked at image build time) | `$$nemoclaw channels stop ` then rebuild | -| API/dashboard forward port | Runtime. Port is re-resolved on next `connect` | `$$nemoclaw connect` or `openshell forward start` | +| API/dashboard forward port | Runtime. The host-side forward is re-resolved on next `connect`; the Hermes entrypoint supervisor continues to own the internal API and dashboard relays. | `$$nemoclaw connect` or `openshell forward start` | +| Hermes plugin code, Langfuse settings, or other startup-only runtime config | Runtime after a supported host-side update and gateway restart | Bake plugin code into the image or use a supported host config command, then run `$$nemoclaw gateway restart` | | Filesystem layout (Landlock zones, read-only mounts, container caps) | **Locked at creation**. No runtime change | Re-onboard with `$$nemoclaw onboard --recreate-sandbox` | | Sandbox name | **Locked at creation** | Re-onboard with a different `--name` | | GPU passthrough enable / device selector | **Locked at creation** | Re-onboard with `--gpu` / `--sandbox-gpu-device` | -| Hermes `config.yaml` keys | Mixed. Inference keys can be patched by `$$nemoclaw inference set`; image, policy, and channel changes still require rebuild. | Prefer NemoClaw host commands so the host registry and rebuilt image stay aligned | - -If a row above conflicts with what you observe, the runtime source of truth for Hermes is `/sandbox/.hermes/config.yaml` plus `/sandbox/.hermes/.env`. -The host registry caches metadata, but the image and Hermes runtime read from the in-sandbox files. +| Hermes `config.yaml` keys | Mixed. Inference and supported config keys can be patched by host commands; image, policy, and channel changes still require rebuild. | Use `$$nemoclaw inference set` or `$$nemoclaw config set` so the config and root-owned trust anchor change together | + +If a row above conflicts with what you observe, the runtime source of truth for Hermes is `/sandbox/.hermes/config.yaml` plus `/sandbox/.hermes/.env`; the host registry caches metadata but the image and Hermes runtime read from the in-sandbox files. +Do not edit `/sandbox/.hermes/config.yaml`, `/sandbox/.hermes/.env`, or their hash files directly and then expect `gateway restart` to establish those bytes as trusted. +Use supported host config and inference commands for intended changes because they update the managed config metadata together. +In the direct root-entrypoint topology, PID 1 validates the Hermes secret boundary and runtime environment and verifies the strict root-owned hash without recomputing it. +In the OpenShell-managed topology, the installed root controller validates the same secret boundary and verifies the strict hash when both config inputs are root-owned and locked. +Mutable managed config has no durable root-owned hash anchor, so restart has the same trust and time-of-check/time-of-use limits as managed cold start and cannot promise a `config hash mismatch` for direct drift. + +Hermes host-side config writes run as a sealed transaction. +NemoClaw binds the write to the SHA-256 digest of the matching read, temporarily seals the mutable config paths, atomically installs fresh config inodes, refreshes the strict and compatibility hashes, and then restores the prior shields posture. +`shields up` also publishes fresh config, environment, and compatibility-hash inodes so a descriptor opened before lockdown cannot retain write authority. +The same root-only mutation lock stays held through Hermes config writes, the full `shields up` or `shields down` filesystem transition and verification, and lifecycle recovery that needs to seal those paths. +If another host mutation is active, the command reports `Hermes config mutation is already in progress`; if another lifecycle request owns the supervisor, it reports `SUPERVISOR_BUSY`. +Both errors are retryable. +Let the active command finish, then retry instead of editing lock or seal files manually. +Hermes config and inference changes are refused while shields are up; run `$$nemoclaw shields down` before the change, then restore lockdown with `$$nemoclaw shields up`. +## How Timed Shields Windows Interact with Host Commands + +NemoClaw serializes host-side config and inference writes, snapshot mutation, sandbox destruction, and shields transitions for each sandbox. +When `shields down --timeout` is active, each mutation binds to that exact timer generation so a replaced or expired timer cannot race a later command or a new sandbox that reuses the same name. +If the timeout expires while a mutation is still changing sandbox state, auto-restore can stop that exact process tree, reclaim the transition, and restore the restrictive policy and config posture. +The ownership check includes both the process ID and process start identity so PID reuse does not grant control over an unrelated process. +Retry a command that the auto-restore deadline interrupts after you open a new shields-down window. + +## How Gateway Lifecycle Control Works + +Built-in OpenClaw and Hermes images support two direct-container lifecycle topologies. + +| Topology | Process ownership | Lifecycle and trust boundary | +|---|---|---| +| Direct root entrypoint | `nemoclaw-start` is root PID 1, the gateway runs under the separate `gateway` UID, and the agent runs under the `sandbox` UID. | A root-only request channel reaches PID 1. The supervisor tracks the exact child, applies the restart seal, validates locked config, and launches the replacement under the gateway UID. | +| OpenShell-managed | `/opt/openshell/bin/openshell-sandbox` is PID 1. It launches nonroot `nemoclaw-start`, which owns and reaps the gateway. The supervisor, gateway, and agent all use the `sandbox` UID. | A root-owned mode `0500` controller entered through sanitized registry-scoped direct-container control validates a stable OpenShell to `nemoclaw-start` to gateway process shape, publishes a root-owned authorization for one exact exit while that controller identity remains live, signals the observed child through a pidfd, waits for the normal supervisor respawn, and proves the replacement listener and HTTP health. | + +The managed controller authenticates the host lifecycle action and prevents PID reuse from redirecting its signal. +It cannot prove process provenance against a malicious process running under the same sandbox UID, and it does not create gateway and agent UID isolation. +Mutable managed config retains the trust and time-of-check/time-of-use limits of managed cold start. +For Hermes, the managed controller always preflights the secret boundary and verifies the strict root-owned hash when the config and environment are locked. +This compatibility path remains necessary because the OpenShell-managed PID 1 topology owns the nonroot supervisor and shared gateway-agent UID. +Remove it only after the minimum supported OpenShell provides a root-owned lifecycle supervisor or a gateway UID distinct from the agent, then migrate both built-in agents to that boundary. + +For built-in OpenClaw and Hermes controllers, a successful `recover` or `gateway restart` response supplies the initial authenticated gateway-health proof. +After the settle window, NemoClaw sends one read-only authenticated `probe` through the same controller before it declares success. +The controller rechecks the exact managed child, listener, HTTP health, and required auxiliary processes from inside the gateway network namespace without restarting the gateway. +A failed managed probe is authoritative and cannot be overridden by an outer-namespace HTTP response. +Custom agents that recover through an SSH script do not use this controller probe and continue to poll ordinary gateway health. + +The nonroot Hermes supervisor continuously repairs the gateway, API relay, dashboard, dashboard relay, and gateway log stream. +Four consecutive gateway health failures trigger exact-child recovery. +Five unexpected gateway exits or failed replacement candidates within 60 seconds quarantine relaunch until the sandbox is recreated. +An authenticated host action authorizes one exit bound to the exact gateway process ID and kernel start identity while the exact root controller process remains live, so deliberate `gateway restart` and controller-driven replacement do not consume that crash budget. +The authorization records host intent for that exact exit; it does not claim that the host signal was the only possible cause of process termination in the shared-UID topology. +After the in-sandbox processes are healthy, the host repairs only the host-side OpenShell forwards. + +The host selects the matching controller automatically for `recover` and `gateway restart`. +Ordinary `openshell sandbox exec` and manual in-sandbox relaunch are not fallback paths. +A current built-in image supports both the direct root-entrypoint and OpenShell-managed topologies. +An arbitrary nonroot entrypoint that does not match the managed OpenShell process shape fails closed with `privileged control unavailable`. +Kubernetes and other deployments without a matching direct container also fail closed with `privileged control unavailable`. +Older images without the matching supervisor or managed controller helper must be updated with `$$nemoclaw rebuild --yes`. + ## Related Topics The table above consolidates details from these topic pages: diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 02ffb189874..7051d8c4984 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -527,23 +527,82 @@ nemohermes my-assistant shields down --timeout 5m --reason "maintenance" | `shields up` | Lock the sandbox config and restore the saved restrictive policy | | `shields down` | Temporarily unlock the sandbox config. Supports `--timeout`, `--reason`, and `--policy` | +Host-side config and inference writes, snapshot mutation, sandbox destruction, and shields transitions serialize per sandbox. +When a timed shields-down window reaches its deadline, auto-restore can interrupt the exact process tree holding that transition and restore lockdown. +Retry an interrupted command in a new shields-down window. + ### `nemohermes recover` -Restart the in-sandbox gateway and re-establish the host-side dashboard port-forward without opening an SSH session. -Use this after a sandbox pod restart, a sandbox crash, or whenever `nemohermes status` reports the gateway is not running but the sandbox is alive. +Repair a stopped in-sandbox gateway and re-establish host-side forwards without opening an SSH session. +Use this after a direct sandbox container restart, a sandbox crash, or whenever `nemohermes status` reports the gateway is not running but the sandbox is alive. -`recover` runs the same recovery the `connect` command performs as a side effect, but without dropping into a shell, so it is safe to call from scripts and automation. +For built-in OpenClaw and Hermes sandboxes, `recover` sends an authenticated lifecycle request through registry-scoped privileged direct-container control. +The host selects the controller from the live container topology. +In a direct root-entrypoint container, the request reaches the root PID 1 supervisor. +In an OpenShell-managed container, the request enters the root-owned mode `0500` managed controller through a sanitized root exec while OpenShell remains PID 1. +It does not use ordinary `openshell sandbox exec` or an in-sandbox manual relaunch as a fallback. It is idempotent. -If the gateway is already running, the command exits zero with a probe message and makes no changes. +When `recover` repairs a stopped built-in OpenClaw or Hermes gateway, it retries only when stdout is empty and stderr is exactly one `SUPERVISOR_BUSY` or `SUPERVISOR_UNAVAILABLE` line, with at most three controller attempts. +Other controller failures stop immediately. +If the gateway is already running, the command exits zero without force-restarting it; it can still re-evaluate supported safety checks and check or recover host-side forwards. +Use [`nemohermes gateway restart`](#nemohermes-name-gateway-restart) when you deliberately need a running gateway to reload runtime configuration or plugins. ```bash nemohermes my-assistant recover ``` -`recover` re-evaluates the documented Hermes secret boundary against `/sandbox/.hermes/.env` on every run, including when the gateway is already healthy. -If the file contains raw secret-shaped values (for example a pasted Telegram, Discord, or Slack bot token in place of the expected `openshell:resolve:env:` placeholder), the command stops the running gateway, exits non-zero, and prints the offending key. +`recover` re-evaluates the documented Hermes secret boundary against `/sandbox/.hermes/.env` and the supervisor runtime environment on every run, including when the gateway is already healthy. +If the file contains raw secret-shaped values (for example a pasted Telegram, Discord, or Slack bot token in place of the expected `openshell:resolve:env:` placeholder), the command exits non-zero and prints the offending key. +The direct root-entrypoint supervisor stops a running gateway after this refusal, while the managed controller refuses before signaling the observed child. Replace each flagged value with the `openshell:resolve:env:` placeholder and re-run. -Older Hermes sandbox images that predate the standalone validator are detected and fail closed: `recover` refuses the gateway recovery, names the sandbox, and explains that `/sandbox/.hermes/.env` could not be re-evaluated. Re-image the sandbox to a current Hermes build before retrying recovery. +The direct root-entrypoint supervisor verifies the strict root-owned config hash. +The managed controller verifies that strict hash when both Hermes config inputs are root-owned and locked. +Mutable config under the managed topology has no durable root-owned hash anchor and retains the same trust and time-of-check/time-of-use limits as managed cold start. +If the boundary validator or supervisor helper is missing, recovery fails closed, names the sandbox, explains that `/sandbox/.hermes/.env` could not be re-evaluated, and leaves an otherwise healthy gateway untouched. +Rebuild an older sandbox image with `nemohermes rebuild --yes` before retrying. + +The privileged control path requires a running direct sandbox container that belongs to the named registry entry. +Supported built-in images use either a direct root entrypoint or the OpenShell-managed process shape with OpenShell as PID 1 and exactly one nonroot `nemoclaw-start` supervisor. +An arbitrary nonroot entrypoint that does not match the supported OpenShell-managed process shape fails with the `privileged control unavailable` failure layer. +Kubernetes and other deployments without a matching direct container also fail with that layer. + +### `nemohermes gateway restart` + +Force-restart the supported in-sandbox gateway process through the controller for the live container topology. +Use this after runtime configuration or plugin changes that the agent reads only at gateway startup, such as Hermes Langfuse plugin settings. +Unlike `recover`, this command restarts a healthy gateway instead of exiting after the health probe. + +```bash +nemohermes my-assistant gateway restart [--quiet|-q] +``` + +On success, the command reports that the gateway was restarted, health passed, and forwards were checked or recovered. +It also checks the dashboard forward, messaging forward, and manifest-declared agent forwards. +`--quiet` suppresses progress lines but still prints refusal diagnostics. +In the direct root-entrypoint topology, PID 1 stops only the gateway child whose process ID and process start identity match the tracked child, applies the restart seal, and launches the replacement under the separate `gateway` UID. +In the OpenShell-managed topology, the installed root controller verifies a stable OpenShell to `nemoclaw-start` to gateway process shape, holds a root-only lifecycle lock, publishes one root-owned exit authorization bound to the exact gateway process ID, kernel start identity, and live controller identity, pidfd-targets the observed child, waits for the nonroot entrypoint supervisor to respawn it under the sandbox UID, and proves the replacement listener and HTTP health. +That managed process proof prevents PID reuse from redirecting the signal but cannot establish provenance against a malicious same-UID process or create gateway and agent UID isolation. +For Hermes, the entrypoint supervisor also owns the dashboard process, internal API relay, dashboard relay, and gateway log stream. +The managed nonroot supervisor continuously repairs those processes, stops an alive but deaf gateway after four consecutive failed health checks, and quarantines relaunch after five unexpected exits or failed replacement candidates within 60 seconds until sandbox recreation. +That authorization keeps an authenticated host-requested exit out of the crash budget while its exact root controller remains live; it records host intent for the exit but does not claim that the host signal was the only possible cause in the shared-UID topology. +The host repairs only the host-side OpenShell forwards after the supervisor reports a healthy gateway. + +For Hermes, both controllers validate `/sandbox/.hermes/.env` against the secret-boundary guard and validate the supervisor runtime environment before restart. +The direct root-entrypoint supervisor verifies `/sandbox/.hermes/config.yaml` and `.env` against the root-owned strict hash and relaunches the process as the `gateway` user. +The managed controller verifies the strict hash when both config inputs are root-owned and locked, but mutable managed config retains cold-start-equivalent trust and time-of-check/time-of-use limits. +Neither controller recomputes a trusted strict hash to adopt direct in-sandbox edits. +Use supported host commands such as `nemohermes config set` and `nemohermes inference set` for intended runtime configuration changes because those commands update the managed config metadata together. +When a strict hash is available and does not match, the command reports the `config hash mismatch` failure layer. +Hermes host config writes, shields transitions, and lifecycle seals share one root-only mutation lock. +Config writes are bound to the digest of the matching read and atomically refresh the strict and compatibility hashes before the prior ownership and mode posture is restored. +The shields transition keeps that lock through recursive filesystem updates, verification, and content-seal capture, and replaces sensitive inodes before lockdown. +If a concurrent lifecycle request reports `SUPERVISOR_BUSY`, or a config or shields command reports `Hermes config mutation is already in progress`, wait for the active operation to finish and retry. +Run `nemohermes shields down` before a Hermes config or inference change; these commands refuse to mutate a shields-up sandbox. + +The command can fail at these layers: unsupported agent, privileged control unavailable, secret-boundary refusal, unsafe config path, config hash mismatch when a strict hash is available, launch failure, health timeout, or forward recovery failure. +An older direct-container image without the matching supervisor or managed controller helper reports `privileged control unavailable` and requires `nemohermes rebuild --yes`. +Ordinary OpenShell exec and manual in-sandbox relaunch are not fallback paths. +Terminal agents do not have a gateway runtime and fail as unsupported. ### `nemohermes status` @@ -717,6 +776,11 @@ If you want to upgrade the sandbox while preserving state, use `nemohermes gateway restart` if prompted so the removal takes effect. ```bash nemohermes my-assistant skill remove my-skill @@ -1233,8 +1297,13 @@ Pass `--yes`, `-y`, or `--force` to skip the prompt in scripted workflows. The sandbox must be running for the backup step to succeed. If an archive command reports partial output while still producing usable data, `rebuild` keeps the captured backup entries and reports only the manifest-defined paths that could not be archived. If any required state path still cannot be backed up, `rebuild` exits before destroying the original sandbox. +When rebuild starts with shields up, NemoClaw opens a 30-minute shields-down window for backup and recreation. +A detached auto-lock timer remains active until NemoClaw commits a successful shields-up state, so it can attempt to restore lockdown if the host rebuild process exits unexpectedly. After restore, the command restores Hermes manifest-defined state and starts the rebuilt Hermes gateway with the regenerated `/sandbox/.hermes` config. +For an older Hermes image that predates sealed shields transitions, rebuild is the only workflow authorized to use the descriptor-safe compatibility transition. +The compatibility path verifies the strict root-owned hash and the in-tree hash, publishes fresh config inodes to revoke retained write descriptors, and restores the trusted lock posture if the transition cannot finish. +Ordinary `shields up` and `shields down` commands refuse the older protocol and direct you to rebuild. ### `nemohermes update` @@ -1297,6 +1366,8 @@ The installer calls `backup-all` automatically before onboarding to protect agai Create a timestamped snapshot of sandbox state. Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. +The command requires shields to be down and keeps the shields check and backup under one per-sandbox transition. +An expired auto-restore timer can interrupt a long-running backup and restore lockdown. ```bash nemohermes my-assistant snapshot create @@ -1327,6 +1398,8 @@ Restore sandbox state from a snapshot. The sandbox must be running before you restore. If no selector is provided, the latest snapshot is used. Restore performs a clean replacement of each state directory, removing files that were added after the snapshot was taken. +The state replacement, mutable-config permission repair, and policy reconciliation run under the same per-sandbox transition. +An expired auto-restore timer can interrupt that work and restore lockdown. The selector accepts any of: @@ -1339,6 +1412,8 @@ When `dst` does not exist, it is auto-created by reusing the source sandbox's co No re-onboarding is needed. When `dst` already exists, `snapshot restore --to ` refuses by default to avoid silently mutating the destination's filesystem. To overwrite an existing destination, pass `--force`: the command deletes `dst`, then recreates it from the source's image and restores the snapshot into the fresh copy. +If the existing destination has an active shields timer, the force path restores and verifies lockdown, revokes the timer, and then deletes the destination. +It clears the remaining local shields state only after deletion succeeds. The `--force` path prompts interactively to confirm the destination name before deleting. Pass `--yes` (or set `NEMOCLAW_NON_INTERACTIVE=1`) to skip the prompt. The snapshot selector and source pod image are both validated before any deletion, so a bad selector or unresolvable image cannot destroy `dst` and only fail afterwards. @@ -1544,6 +1619,8 @@ Keeping the placeholder preserves dashboard and API authentication after provide Under the `nemohermes` alias, it uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. By default, the command syncs the default registered sandbox. +The command refuses before changing the OpenShell route when the selected sandbox has shields up. +Run `nemohermes shields down`, apply the inference change, then run `nemohermes shields up` again. ```bash nemohermes inference set --provider --model [--sandbox ] [--no-verify] [--endpoint-url ] [--credential-env ] [--inference-api ] @@ -1557,7 +1634,11 @@ If the in-sandbox config sync fails, NemoClaw keeps the gateway and registry ali Supported provider names are `nvidia-prod`, `nvidia-nim`, `nvidia-router`, `openai-api`, `anthropic-prod`, `compatible-anthropic-endpoint`, `gemini-api`, `compatible-endpoint`, `hermes-provider`, `ollama-local`, and `vllm-local`. Use `--no-verify` only when OpenShell cannot verify the provider at switch time but you have already confirmed the provider and credential. -When switching to `compatible-endpoint` or `compatible-anthropic-endpoint` from a different provider family, pass `--endpoint-url` with the trusted custom provider URL so NemoClaw can persist durable rebuild metadata. `--credential-env` and `--inference-api` may also be supplied for the compatible provider metadata; supported API values are `openai-completions`, `anthropic-messages`, and `openai-responses`. +When switching to `compatible-endpoint` or `compatible-anthropic-endpoint` from a different provider family, pass `--endpoint-url` with the trusted custom provider URL so NemoClaw can persist durable rebuild metadata. +NemoClaw rejects loopback, link-local, private, and internal endpoint addresses, including public hostnames that resolve to a private address. +For public HTTP URLs, NemoClaw stores the validated IP address to prevent DNS rebinding; HTTPS URLs keep their hostname after DNS validation. +NemoClaw accepts `http://host.openshell.internal:` only with an explicit port from `1024` through `65535`; this narrow exception supports NemoClaw's sandbox-to-host inference routes and is not a general private-endpoint bypass. +`--credential-env` and `--inference-api` may also be supplied for the compatible provider metadata; supported API values are `openai-completions`, `anthropic-messages`, and `openai-responses`. ### `nemohermes setup` diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0e3de509f0f..9a38401c8e2 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -680,14 +680,25 @@ $$nemoclaw my-assistant shields down --timeout 5m --reason "maintenance" | `shields up` | Lock the sandbox config and restore the saved restrictive policy | | `shields down` | Temporarily unlock the sandbox config. Supports `--timeout`, `--reason`, and `--policy` | +Host-side config and inference writes, snapshot mutation, sandbox destruction, and shields transitions serialize per sandbox. +When a timed shields-down window reaches its deadline, auto-restore can interrupt the exact process tree holding that transition and restore lockdown. +Retry an interrupted command in a new shields-down window. + ### `$$nemoclaw recover` -Restart the in-sandbox gateway and re-establish the host-side dashboard port-forward without opening an SSH session. -Use this after a sandbox pod restart, a sandbox crash, or whenever `$$nemoclaw status` reports the gateway is not running but the sandbox is alive. +Repair a stopped in-sandbox gateway and re-establish host-side forwards without opening an SSH session. +Use this after a direct sandbox container restart, a sandbox crash, or whenever `$$nemoclaw status` reports the gateway is not running but the sandbox is alive. -`recover` runs the same recovery the `connect` command performs as a side effect, but without dropping into a shell, so it is safe to call from scripts and automation. +For built-in OpenClaw and Hermes sandboxes, `recover` sends an authenticated lifecycle request through registry-scoped privileged direct-container control. +The host selects the controller from the live container topology. +In a direct root-entrypoint container, the request reaches the root PID 1 supervisor. +In an OpenShell-managed container, the request enters the root-owned mode `0500` managed controller through a sanitized root exec while OpenShell remains PID 1. +It does not use ordinary `openshell sandbox exec` or an in-sandbox manual relaunch as a fallback. It is idempotent. -If the gateway is already running, the command exits zero with a probe message and makes no changes. +When `recover` repairs a stopped built-in OpenClaw or Hermes gateway, it retries only when stdout is empty and stderr is exactly one `SUPERVISOR_BUSY` or `SUPERVISOR_UNAVAILABLE` line, with at most three controller attempts. +Other controller failures stop immediately. +If the gateway is already running, the command exits zero without force-restarting it; it can still re-evaluate supported safety checks and check or recover host-side forwards. +Use [`$$nemoclaw gateway restart`](#$$nemoclaw-name-gateway-restart) when you deliberately need a running gateway to reload runtime configuration or plugins. ```bash $$nemoclaw my-assistant recover @@ -695,13 +706,65 @@ $$nemoclaw my-assistant recover -`recover` re-evaluates the documented Hermes secret boundary against `/sandbox/.hermes/.env` on every run, including when the gateway is already healthy. -If the file contains raw secret-shaped values (for example a pasted Telegram, Discord, or Slack bot token in place of the expected `openshell:resolve:env:` placeholder), the command stops the running gateway, exits non-zero, and prints the offending key. +`recover` re-evaluates the documented Hermes secret boundary against `/sandbox/.hermes/.env` and the supervisor runtime environment on every run, including when the gateway is already healthy. +If the file contains raw secret-shaped values (for example a pasted Telegram, Discord, or Slack bot token in place of the expected `openshell:resolve:env:` placeholder), the command exits non-zero and prints the offending key. +The direct root-entrypoint supervisor stops a running gateway after this refusal, while the managed controller refuses before signaling the observed child. Replace each flagged value with the `openshell:resolve:env:` placeholder and re-run. -Older Hermes sandbox images that predate the standalone validator are detected and fail closed: `recover` refuses the gateway recovery, names the sandbox, and explains that `/sandbox/.hermes/.env` could not be re-evaluated. Re-image the sandbox to a current Hermes build before retrying recovery. +The direct root-entrypoint supervisor verifies the strict root-owned config hash. +The managed controller verifies that strict hash when both Hermes config inputs are root-owned and locked. +Mutable config under the managed topology has no durable root-owned hash anchor and retains the same trust and time-of-check/time-of-use limits as managed cold start. +If the boundary validator or supervisor helper is missing, recovery fails closed, names the sandbox, explains that `/sandbox/.hermes/.env` could not be re-evaluated, and leaves an otherwise healthy gateway untouched. +Rebuild an older sandbox image with `$$nemoclaw rebuild --yes` before retrying. + + + +The privileged control path requires a running direct sandbox container that belongs to the named registry entry. +Supported built-in images use either a direct root entrypoint or the OpenShell-managed process shape with OpenShell as PID 1 and exactly one nonroot `nemoclaw-start` supervisor. +An arbitrary nonroot entrypoint that does not match the supported OpenShell-managed process shape fails with the `privileged control unavailable` failure layer. +Kubernetes and other deployments without a matching direct container also fail with that layer. + +### `$$nemoclaw gateway restart` + +Force-restart the supported in-sandbox gateway process through the controller for the live container topology. +Use this after runtime configuration or plugin changes that the agent reads only at gateway startup, such as Hermes Langfuse plugin settings. +Unlike `recover`, this command restarts a healthy gateway instead of exiting after the health probe. + +```bash +$$nemoclaw my-assistant gateway restart [--quiet|-q] +``` + +On success, the command reports that the gateway was restarted, health passed, and forwards were checked or recovered. +It also checks the dashboard forward, messaging forward, and manifest-declared agent forwards. +`--quiet` suppresses progress lines but still prints refusal diagnostics. +In the direct root-entrypoint topology, PID 1 stops only the gateway child whose process ID and process start identity match the tracked child, applies the restart seal, and launches the replacement under the separate `gateway` UID. +In the OpenShell-managed topology, the installed root controller verifies a stable OpenShell to `nemoclaw-start` to gateway process shape, holds a root-only lifecycle lock, publishes one root-owned exit authorization bound to the exact gateway process ID, kernel start identity, and live controller identity, pidfd-targets the observed child, waits for the nonroot entrypoint supervisor to respawn it under the sandbox UID, and proves the replacement listener and HTTP health. +That managed process proof prevents PID reuse from redirecting the signal but cannot establish provenance against a malicious same-UID process or create gateway and agent UID isolation. +For Hermes, the entrypoint supervisor also owns the dashboard process, internal API relay, dashboard relay, and gateway log stream. +The managed nonroot supervisor continuously repairs those processes, stops an alive but deaf gateway after four consecutive failed health checks, and quarantines relaunch after five unexpected exits or failed replacement candidates within 60 seconds until sandbox recreation. +That authorization keeps an authenticated host-requested exit out of the crash budget while its exact root controller remains live; it records host intent for the exit but does not claim that the host signal was the only possible cause in the shared-UID topology. +The host repairs only the host-side OpenShell forwards after the supervisor reports a healthy gateway. + + + +For Hermes, both controllers validate `/sandbox/.hermes/.env` against the secret-boundary guard and validate the supervisor runtime environment before restart. +The direct root-entrypoint supervisor verifies `/sandbox/.hermes/config.yaml` and `.env` against the root-owned strict hash and relaunches the process as the `gateway` user. +The managed controller verifies the strict hash when both config inputs are root-owned and locked, but mutable managed config retains cold-start-equivalent trust and time-of-check/time-of-use limits. +Neither controller recomputes a trusted strict hash to adopt direct in-sandbox edits. +Use supported host commands such as `$$nemoclaw config set` and `$$nemoclaw inference set` for intended runtime configuration changes because those commands update the managed config metadata together. +When a strict hash is available and does not match, the command reports the `config hash mismatch` failure layer. +Hermes host config writes, shields transitions, and lifecycle seals share one root-only mutation lock. +Config writes are bound to the digest of the matching read and atomically refresh the strict and compatibility hashes before the prior ownership and mode posture is restored. +The shields transition keeps that lock through recursive filesystem updates, verification, and content-seal capture, and replaces sensitive inodes before lockdown. +If a concurrent lifecycle request reports `SUPERVISOR_BUSY`, or a config or shields command reports `Hermes config mutation is already in progress`, wait for the active operation to finish and retry. +Run `$$nemoclaw shields down` before a Hermes config or inference change; these commands refuse to mutate a shields-up sandbox. +The command can fail at these layers: unsupported agent, privileged control unavailable, secret-boundary refusal, unsafe config path, config hash mismatch when a strict hash is available, launch failure, health timeout, or forward recovery failure. +An older direct-container image without the matching supervisor or managed controller helper reports `privileged control unavailable` and requires `$$nemoclaw rebuild --yes`. +Ordinary OpenShell exec and manual in-sandbox relaunch are not fallback paths. +Terminal agents do not have a gateway runtime and fail as unsupported. + ### `$$nemoclaw status` Show sandbox status, health, and inference configuration. @@ -992,6 +1055,11 @@ If you want to upgrade the sandbox while preserving state, use `$$nemoclaw -For Hermes, restart the Hermes gateway if prompted so the removal takes effect. +Run `$$nemoclaw gateway restart` if prompted so the removal takes effect. @@ -1564,6 +1632,8 @@ Pass `--yes`, `-y`, or `--force` to skip the prompt in scripted workflows. The sandbox must be running for the backup step to succeed. If an archive command reports partial output while still producing usable data, `rebuild` keeps the captured backup entries and reports only the manifest-defined paths that could not be archived. If any required state path still cannot be backed up, `rebuild` exits before destroying the original sandbox. +When rebuild starts with shields up, NemoClaw opens a 30-minute shields-down window for backup and recreation. +A detached auto-lock timer remains active until NemoClaw commits a successful shields-up state, so it can attempt to restore lockdown if the host rebuild process exits unexpectedly. @@ -1573,6 +1643,9 @@ After restore, the command runs `openclaw doctor --fix` for cross-version struct After restore, the command restores Hermes manifest-defined state and starts the rebuilt Hermes gateway with the regenerated `/sandbox/.hermes` config. +For an older Hermes image that predates sealed shields transitions, rebuild is the only workflow authorized to use the descriptor-safe compatibility transition. +The compatibility path verifies the strict root-owned hash and the in-tree hash, publishes fresh config inodes to revoke retained write descriptors, and restores the trusted lock posture if the transition cannot finish. +Ordinary `shields up` and `shields down` commands refuse the older protocol and direct you to rebuild. @@ -1637,6 +1710,8 @@ The installer calls `backup-all` automatically before onboarding to protect agai Create a timestamped snapshot of sandbox state. Snapshots are stored in `~/.nemoclaw/rebuild-backups//`. +The command requires shields to be down and keeps the shields check and backup under one per-sandbox transition. +An expired auto-restore timer can interrupt a long-running backup and restore lockdown. ```bash $$nemoclaw my-assistant snapshot create @@ -1667,6 +1742,8 @@ Restore sandbox state from a snapshot. The sandbox must be running before you restore. If no selector is provided, the latest snapshot is used. Restore performs a clean replacement of each state directory, removing files that were added after the snapshot was taken. +The state replacement, mutable-config permission repair, and policy reconciliation run under the same per-sandbox transition. +An expired auto-restore timer can interrupt that work and restore lockdown. The selector accepts any of: @@ -1679,6 +1756,8 @@ When `dst` does not exist, it is auto-created by reusing the source sandbox's co No re-onboarding is needed. When `dst` already exists, `snapshot restore --to ` refuses by default to avoid silently mutating the destination's filesystem. To overwrite an existing destination, pass `--force`: the command deletes `dst`, then recreates it from the source's image and restores the snapshot into the fresh copy. +If the existing destination has an active shields timer, the force path restores and verifies lockdown, revokes the timer, and then deletes the destination. +It clears the remaining local shields state only after deletion succeeds. The `--force` path prompts interactively to confirm the destination name before deleting. Pass `--yes` (or set `NEMOCLAW_NON_INTERACTIVE=1`) to skip the prompt. The snapshot selector and source pod image are both validated before any deletion, so a bad selector or unresolvable image cannot destroy `dst` and only fail afterwards. @@ -1902,6 +1981,8 @@ Under the `nemohermes` alias, it uses the registered Hermes sandbox when exactly By default, the command syncs the default registered sandbox. +The command refuses before changing the OpenShell route when the selected sandbox has shields up. +Run `$$nemoclaw shields down`, apply the inference change, then run `$$nemoclaw shields up` again. ```bash $$nemoclaw inference set --provider --model [--sandbox ] [--no-verify] [--endpoint-url ] [--credential-env ] [--inference-api ] @@ -1915,7 +1996,11 @@ If the in-sandbox config sync fails, NemoClaw keeps the gateway and registry ali Supported provider names are `nvidia-prod`, `nvidia-nim`, `nvidia-router`, `openai-api`, `anthropic-prod`, `compatible-anthropic-endpoint`, `gemini-api`, `compatible-endpoint`, `hermes-provider`, `ollama-local`, and `vllm-local`. Use `--no-verify` only when OpenShell cannot verify the provider at switch time but you have already confirmed the provider and credential. -When switching to `compatible-endpoint` or `compatible-anthropic-endpoint` from a different provider family, pass `--endpoint-url` with the trusted custom provider URL so NemoClaw can persist durable rebuild metadata. `--credential-env` and `--inference-api` may also be supplied for the compatible provider metadata; supported API values are `openai-completions`, `anthropic-messages`, and `openai-responses`. +When switching to `compatible-endpoint` or `compatible-anthropic-endpoint` from a different provider family, pass `--endpoint-url` with the trusted custom provider URL so NemoClaw can persist durable rebuild metadata. +NemoClaw rejects loopback, link-local, private, and internal endpoint addresses, including public hostnames that resolve to a private address. +For public HTTP URLs, NemoClaw stores the validated IP address to prevent DNS rebinding; HTTPS URLs keep their hostname after DNS validation. +NemoClaw accepts `http://host.openshell.internal:` only with an explicit port from `1024` through `65535`; this narrow exception supports NemoClaw's sandbox-to-host inference routes and is not a general private-endpoint bypass. +`--credential-env` and `--inference-api` may also be supplied for the compatible provider metadata; supported API values are `openai-completions`, `anthropic-messages`, and `openai-responses`. ### `$$nemoclaw setup` diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 02f69df05fa..80052ce3a51 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -404,7 +404,7 @@ Run `$$nemoclaw status` for a broader gateway health report. If `nemohermes recover` reports that the Hermes secret-boundary validator is missing, the sandbox image predates the recovery-side validator that re-checks `/sandbox/.hermes/.env`. -Current NemoClaw releases fail closed in this state: recovery reports that the validator is missing, stops Hermes gateway/dashboard processes, refuses to claim the secret boundary was checked, and instructs you to re-image the sandbox with a current Hermes build. +Current NemoClaw releases fail closed in this state: recovery reports that the validator is missing, leaves an otherwise healthy gateway untouched, refuses to claim the secret boundary was checked, and instructs you to re-image the sandbox with a current Hermes build. Re-image the sandbox with a current Hermes build before retrying recovery: @@ -431,7 +431,7 @@ For example, `openclaw plugins install` logs that message until the gateway rest Apply them with a supervised restart: ```bash -$$nemoclaw recover +$$nemoclaw gateway restart ``` or rebuild the sandbox for changes that affect provisioning: @@ -644,6 +644,98 @@ If the sandbox was intentionally deleted and you want a clean setup instead, run Create a snapshot first when the sandbox is reachable enough to back up state. For details, refer to [Back Up and Restore](../manage-sandboxes/backup-restore). +### `gateway restart` or `recover` reports `privileged control unavailable` + +Built-in OpenClaw and Hermes lifecycle commands require a running direct sandbox container that belongs to the named NemoClaw registry entry. +The host uses registry-scoped privileged direct-container control to send an authenticated request to the controller for the live topology. +It does not fall back to ordinary `openshell sandbox exec`, SSH, or a manual in-sandbox relaunch. + +Current built-in images support two direct-container shapes. +A direct root-entrypoint container uses the root PID 1 supervisor. +An OpenShell-managed container uses `/opt/openshell/bin/openshell-sandbox` as PID 1, exactly one nonroot `nemoclaw-start` supervisor, and the installed root-owned mode `0500` managed controller. +An arbitrary nonroot entrypoint that does not match that managed process shape fails with `privileged control unavailable`. +Kubernetes and other deployments without a matching direct container also fail closed with `privileged control unavailable`. +Run the lifecycle command from a supported direct-container deployment rather than trying to launch the gateway by hand. + +On a direct-container deployment, first confirm that the sandbox is running: + +```bash +$$nemoclaw status +``` + +When `recover` repairs a stopped built-in gateway, NemoClaw automatically retries only when stdout is empty and stderr is exactly one `SUPERVISOR_BUSY` or `SUPERVISOR_UNAVAILABLE` line, with at most three controller attempts. +It does not retry other status or output combinations. +If that bounded retry is exhausted, or if `gateway restart` reports `SUPERVISOR_BUSY`, wait for the active request to finish and retry the command. +If the error mentions `SUPERVISOR_REBUILD_REQUIRED`, `SUPERVISOR_UNAVAILABLE`, a missing `nemoclaw-gateway-control` helper, or a missing managed controller, the sandbox image may predate the current lifecycle contract. +The managed controller also refuses an ambiguous or changing process tree instead of guessing which same-UID process is the gateway. +Rebuild the image before retrying: + +```bash +$$nemoclaw rebuild --yes +``` + +For a custom image, update its Dockerfile to preserve the current NemoClaw entrypoint, root-only gateway control helper, root-only managed controller, and shared supervisor library before rebuilding. + +### Hermes config or shields reports a mutation already in progress + +Hermes host config writes, shields transitions, and lifecycle seals use the same root-only mutation lock. +A host-side config write is bound to the SHA-256 digest of the matching read, installs fresh sealed config inodes, refreshes both config hashes, and restores the prior permissions before releasing that lock. +For shields changes, the lock remains held through recursive state-directory updates, config verification, and content-seal capture. +If a concurrent config or shields command reports `Hermes config mutation is already in progress`, do not remove `/run/nemoclaw/hermes-config-mutation.lock` manually. +Wait for the active config, shields, recovery, or restart command to finish, then retry. +If the command says shields are up, run `$$nemoclaw shields down` before `config set` or `inference set`. + +### Hermes startup reports `HERMES_CONFIG_MUTATION_ORPHANED` + +This refusal means a root-owned config or shields transaction stopped without a safely recoverable complete state. +NemoClaw intentionally does not guess whether a partially updated recursive state tree should be locked or mutable, and it does not treat a leftover lock file as permission to continue. +Do not delete `/run/nemoclaw/hermes-config-mutation.lock`, the restart state, or the persistent transaction marker manually. +The config root remains sealed from the sandbox identity, so an ordinary in-place `rebuild` cannot create a new trustworthy backup and will stop before deleting the sandbox. +If you already have a trusted host-side snapshot, record its selector, destroy the sealed sandbox, re-onboard the same sandbox name from trusted host configuration, and then restore that snapshot: + +```bash +$$nemoclaw snapshot list +$$nemoclaw destroy +$$nemoclaw onboard --name --agent hermes +$$nemoclaw snapshot restore +``` + +Destroying the sealed sandbox permanently discards any state newer than the selected snapshot, so verify that the host-side snapshot exists before confirming destruction. +Without a trusted pre-incident snapshot, automatic state-preserving recovery is not available. +Recreate the sandbox from host-side onboarding configuration only if you accept losing the inaccessible in-sandbox state. + +### Hermes startup reports `HERMES_RESTART_SEAL_ORPHANED` + +This refusal means a container recreation discarded the root-only restart metadata under `/run` while the persistent `/sandbox` tree still carries the frozen transaction marker, or a non-root entrypoint found a root transaction it cannot safely restore. +NemoClaw cannot safely infer the original ownership, modes, or inode flags from a partial seal, so startup fails closed even when `config.yaml` and `.env` still look readable. +Do not repair the paths with manual `chown`, `chmod`, or hash regeneration. +An ordinary `rebuild` cannot safely back up a sealed tree. +Restore a trusted snapshot into a new sandbox as shown above, or recreate from host-side onboarding configuration if no state-preserving recovery is required. + +### Hermes startup reports `HERMES_LOCKED_PARENT_UNPROTECTED` + +This refusal means Hermes config files look shields-locked but `/sandbox` is not `root:sandbox 1775`, so the sandbox identity could rename the entire `.hermes` lock root. +`shields up` cannot repair this after PID 1 has refused startup. +Do not change the parent ownership manually or accept the current bytes as a new seal. +Restore a trusted pre-incident snapshot into a new sandbox, or recreate the sandbox from host-side onboarding configuration. + +### OpenClaw startup reports `OPENCLAW_LOCKED_PARENT_UNPROTECTED` + +This refusal means the OpenClaw config directory is root-owned but `/sandbox` is not `root:sandbox 1775`, so the sandbox identity could rename the entire `.openclaw` lock root. +PID 1 refuses startup before migration or config reads, and `shields up` cannot repair the parent after that refusal. +Do not change the parent ownership manually or accept the current bytes as a new seal. +If you have a trusted host-side snapshot from before the incident, record its selector, destroy the refused sandbox, re-onboard the same sandbox name from trusted host configuration, and restore that snapshot: + +```bash +$$nemoclaw snapshot list +$$nemoclaw destroy +$$nemoclaw onboard --name --agent openclaw +$$nemoclaw snapshot restore +``` + +Destroying the refused sandbox permanently discards state newer than the selected snapshot, so confirm that the host-side snapshot exists before destruction. +Without a trusted pre-incident snapshot, recreate the sandbox from host-side onboarding configuration only if you accept losing the inaccessible in-sandbox state. + ### Sandbox is running an outdated agent version After upgrading NemoClaw, `$$nemoclaw connect` and `$$nemoclaw status` warn if the sandbox is running an older agent version than the current image. @@ -1660,6 +1752,30 @@ After the rebuild completes, return to the Skills page to confirm the skill is r The issues below are common problems you may encounter when running Hermes through `nemohermes`. For setup, refer to [Quickstart with Hermes](../../hermes/get-started/quickstart). +### Hermes restart reports `config hash mismatch` + +A Hermes restart reports `config hash mismatch` when a strict root-owned hash is available and `/sandbox/.hermes/config.yaml` or `/sandbox/.hermes/.env` does not match it. +The direct root-entrypoint supervisor always uses the strict hash at `/etc/nemoclaw/hermes.config-hash`. +The OpenShell-managed controller uses that hash when both config inputs are root-owned and locked. +Mutable config in the managed topology has no durable root-owned hash anchor, so restart retains the same trust and time-of-check/time-of-use limits as managed cold start and cannot use this error to prove direct drift. +Both controllers validate the secret boundary and supervisor runtime environment before they stop the tracked gateway. +They do not recompute a trusted strict hash to adopt direct edits made inside the sandbox. + +For intended changes, use supported host commands such as `nemohermes config set` and `nemohermes inference set` so NemoClaw updates the config and its strict and compatibility hashes together. +Do not edit either hash file manually. + +If direct edits have already caused a mismatch, restore the original config and environment files or rebuild from the registered configuration: + +```bash +nemohermes rebuild --yes +``` + +If the command instead reports `secret-boundary refusal`, inspect `/sandbox/.hermes/.env` for raw secret-shaped values. +Replace them through the supported credential flow so the file contains `openshell:resolve:env:` placeholders, then run `nemohermes recover`. +The Hermes entrypoint supervisor remains responsible for the gateway, dashboard, internal API relay, dashboard relay, and gateway log stream throughout recovery. +In the OpenShell-managed topology, that nonroot supervisor repairs failed auxiliaries continuously, recovers a gateway after four consecutive failed listener or HTTP health checks, and quarantines relaunch after five exits within 60 seconds until the sandbox is recreated. +The host only repairs the host-side OpenShell forwards after the supervised processes pass health checks. + ### Port 8642 in a browser shows a blank page or `Cannot GET /` `nemohermes onboard` forwards port `8642`, but Hermes serves an OpenAI-compatible API at that port, not a chat dashboard. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index 233e8b10f67..c050b05d28a 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -208,7 +208,12 @@ Writable agent state such as plugins, skills, hooks, and workspace metadata live By default, this directory starts writable so the agent can manage its own config, install skills, and write to standard home-directory paths natively. For sensitive workloads, use a reviewed host-side immutability workflow after initial setup so the sandbox user cannot change config or high-risk state entry points. -The immutability workflow locks high-risk state directories (`skills`, `hooks`, `cron`, `agents`, `extensions`, `plugins`, `workspace`, `memory`, `devices`, `canvas`, `telegram`, `wechat`, `whatsapp`, `platforms`, `weixin`, `profiles`, `skins`) to `root:sandbox` with `chmod -R go-w`. +The immutability workflow locks high-risk state directories (`skills`, `agent`, `hooks`, `cron`, `agents`, `extensions`, `plugins`, `workspace`, `memory`, `devices`, `canvas`, `telegram`, `wechat`, `whatsapp`, `platforms`, `weixin`, `profiles`, `skins`) to `root:sandbox` and removes group and world write access. +The root-only helper traverses from opened directory descriptors with no-follow semantics instead of using recursive pathname `chown` or `chmod`. +Read-only preflight and unlock operations reject unsafe external symlinks, hardlinks, special files, cross-device entries, and entries that race the traversal without modifying them. +After the top-level config binding is frozen, lockdown makes containment monotonic. +It removes unsafe symlinks, special entries, and protected-root names that are not directories through descriptor-relative operations without following their targets. +For protected regular files, lockdown publishes a fresh inode, severing hardlinks while preserving file content, read/execute mode, timestamps, and supported extended attributes; this also revokes write authority held through a descriptor opened before `shields up`. The OpenClaw gateway (a member of the `sandbox` group) keeps read access to plugin and agent code; the sandbox user can no longer write them. The same workflow also locks the secret-bearing directories (`credentials`, `identity`, `pairing`) to `root:root 700` with `chmod -R go-rwX`. Neither the sandbox user nor the gateway can read those secrets while the lock is active. @@ -218,8 +223,9 @@ The lock helper silently skips dirs that are not present in a given agent's conf Two exemption kinds keep runtime data writable. The lock inventory omits top-level Hermes runtime dirs (`sessions/`, `memories/`, `logs/`, `cache/`, `plans/`) and the image-build-regenerated `openclaw-weixin/`. The lock helper never touches those paths. -Inside a locked tree, the helper restores `agents//sessions/` to `sandbox:sandbox 2770` after the surrounding `agents/` lock so the OpenClaw TUI can create and write session metadata under an otherwise root-owned parent. -If any high-risk state-dir root is a symlink when the lock runs, the lock helper refuses to proceed and reports "Config not locked: state dir root is a symlink" instead of following the link with privileged `chown -R` / `chmod -R`. +Inside a locked tree, the helper keeps each `agents//sessions/` root at `sandbox:sandbox 2770` so the OpenClaw TUI can create and write session metadata under an otherwise root-owned parent. +It validates the carve-out root but deliberately does not traverse or rewrite live session descendants. +Cross-device entries, detected traversal races, or failures to remove or replace an unsafe entry make lockdown fail closed with the exact path and reason. - **DAC permissions (default).** The sandbox user owns `/sandbox/.openclaw` with mode `2770` (setgid `sandbox:sandbox`) and `openclaw.json` with mode `660`, so the agent and its group can read and write config directly. @@ -328,14 +334,16 @@ Refer to [Sandbox Hardening](../deployment/sandbox-hardening). ### Gateway Process Isolation -The in-sandbox gateway runs as a separate `gateway` user, not as the `sandbox` user that runs the agent. +Gateway and agent UID isolation depends on the container process topology. +A direct root-entrypoint container runs the gateway as the separate `gateway` user and the agent as the `sandbox` user. +An OpenShell-managed container has OpenShell as PID 1 and launches nonroot `nemoclaw-start`, so the supervisor, gateway, and agent all use the `sandbox` UID. | Aspect | Detail | |---|---| -| Default | The entrypoint starts the gateway process using `gosu gateway`, isolating it from the agent's `sandbox` user. | -| What you can change | This is not a user-facing knob. The entrypoint enforces it when running as root. In non-root mode (when OpenShell sets `no-new-privileges`), gateway process isolation does not work because `gosu` cannot change users. | -| Risk if relaxed | If the gateway and agent run as the same user, the agent can kill the gateway process and restart it with a tampered configuration (the "fake-HOME" attack). | -| Recommendation | No action needed. The entrypoint handles this automatically. Be aware that non-root mode disables this isolation. | +| Default | Direct root entrypoints use `gosu gateway` for UID isolation. The OpenShell-managed topology runs the gateway and agent under the same sandbox UID because `no-new-privileges` prevents the nonroot entrypoint from changing users. | +| What you can change | This is not a user-facing knob. The selected container topology determines whether the entrypoint can step down from root to the gateway UID. | +| Risk if relaxed | A same-UID agent can signal peer processes and can attempt to imitate the expected gateway process shape. The root managed controller prevents PID-reuse mistakes, but it cannot prove provenance against a malicious same-UID process or provide the direct root-entrypoint restart seal for mutable config. | +| Recommendation | Use a direct root-entrypoint deployment when separate gateway and agent UIDs are required. Treat the managed controller as authenticated lifecycle and exact-target safety, not as a same-UID provenance boundary. | ### No New Privileges @@ -346,7 +354,7 @@ The `no-new-privileges` flag prevents processes from gaining additional privileg | Default | OpenShell sets `PR_SET_NO_NEW_PRIVS` using `prctl()` inside the sandbox process as part of the seccomp filter setup. The NemoClaw Compose example also shows the equivalent `security_opt: no-new-privileges:true` setting. | | What you can change | OpenShell's seccomp path enforces this inside the sandbox. It is not a user-facing knob. | | Risk if relaxed | Without this flag, a compromised process could execute a setuid binary to escalate to root inside the container, then attempt container escape techniques. | -| Recommendation | No action needed. OpenShell enforces this automatically when the sandbox network policy is active. This flag prevents `gosu` from switching users, so non-root mode disables gateway process isolation in the NemoClaw entrypoint. | +| Recommendation | No action needed. OpenShell enforces this automatically when the sandbox network policy is active. In the OpenShell-managed topology, this flag also means the nonroot entrypoint and gateway remain under the sandbox UID. | ### Process Limit @@ -640,6 +648,7 @@ The following patterns weaken security without providing meaningful benefit. | Limitation | Impact | Mitigation | |-----------|--------|------------| | Bypassing managed gateway paths | Network policy and inference auth are not enforced when an agent runtime is launched outside the NemoClaw-managed gateway path. | Use NemoClaw-managed sandbox entrypoints for production workflows. | +| Same-UID lifecycle control in the OpenShell-managed topology | The root controller authenticates the host action, verifies a stable process shape, pidfd-targets the exact observed child, and proves replacement health. It cannot establish malicious process provenance when the supervisor, gateway, and agent share the sandbox UID. Mutable config also has managed cold-start trust and time-of-check/time-of-use limits unless it is root-owned and locked. | Use a direct root-entrypoint deployment when UID isolation and the root restart seal are required. Lock managed config before treating the strict hash as a trust anchor, and recreate a sandbox after suspected same-UID compromise. | | Direct filesystem writes bypass application-layer scanners | Application-layer scanners can intercept agent tool calls, not arbitrary raw filesystem writes (e.g., `echo secret > file`). | Landlock restricts writable paths. Application-layer scanning is defense-in-depth, not a filesystem-level control. | | Base64/hex-encoded secrets are not detected | Content-based regex scanning cannot detect encoded or obfuscated secrets. | Use environment variables or credential stores instead of writing secrets to files. | diff --git a/docs/security/openshell-0.0.71-gateway-auth-review.mdx b/docs/security/openshell-0.0.71-gateway-auth-review.mdx index a3632269c71..c84623c5728 100644 --- a/docs/security/openshell-0.0.71-gateway-auth-review.mdx +++ b/docs/security/openshell-0.0.71-gateway-auth-review.mdx @@ -4,7 +4,9 @@ title: "OpenShell 0.0.71 Gateway Authentication Review" sidebar-title: "OpenShell 0.0.71 Review" description: "Reviews the OpenShell 0.0.71 gateway authentication boundary, compatibility behavior, and supporting validation in NemoClaw." -description-agent: "Reviews the OpenShell 0.0.71 gateway authentication boundary and evidence. Use when evaluating gateway mTLS, sandbox JWTs, compatibility behavior, or recovery controls." +description-agent: >- + Reviews the OpenShell 0.0.71 gateway authentication boundary and evidence. + Use when evaluating gateway mTLS, sandbox JWTs, compatibility behavior, or recovery controls. keywords: ["OpenShell 0.0.71", "gateway authentication", "mTLS", "sandbox JWT"] content: type: "reference" @@ -16,22 +18,54 @@ Scope: NemoClaw Docker-driver gateway config generated for OpenShell `0.0.71`. ## Source-of-Truth Boundaries -- OpenShell gateway auth source contract: invalid state is an OpenShell `0.0.71` Docker-driver gateway launched from NemoClaw without the upstream config-file auth policy, local mTLS bundle, sandbox JWT bundle, or Docker bridge callback route that OpenShell expects. Source boundary is upstream OpenShell config/auth/listener/Docker-driver behavior; NemoClaw only generates config, local TLS/JWT material, bind policy, and launch env. Regression coverage is the live `openshell-gateway-auth-source-contract` scenario plus local config/env/launch tests. Remove the NemoClaw-local compatibility notes when OpenShell exposes a stable SDK/config contract that makes this generated config surface unnecessary. -- Docker-hosted gateway compatibility container: OpenShell `0.0.68` lowered the standalone Linux gateway's glibc floor to `2.28`, and `0.0.71` carries that support. Supported Ubuntu 20.04+, RHEL/Rocky 8+, Amazon Linux 2023+, and Fedora 32+ hosts therefore launch the gateway directly. NemoClaw retains the existing container bridge only as an explicit opt-in for an older host below the upstream support floor or a forced diagnostic run. `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH=1` is still required before using `--network host` and read-only Docker socket access. The container keeps the main listener on `127.0.0.1`, drops Linux capabilities, sets `no-new-privileges`, and publishes no additional Docker ports. The production onboarding path emits this trust boundary through `console.warn`. This fallback does not extend OpenShell's supported host matrix. Regression coverage is the compatibility-container launch/config tests plus the live gateway auth source-contract scenario. Rootless Docker/Podman remain outside the accepted path for this shim until the OpenShell Docker driver publishes a supported rootless compatibility contract. -- Hermes env-file secret-boundary enforcement: invalid state is a Hermes sandbox recovery path that restarts or accepts a running gateway while `/sandbox/.hermes/.env` contains raw secret-shaped values that the Hermes startup validator would reject. Source boundary is the Hermes image entrypoint and `validate-hermes-env-secret-boundary.py`; NemoClaw only re-runs that source validator on recovery/probe paths that bypass the entrypoint. This PR cannot retroactively bake the validator into already-created older Hermes sandbox images, so missing-validator recovery now fails closed with a re-image instruction instead of claiming the boundary was checked. Regression coverage lives in `src/lib/actions/sandbox/hermes-secret-boundary-recovery.test.ts`, `src/lib/agent/runtime-hermes-secret-boundary-shape.test.ts`, and `src/lib/agent/runtime-hermes-secret-boundary-behavioural.test.ts`. Remove the NemoClaw recovery-side shim when Hermes exposes a stable recovery entrypoint that always re-enters the validator. -- Gateway JWT generation lock recovery: invalid state is a crashed NemoClaw process leaving `.jwt-generating` behind after taking the exclusive host-side bundle-generation lock. The source boundary is NemoClaw's own atomic JWT bundle writer; OpenShell consumes the resulting paths but does not own this lock, so the source fix belongs here. Live contenders wait up to five seconds for the owner to publish its bundle, after which they fail closed. A stale lock is removed only when it contains a numeric owner PID that the operating system reports as absent, and a per-acquisition nonce prevents a replaced lock from being mistaken for the observed owner. Malformed or unprobeable locks continue to fail closed. Regression coverage lives in `src/lib/onboard/docker-driver-gateway-jwt-bundle.test.ts`, including a synchronized 12-process contention test. Remove the lock and its recovery together if JWT bundle generation moves into OpenShell or to an OS-backed locking primitive. -- Markerless sandbox gateway recovery output: invalid state is newer OpenShell sandbox exec/relaunch output that starts the gateway launcher but omits NemoClaw's legacy `GATEWAY_PID=` or `ALREADY_RUNNING` markers. Source boundary is OpenShell exec/recovery output format; NemoClaw treats the text as "may have started" only and still requires a healthy gateway probe. Regression coverage lives in `test/cli/connect-recovery-markerless.test.ts`. Remove the markerless heuristic when OpenShell provides a stable machine-readable recovery marker. -- Sessions admin gateway RPC helper: invalid state is a host CLI session reset/delete action that needs OpenClaw backend/operator scope while preserving gateway token, loopback, and auto-pair boundaries. Source boundary is OpenClaw's gateway-runtime API; NemoClaw's helper is limited to `sessions.reset` and `sessions.delete`. Regression coverage lives in `src/lib/actions/sandbox/sessions/gateway-rpc-call.test.ts`. Add new methods only with a caller, allowlist entry, and negative test. +- OpenShell gateway auth source contract: invalid state is an OpenShell `0.0.71` Docker-driver gateway launched from NemoClaw without the upstream config-file auth policy, local mTLS bundle, sandbox JWT bundle, or Docker bridge callback route that OpenShell expects. + Source boundary is upstream OpenShell config/auth/listener/Docker-driver behavior; NemoClaw only generates config, local TLS/JWT material, bind policy, and launch env. + Regression coverage is the live `openshell-gateway-auth-source-contract` scenario plus local config/env/launch tests. + Remove the NemoClaw-local compatibility notes when OpenShell exposes a stable SDK/config contract that makes this generated config surface unnecessary. +- Docker-hosted gateway compatibility container: OpenShell `0.0.68` lowered the standalone Linux gateway's glibc floor to `2.28`, and `0.0.71` carries that support. + Supported Ubuntu 20.04+, RHEL/Rocky 8+, Amazon Linux 2023+, and Fedora 32+ hosts therefore launch the gateway directly. + NemoClaw retains the existing container bridge only as an explicit opt-in for an older host below the upstream support floor or a forced diagnostic run. + `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH=1` is still required before using `--network host` and read-only Docker socket access. + The container keeps the main listener on `127.0.0.1`, drops Linux capabilities, sets `no-new-privileges`, and publishes no additional Docker ports. + The production onboarding path emits this trust boundary through `console.warn`. + This fallback does not extend OpenShell's supported host matrix. + Regression coverage is the compatibility-container launch/config tests plus the live gateway auth source-contract scenario. + Rootless Docker/Podman remain outside the accepted path for this shim until the OpenShell Docker driver publishes a supported rootless compatibility contract. +- Hermes env-file secret-boundary enforcement: invalid state is a Hermes sandbox recovery path that restarts or accepts a running gateway while `/sandbox/.hermes/.env` contains raw secret-shaped values that the Hermes startup validator would reject. + Source boundary is the Hermes image entrypoint and `validate-hermes-env-secret-boundary.py`; NemoClaw re-runs that source validator through the topology-specific gateway controller before recovery/probe paths can succeed. + The direct root-entrypoint supervisor validates the boundary in `agents/hermes/start.sh`, while the OpenShell-managed topology validates it in `scripts/managed-gateway-control.py`; both surface typed failures through the root-only gateway-control path. + This PR cannot retroactively bake the validator into already-created older Hermes sandbox images, so missing-validator recovery fails closed with a re-image instruction instead of claiming the boundary was checked. + Regression coverage lives in `test/process-recovery.test.ts`, `test/managed-gateway-control.test.ts`, and `test/hermes-gateway-supervisor-recovery.test.ts`. + Remove the NemoClaw recovery-side checks when every supported Hermes topology exposes a stable recovery entrypoint that always re-enters the validator. +- Gateway JWT generation lock recovery: invalid state is a crashed NemoClaw process leaving `.jwt-generating` behind after taking the exclusive host-side bundle-generation lock. + The source boundary is NemoClaw's own atomic JWT bundle writer; OpenShell consumes the resulting paths but does not own this lock, so the source fix belongs here. + Live contenders wait up to five seconds for the owner to publish its bundle, after which they fail closed. + A stale lock is removed only when it contains a numeric owner PID that the operating system reports as absent, and a per-acquisition nonce prevents a replaced lock from being mistaken for the observed owner. + Malformed or unprobeable locks continue to fail closed. + Regression coverage lives in `src/lib/onboard/docker-driver-gateway-jwt-bundle.test.ts`, including a synchronized 12-process contention test. + Remove the lock and its recovery together if JWT bundle generation moves into OpenShell or to an OS-backed locking primitive. +- Authenticated sandbox gateway recovery completion: invalid state is treating markerless OpenShell sandbox exec output as proof that a built-in gateway started. + NemoClaw accepts built-in recovery only when the topology-specific controller emits a `GATEWAY_PID=` completion marker and the managed health probe passes. + Regression coverage lives in `test/process-recovery.test.ts` and `test/process-recovery-managed-controller.test.ts`. + Remove the completion parser when OpenShell provides a stable machine-readable controller response. +- Sessions admin gateway RPC helper: invalid state is a host CLI session reset/delete action that needs OpenClaw backend/operator scope while preserving gateway token, loopback, and auto-pair boundaries. + Source boundary is OpenClaw's gateway-runtime API; NemoClaw's helper is limited to `sessions.reset` and `sessions.delete`. + Regression coverage lives in `src/lib/actions/sandbox/sessions/gateway-rpc-call.test.ts`. + Add new methods only with a caller, allowlist entry, and negative test. ## Acceptance Mapping -Issue #5591 is the dependency-update umbrella. Its literal proposed-design clauses map across the split dependency PRs: +Issue #5591 is the dependency-update umbrella. +Its literal proposed-design clauses map across the split dependency PRs: - `Latest stable version of Hermes`: handled by PR #5594 (`dep/hermes-v2026.6.19`), not by this OpenShell PR. - `Latest version of OpenShell`: this PR pins and validates OpenShell `0.0.71`. - `Latest stable version of OpenClaw`: handled by PR #5595 (`dep/openclaw-2026.6.9`), not by this OpenShell PR. -Issue #2478 is not an acceptance target for this OpenShell version-pin PR. Its crash-loop clauses include "Every time it boots, it crashes on the same line" and "`connect` doesn't auto-recover" because `@homebridge/ciao` calls `os.networkInterfaces()` under sandbox netlink restrictions. The source fix remains the existing guard-chain/preload work validated by `test/e2e/live/issue-2478-crash-loop-recovery.test.ts`. This PR only updates markerless recovery wrapper behavior: newer OpenShell relaunch output can be accepted after, and only after, the gateway health probe succeeds. +Issue #2478 is not an acceptance target for this OpenShell version-pin PR. +Its crash-loop clauses include "Every time it boots, it crashes on the same line" and "`connect` doesn't auto-recover" because `@homebridge/ciao` calls `os.networkInterfaces()` under sandbox netlink restrictions. +The source fix remains the existing guard-chain/preload work validated by `test/e2e/live/issue-2478-crash-loop-recovery.test.ts`. +Built-in recovery still requires an authenticated controller completion marker and a successful managed health probe. ## Source Review @@ -43,25 +77,35 @@ Reviewed upstream source at `NVIDIA/OpenShell@v0.0.71` (`a242f84bb367d6df7d4d133 - `crates/openshell-server/src/multiplex.rs`: mTLS user authentication promotes a verified client certificate into a user principal when `[openshell.gateway.mtls_auth] enabled = true`; when `allow_unauthenticated_users` is false, missing auth is rejected. - `crates/openshell-server/src/multiplex.rs`: user principals are rejected from sandbox-only methods with `permission_denied`, while sandbox principals are checked against the sandbox method allowlist. - `crates/openshell-server/src/lib.rs`: the server binds the configured main listener plus compute-driver `gateway_bind_addresses`, skipping only driver addresses already covered by a wildcard listener. -- `crates/openshell-driver-docker/src/lib.rs`: Docker-driver sandboxes see loopback and arbitrary hostnames rewritten to `host.openshell.internal:`, and native Linux Docker gets a bridge-gateway bind address such as `:`. OpenShell `0.0.70` also makes the configured `supervisor_image` authoritative ahead of local build artifacts. +- `crates/openshell-driver-docker/src/lib.rs`: Docker-driver sandboxes see loopback and arbitrary hostnames rewritten to `host.openshell.internal:`, and native Linux Docker gets a bridge-gateway bind address such as `:`. + OpenShell `0.0.70` also makes the configured `supervisor_image` authoritative ahead of local build artifacts. - `crates/openshell-server/src/auth/sandbox_jwt.rs`: `SandboxJwtAuthenticator` validates Ed25519/EdDSA sandbox JWTs, requires the configured `kid`, `iss`, `aud`, and `sub`, and rejects expired tokens while allowing non-matching `kid` values to fall through to other authenticators. - `crates/openshell-supervisor-network/src/l7`: OpenShell `0.0.68` blocks the h2c L7 tunnel escape before traffic reaches the gateway auth boundary. ## NemoClaw Boundary -NemoClaw generates an OpenShell gateway config with `gateway_jwt`, local TLS, mTLS user authentication, and `allow_unauthenticated_users = false`. Host-side OpenShell CLI user calls use local mTLS; sandbox callbacks use mTLS plus the OpenShell gateway JWT. In this PR, host-side OpenShell CLI user calls use local mTLS instead of the unsafe unauthenticated local-user fallback. +NemoClaw generates an OpenShell gateway config with `gateway_jwt`, local TLS, mTLS user authentication, and `allow_unauthenticated_users = false`. +Host-side OpenShell CLI user calls use local mTLS; sandbox callbacks use mTLS plus the OpenShell gateway JWT. +In this PR, host-side OpenShell CLI user calls use local mTLS instead of the unsafe unauthenticated local-user fallback. -The generated config sets `[openshell.gateway.tls]` with the NemoClaw-owned local server certificate, requires client certificates, enables `[openshell.gateway.mtls_auth]`, and provides Docker `guest_tls_ca`, `guest_tls_cert`, and `guest_tls_key` entries so supervisor-to-gateway callbacks use the same local CA. It also scrubs inherited `OPENSHELL_DISABLE_GATEWAY_AUTH=true` from host and compatibility-container launches. +The generated config sets `[openshell.gateway.tls]` with the NemoClaw-owned local server certificate, requires client certificates, enables `[openshell.gateway.mtls_auth]`, and provides Docker `guest_tls_ca`, `guest_tls_cert`, and `guest_tls_key` entries so supervisor-to-gateway callbacks use the same local CA. +It also scrubs inherited `OPENSHELL_DISABLE_GATEWAY_AUTH=true` from host and compatibility-container launches. -The local TLS reuse check allows a fixed 5-minute certificate validity skew to absorb normal host/container clock drift while still regenerating bundles outside that bounded window; the bound is intentionally not environment-overridable for this release so deployments cannot silently widen the local mTLS acceptance window. The sandbox JWT config uses OpenShell's `ttl_secs = 3600` gateway contract: short enough for local sandbox callbacks, long enough to avoid unnecessary re-mint churn during normal Docker-driver operations, and covered by the upstream OpenShell sandbox JWT expiry tests plus NemoClaw config-auth contract tests. +The local TLS reuse check allows a fixed 5-minute certificate validity skew to absorb normal host/container clock drift while still regenerating bundles outside that bounded window; the bound is intentionally not environment-overridable for this release so deployments cannot silently widen the local mTLS acceptance window. +The sandbox JWT config uses OpenShell's `ttl_secs = 3600` gateway contract: short enough for local sandbox callbacks, long enough to avoid unnecessary re-mint churn during normal Docker-driver operations, and covered by the upstream OpenShell sandbox JWT expiry tests plus NemoClaw config-auth contract tests. -The Docker-hosted compatibility gateway requires `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH=1` and keeps the main OpenShell listener on `127.0.0.1`. Sandbox callback reachability is preserved by OpenShell's Docker driver: it rewrites the sandbox-facing endpoint to `host.openshell.internal:` and the OpenShell server adds the computed Docker bridge listener when that route is needed. `NEMOCLAW_OPENSHELL_GATEWAY_COMPAT_BIND_ADDRESS=0.0.0.0` is rejected so the main listener is not widened. The compatibility container does not publish Docker ports; it uses host networking only for parity with the host gateway's Docker bridge listener calculation after explicit opt-in. +The Docker-hosted compatibility gateway requires `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH=1` and keeps the main OpenShell listener on `127.0.0.1`. +Sandbox callback reachability is preserved by OpenShell's Docker driver: it rewrites the sandbox-facing endpoint to `host.openshell.internal:` and the OpenShell server adds the computed Docker bridge listener when that route is needed. +`NEMOCLAW_OPENSHELL_GATEWAY_COMPAT_BIND_ADDRESS=0.0.0.0` is rejected so the main listener is not widened. +The compatibility container does not publish Docker ports; it uses host networking only for parity with the host gateway's Docker bridge listener calculation after explicit opt-in. -Package-managed Docker-driver gateways also reject `NEMOCLAW_GATEWAY_BIND_ADDRESS=0.0.0.0` while the 0.0.71 Docker-driver config is active. Use the dashboard bind setting for remote dashboard exposure instead of widening the OpenShell gateway surface. +Package-managed Docker-driver gateways also reject `NEMOCLAW_GATEWAY_BIND_ADDRESS=0.0.0.0` while the 0.0.71 Docker-driver config is active. +Use the dashboard bind setting for remote dashboard exposure instead of widening the OpenShell gateway surface. ## Upstream Contract Coverage -`test/e2e/live/openshell-gateway-auth-source-contract.test.ts` is the live/source-contract scenario for this PR. It uses OpenShell 0.0.71 plus NemoClaw-generated `OPENSHELL_GATEWAY_CONFIG` and verifies: +`test/e2e/live/openshell-gateway-auth-source-contract.test.ts` is the live/source-contract scenario for this PR. +It uses OpenShell 0.0.71 plus NemoClaw-generated `OPENSHELL_GATEWAY_CONFIG` and verifies: - no-token Docker sandbox-origin access to a user-callable gateway API is rejected or unreachable; - valid sandbox JWT access from Docker origin to an allowlisted sandbox method reaches OpenShell auth over `host.openshell.internal` with the generated guest mTLS material, and a token minted for one sandbox is rejected when it requests another sandbox config; diff --git a/docs/security/tcb-boundary.mdx b/docs/security/tcb-boundary.mdx new file mode 100644 index 00000000000..8e861f0cc76 --- /dev/null +++ b/docs/security/tcb-boundary.mdx @@ -0,0 +1,135 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Trusted Computing Base for Gateway Lifecycle Control" +sidebar-title: "Trusted Computing Base" +description: "Defines the trusted computing base, privilege boundaries, and review invariants for NemoClaw gateway lifecycle and shields operations." +description-agent: >- + Maps NemoClaw gateway lifecycle and shields components to their trust boundaries, threats, privilege levels, and verification requirements. + Use when reviewing privileged gateway restart, config mutation, or shields changes. +keywords: ["nemoclaw trusted computing base", "gateway lifecycle security", "shields trust boundary"] +content: + type: "reference" +--- + +NemoClaw uses a small set of host and sandbox components to restart built-in gateways and change shields posture without granting lifecycle authority to the sandbox agent. +This page defines the trusted computing base for those operations and the evidence required when the boundary changes. + +## Security Boundary + +The operator, NemoClaw host CLI, OpenShell control plane, container runtime, and immutable image contents are trusted. +The agent process, agent-writable configuration and state, mutable environment variables, status files written by the sandbox user, and network responses are untrusted. +Host root compromise and replacement of root-owned image files are outside this boundary because either condition already controls the sandbox runtime. + +The lifecycle boundary maintains these invariants. + +- Only a registry-selected sandbox can receive a host lifecycle request. +- Only root-owned installed helpers can perform privileged lifecycle or filesystem transitions. +- A mutable path, status file, process ID, command line, or listener alone never grants authority. +- Process decisions bind the observed process ID to its start identity, parent chain, user identity, PID namespace, executable shape, and listener ownership where the topology exposes those signals. +- Filesystem transitions open trusted parents by descriptor, reject symlinks and unsafe hard links, bound traversal and input size, and verify the resulting inode state. +- A failed or ambiguous proof stops the operation without reporting recovery or a locked shields posture. +- The OpenShell-managed topology authenticates the host action but does not create gateway and agent UID isolation. + + +Changes to a component or invariant on this page require sensitive-path review and focused regression coverage before merge. +A successful build does not replace review of privilege, process identity, descriptor safety, rollback, and fail-closed behavior. + + +## Component Map + +| Component | Execution and privilege | Trusted input | Security responsibility | +|---|---|---|---| +| `scripts/state-dir-guard.py` | The installed copy is root-owned and mode `0500`; the host reaches it through the shields transaction. | Fixed paths, a bounded action contract, and a lock token from the host coordinator. | Applies descriptor-rooted state-directory posture changes, rejects link and mount substitution, bounds traversal, and verifies the committed modes and ownership. | +| `scripts/openclaw-config-guard.py` | The installed copy is root-owned and mode `0500`; direct root PID 1 or the authenticated host transaction invokes it. | Bounded strict JSON for writes, stable captured config bytes for restart validation, and fixed installed parser paths for existing JSON5 config. | Seals and unseals OpenClaw config with no-follow descriptors, stable inode checks, atomic replacement, hash coherence, and recoverable transaction journals. | +| `scripts/managed-gateway-control.py` | The installed copy is root-owned and mode `0500`; the host invokes it through sanitized registry-scoped direct-container execution. | A fixed action, a 64-character nonce, fixed installed helpers, and a live OpenShell process tree observed through `/proc`. | Authenticates the host action, proves the managed supervisor and gateway identity, holds a root-owned mode `0600` lifecycle lock, publishes one root-owned mode `0444` exact-exit authorization bound to the gateway and live root controller identities, signals through a pidfd, waits for the normal respawn loop, and verifies listener and HTTP health. | +| `src/lib/shields/transition-lock.ts` | Runs in the host CLI under the operator account and owns the canonical per-sandbox transition lock. | Host state directory entries whose owner PID and start identity match the live lock owner. | Serializes shields mutations, rejects ambiguous or reused owners, and allows takeover only through the explicit recovery contract. | +| `src/lib/shields/timer-bound-lock.ts` | Runs in the host CLI and composes the transition lock with the recorded auto-restore generation. | A validated timer marker and transition owner from the host state directory. | Prevents an expired or replaced timer from authorizing a later mutation and keeps restore authority bound to one generation. | +| `src/lib/shields/verify-lock.ts` | Runs in the host CLI and delegates sandbox inspection through the privileged execution adapter. | Resolved built-in agent paths and the expected locked posture recorded by the host. | Verifies modes, ownership, immutable flags, layout, and recorded content hashes before NemoClaw reports shields as locked. | +| `agents/hermes/runtime-config-guard.py` | The installed copy is root-owned; its privileged actions require direct startup authority, a root-owned readiness lease, or the narrowly proven OpenShell-managed startup shape. | Fixed Hermes paths, bounded actions, stable descriptor snapshots, a transaction token, and authenticated startup or host authority. | Enforces the Hermes secret boundary, config and hash transactions, restart seals, shields transitions, rollback, and stable state-directory posture. | + +The root-owned `/usr/local/bin/nemoclaw-gateway-control` entry point and the sourced `gateway-supervisor.sh` library are adjacent trusted entry points. +The entry point validates the action and nonce, rejects nonroot callers, classifies the direct and OpenShell-managed topologies, and forwards only to the matching controller. +The supervisor owns the direct PID 1 request channel and publishes bounded status for the matching nonce. + +## Interaction Model + +```mermaid +flowchart LR + Operator[Operator] --> CLI[NemoClaw host CLI] + CLI --> HostLock[Transition and timer-bound locks] + HostLock --> RootExec[Registry-scoped root execution] + RootExec --> Control[nemoclaw-gateway-control] + Control --> Direct[Direct root PID 1 supervisor] + Control --> Managed[Managed gateway controller] + Direct --> Config[OpenClaw or Hermes config guard] + Managed --> Config + HostLock --> State[State directory guard] + HostLock --> Verify[Shields lock verifier] + Config --> Gateway[Proven gateway process] + State --> Verify +``` + +The host CLI first resolves the sandbox from host-owned registry state and selects the built-in agent topology. +Gateway restart generates a fresh nonce and enters `nemoclaw-gateway-control` as root with injection-capable environment variables cleared. +The direct topology publishes a root-owned request to PID 1, while the OpenShell-managed topology executes `managed-gateway-control.py` directly. +Both paths prove the exact replacement gateway and health state before the host repairs port forwards or reports success. + +Shields mutations acquire the host transition lock before changing network policy, config posture, timer authority, or host state. +The coordinator invokes the agent-specific config guard and `state-dir-guard.py`, verifies the resulting posture, then commits host state and audit output. +Rollback keeps the same lock and transaction token so a stale callback cannot adopt the transition. + +## Filesystem and Descriptor Proofs + +Production Python guards bind privileged helpers and parser dependencies to fixed installed paths. +The managed controller enables alternate procfs and filesystem roots only when a source checkout also sets the explicit `NEMOCLAW_MANAGED_CONTROL_ALLOW_NONROOT_TEST=1` test flag. +They open trusted directories and files with no-follow and close-on-exec flags, compare descriptor metadata, and reject unsafe owners, modes, link counts, mounts, and inode replacement. +They bound file size, entry count, logical bytes, journal size, and process-table traversal before reading attacker-influenced state. +Atomic replacement uses fresh files in the already opened parent directory and verifies the installed inode before the transaction commits. + +OpenClaw writes from NemoClaw must be strict JSON. +Existing OpenClaw runtime config can contain JSON5 comments or trailing commas, so restart validation retains the packaged JSON5 parser for read compatibility. +The guard verifies `/usr/local/bin/node` and `/opt/nemoclaw/node_modules/json5` as root-owned, non-writable installed objects before invoking the parser with a fixed environment, closed file descriptors, bounded input, and a timeout. +The image build repeats the ownership and writability checks after lockfile-based `npm ci` installation. + +## Process and Listener Proofs + +The direct supervisor records the gateway process ID and kernel start identity and verifies the parent relationship before signalling or reaping the process. +The Docker health fallback reads the same two-field record, verifies the process state and start identity before and after reading its command line, and accepts only the exact installed gateway arguments for the configured port or a known rewritten gateway process title. +A PID namespace inode would not distinguish PID reuse inside the same container because every process shares that namespace; PID 1 exit also terminates the container and removes the `/tmp` record. + +The managed controller uses a stronger process key because OpenShell remains PID 1 while nonroot children can be replaced. +Its key includes PID, start identity, parent PID, user IDs, namespace PID and inode, command line, process state, and procfs device and inode metadata. +It verifies listener ownership in the same network namespace and uses a pidfd for signalling where the platform supports it. +For managed Hermes replacement, the controller binds the exact-exit authorization to the gateway process ID and start identity plus its own process ID and start identity. +The nonroot supervisor accepts that authorization only while the same root controller with the fixed installed command shape remains live. +The authorization records authenticated host intent for the exact exit rather than proving that the host signal was its sole cause; a mismatched or orphaned authorization counts as an unexpected exit. + +## Topology Limits + +The direct topology separates the root supervisor, `gateway` UID, and `sandbox` UID. +The root process belongs to the `sandbox` supplementary group because capability-dropped PID 1 still needs descriptor-safe access to the mutable tree before it can validate or transition the tree. +This membership is an intentional base-image invariant rather than a stale-base compatibility exception. + +The OpenShell-managed topology runs the supervisor, gateway, and agent under the same `sandbox` UID. +The managed controller prevents accidental cross-process signalling and PID reuse, but it cannot prove provenance against a malicious same-UID agent or create UID isolation. +Remove this compatibility path only after the minimum supported OpenShell provides a root-owned lifecycle supervisor or a gateway UID distinct from the agent. + +The macOS VM compatibility path accepts a nonroot NemoClaw PID 1 when the VM ownership remap prevents a root-owned readiness lease. +The guard first proves either the live NemoClaw PID 1 shape, a readiness lease bound to the current PID 1, or the complete OpenShell-managed supervisor shape. +Remove this path when the minimum supported OpenShell macOS VM preserves root ownership for the readiness lease. + +## Review and Removal Conditions + +Reviewers must re-check this page when a lifecycle helper, shields coordinator, config guard, installed mode, process proof, or test seam changes. +The following conditions govern current compatibility code and architecture work. + +- Remove the final OpenClaw stale-base group repair when the minimum supported OpenClaw sandbox base tag is `v0.0.71` or newer, the source provisioning contract guarantees both memberships, and both final-image tests pass. +- Keep root membership in the base image while capability-dropped root PID 1 owns lifecycle validation for sandbox-group mutable state. +- Remove the managed shared-UID controller when the supported OpenShell topology provides a root-owned supervisor or a distinct gateway UID. +- Remove JSON5 restart validation only when every supported OpenClaw config is guaranteed to be strict JSON; NemoClaw write transactions already reject JSON5-only syntax. +- Decompose the host shields coordinator only with behavior-preserving changes that keep policy, config, timer, rollback, state, and audit ordering under one typed transaction contract. +- Keep the managed controller's source-path and fake-root overrides disabled unless the explicit source test flag is present, and keep installed helpers bound to fixed production paths. + +Final-image validation must cover both built-in images. +It checks helper owners and modes, root and gateway supplementary groups, root execution of the read-only `probe` path, and refusal before helper entry when the sandbox user attempts execution. diff --git a/scripts/checks/no-test-dist-imports.ts b/scripts/checks/no-test-dist-imports.ts index c9c1e366b90..c004856d135 100644 --- a/scripts/checks/no-test-dist-imports.ts +++ b/scripts/checks/no-test-dist-imports.ts @@ -60,6 +60,221 @@ function isCompiledInternalSpecifier(specifier: string): boolean { ); } +type Binding = + | { kind: "create-require" } + | { kind: "json-object" } + | { kind: "module-namespace" } + | { kind: "path" } + | { kind: "path-builder"; method: "join" | "resolve" } + | { kind: "require" } + | { kind: "static-string"; value: string } + | { kind: "string-constructor" } + | { kind: "unknown" }; + +type ScopeKind = "block" | "function" | "root"; + +interface LexicalScope { + bindings: Map; + kind: ScopeKind; + parent: LexicalScope | null; +} + +function resolveBinding(scope: LexicalScope, name: string): Binding | undefined { + for (let current: LexicalScope | null = scope; current; current = current.parent) { + const binding = current.bindings.get(name); + if (binding) return binding; + } + return undefined; +} + +function unwrapExpression(node: ts.Expression): ts.Expression { + let current = node; + while ( + ts.isParenthesizedExpression(current) || + ts.isAsExpression(current) || + ts.isTypeAssertionExpression(current) || + ts.isNonNullExpression(current) || + ts.isSatisfiesExpression(current) + ) { + current = current.expression; + } + return current; +} + +function staticString(node: ts.Expression | undefined, scope: LexicalScope): string | undefined { + if (!node) return undefined; + const expression = unwrapExpression(node); + if (ts.isStringLiteralLike(expression)) return expression.text; + if (ts.isIdentifier(expression)) { + const binding = resolveBinding(scope, expression.text); + return binding?.kind === "static-string" ? binding.value : undefined; + } + return undefined; +} + +function accessedMember( + node: ts.Expression, + scope: LexicalScope, +): { name: string; target: ts.Expression } | undefined { + const expression = unwrapExpression(node); + if (ts.isPropertyAccessExpression(expression)) { + return { name: expression.name.text, target: expression.expression }; + } + if (ts.isElementAccessExpression(expression)) { + const name = staticString(expression.argumentExpression, scope); + return name === undefined ? undefined : { name, target: expression.expression }; + } + return undefined; +} + +function isModuleNamespaceReference(node: ts.Expression, scope: LexicalScope): boolean { + const expression = unwrapExpression(node); + if (ts.isIdentifier(expression)) { + return resolveBinding(scope, expression.text)?.kind === "module-namespace"; + } + return ( + ts.isCallExpression(expression) && + isRequireReference(expression.expression, scope) && + ["module", "node:module"].includes(staticString(expression.arguments[0], scope) ?? "") + ); +} + +function isCreateRequireReference(node: ts.Expression, scope: LexicalScope): boolean { + const expression = unwrapExpression(node); + if (ts.isIdentifier(expression)) { + return resolveBinding(scope, expression.text)?.kind === "create-require"; + } + const member = accessedMember(expression, scope); + return member?.name === "createRequire" && isModuleNamespaceReference(member.target, scope); +} + +function isRequireReference(node: ts.Expression, scope: LexicalScope): boolean { + const expression = unwrapExpression(node); + if (ts.isIdentifier(expression)) { + return resolveBinding(scope, expression.text)?.kind === "require"; + } + return ts.isCallExpression(expression) && isCreateRequireReference(expression.expression, scope); +} + +function isPathReference(node: ts.Expression, scope: LexicalScope): boolean { + const expression = unwrapExpression(node); + if (ts.isIdentifier(expression)) { + return resolveBinding(scope, expression.text)?.kind === "path"; + } + return ( + ts.isCallExpression(expression) && + isRequireReference(expression.expression, scope) && + ["path", "node:path"].includes(staticString(expression.arguments[0], scope) ?? "") + ); +} + +function pathBuilderMethod( + node: ts.Expression, + scope: LexicalScope, +): "join" | "resolve" | undefined { + const expression = unwrapExpression(node); + if (ts.isIdentifier(expression)) { + const binding = resolveBinding(scope, expression.text); + return binding?.kind === "path-builder" ? binding.method : undefined; + } + const member = accessedMember(expression, scope); + if ( + (member?.name === "join" || member?.name === "resolve") && + isPathReference(member.target, scope) + ) { + return member.name; + } + return undefined; +} + +function normalizedPathParts( + method: "join" | "resolve", + args: ts.NodeArray, + scope: LexicalScope, +): Array { + const parts: Array = []; + for (const argument of args) { + const value = staticString(argument, scope); + if (value === undefined) { + parts.push(null); + continue; + } + const normalizedValue = value.replaceAll("\\", "/"); + if (method === "resolve" && normalizedValue.startsWith("/")) parts.length = 0; + for (const part of normalizedValue.split("/")) { + if (!part || part === ".") continue; + if (part === "..") { + const previous = parts.at(-1); + if (previous !== undefined && previous !== null && previous !== "..") parts.pop(); + else parts.push(part); + } else { + parts.push(part); + } + } + } + return parts; +} + +function compiledPathBuilderTarget( + node: ts.CallExpression, + scope: LexicalScope, +): string | undefined { + const method = pathBuilderMethod(node.expression, scope); + if (!method) return undefined; + const parts = normalizedPathParts(method, node.arguments, scope); + for (let index = 0; index < parts.length; index += 1) { + if (parts[index] !== "dist") continue; + const compiledTarget = parts[index + 1]; + if (compiledTarget === "lib" || compiledTarget === "commands") { + return `dist/${compiledTarget}`; + } + if (compiledTarget === "nemoclaw.js") return "dist/nemoclaw.js"; + } + return undefined; +} + +function isStringRawTag(node: ts.Expression, scope: LexicalScope): boolean { + const member = accessedMember(node, scope); + const target = member && unwrapExpression(member.target); + return ( + member?.name === "raw" && + !!target && + ts.isIdentifier(target) && + resolveBinding(scope, target.text)?.kind === "string-constructor" + ); +} + +function stringRawSubstitution(node: ts.Expression, scope: LexicalScope): string { + const value = staticString(node, scope); + if (value !== undefined) return value; + + const expression = unwrapExpression(node); + if (ts.isCallExpression(expression)) { + const member = accessedMember(expression.expression, scope); + const target = member && unwrapExpression(member.target); + if ( + member?.name === "stringify" && + target && + ts.isIdentifier(target) && + resolveBinding(scope, target.text)?.kind === "json-object" + ) { + const argument = staticString(expression.arguments[0], scope); + if (argument !== undefined) return JSON.stringify(argument); + } + } + + return "undefined"; +} + +function templateSource(node: ts.TemplateLiteral, scope: LexicalScope): string { + if (ts.isNoSubstitutionTemplateLiteral(node)) return node.text; + return node.templateSpans.reduce( + (source, span) => + `${source}${stringRawSubstitution(span.expression, scope)}${span.literal.text}`, + node.head.text, + ); +} + export function findCompiledInternalViolations(file: string, source: string): Violation[] { const sourceFile = ts.createSourceFile( file, @@ -70,73 +285,400 @@ export function findCompiledInternalViolations(file: string, source: string): Vi ); const violations: Violation[] = []; - function add(node: ts.Node, detail: string): void { - const position = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)); - violations.push({ file, line: position.line + 1, detail }); - } + function scan(scannedFile: ts.SourceFile, lineOffset = 0, scanTemplates = true): void { + function createScope(parent: LexicalScope | null, kind: ScopeKind): LexicalScope { + return { bindings: new Map(), kind, parent }; + } - function checkSpecifier(node: ts.Node, specifier: string): void { - if (isCompiledInternalSpecifier(specifier)) { - add(node, `imports compiled CLI internals from ${JSON.stringify(specifier)}`); + function declareBinding(scope: LexicalScope, name: string, binding: Binding): void { + scope.bindings.set(name, binding); } - } - function visit(node: ts.Node): void { - if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) { - checkSpecifier(node.moduleSpecifier, node.moduleSpecifier.text); - } else if ( - ts.isExportDeclaration(node) && - node.moduleSpecifier && - ts.isStringLiteralLike(node.moduleSpecifier) - ) { - checkSpecifier(node.moduleSpecifier, node.moduleSpecifier.text); - } else if (ts.isCallExpression(node)) { - const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require"; - const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword; - const isRequireResolve = - ts.isPropertyAccessExpression(node.expression) && - ts.isIdentifier(node.expression.expression) && - node.expression.expression.text === "require" && - node.expression.name.text === "resolve"; - const firstArgument = node.arguments[0]; + function declareBindingName(scope: LexicalScope, name: ts.BindingName): void { + if (ts.isIdentifier(name)) { + declareBinding(scope, name.text, { kind: "unknown" }); + return; + } + for (const element of name.elements) { + if (!ts.isOmittedExpression(element)) declareBindingName(scope, element.name); + } + } + + function isBlockScoped(declaration: ts.VariableDeclaration): boolean { + return ( + ts.isVariableDeclarationList(declaration.parent) && + (declaration.parent.flags & ts.NodeFlags.BlockScoped) !== 0 + ); + } + + function collectVarBindings(node: ts.Node, scope: LexicalScope, root: ts.Node): void { if ( - (isRequire || isDynamicImport || isRequireResolve) && - firstArgument && - ts.isStringLiteralLike(firstArgument) + node !== root && + (ts.isFunctionLike(node) || + ts.isModuleBlock(node) || + ts.isClassStaticBlockDeclaration(node)) ) { - checkSpecifier(firstArgument, firstArgument.text); + return; } + if (ts.isVariableDeclaration(node) && !isBlockScoped(node)) { + declareBindingName(scope, node.name); + } + ts.forEachChild(node, (child) => collectVarBindings(child, scope, root)); + } - const isPathBuilder = - ts.isPropertyAccessExpression(node.expression) && - ts.isIdentifier(node.expression.expression) && - node.expression.expression.text === "path" && - ["join", "resolve"].includes(node.expression.name.text); - if (isPathBuilder) { - const parts = node.arguments.map((argument) => - ts.isStringLiteralLike(argument) ? argument.text : null, + function declareImportBindings(node: ts.ImportDeclaration, scope: LexicalScope): void { + if (!node.importClause || !ts.isStringLiteralLike(node.moduleSpecifier)) return; + const moduleName = node.moduleSpecifier.text; + const isModuleImport = moduleName === "module" || moduleName === "node:module"; + const isPathImport = moduleName === "path" || moduleName === "node:path"; + const { importClause } = node; + if (importClause.name) { + declareBinding( + scope, + importClause.name.text, + isPathImport + ? { kind: "path" } + : isModuleImport + ? { kind: "module-namespace" } + : { kind: "unknown" }, + ); + } + const namedBindings = importClause.namedBindings; + if (namedBindings && ts.isNamespaceImport(namedBindings)) { + declareBinding( + scope, + namedBindings.name.text, + isPathImport + ? { kind: "path" } + : isModuleImport + ? { kind: "module-namespace" } + : { kind: "unknown" }, ); - const distIndex = parts.indexOf("dist"); - const compiledTarget = distIndex >= 0 ? parts[distIndex + 1] : null; - if (compiledTarget === "lib" || compiledTarget === "commands") { - add(node, `constructs a path into dist/${compiledTarget}`); - } else if (distIndex >= 0 && compiledTarget === "nemoclaw.js") { + } else if (namedBindings) { + for (const element of namedBindings.elements) { + const importedName = element.propertyName?.text ?? element.name.text; + declareBinding( + scope, + element.name.text, + isModuleImport && importedName === "createRequire" + ? { kind: "create-require" } + : isPathImport && (importedName === "join" || importedName === "resolve") + ? { kind: "path-builder", method: importedName } + : { kind: "unknown" }, + ); + } + } + } + + function externalModuleSpecifier( + node: ts.ImportEqualsDeclaration, + ): ts.StringLiteralLike | undefined { + const expression = ts.isExternalModuleReference(node.moduleReference) + ? node.moduleReference.expression + : undefined; + return expression && ts.isStringLiteralLike(expression) ? expression : undefined; + } + + function predeclareStatementBindings( + statements: ts.NodeArray, + scope: LexicalScope, + ): void { + for (const statement of statements) { + if (ts.isVariableStatement(statement)) { + if ((statement.declarationList.flags & ts.NodeFlags.BlockScoped) !== 0) { + for (const declaration of statement.declarationList.declarations) { + declareBindingName(scope, declaration.name); + } + } + } else if ( + (ts.isClassDeclaration(statement) || + ts.isEnumDeclaration(statement) || + ts.isFunctionDeclaration(statement)) && + statement.name + ) { + declareBinding(scope, statement.name.text, { kind: "unknown" }); + } else if (ts.isModuleDeclaration(statement) && ts.isIdentifier(statement.name)) { + declareBinding(scope, statement.name.text, { kind: "unknown" }); + } else if (ts.isImportDeclaration(statement)) { + declareImportBindings(statement, scope); + } else if (ts.isImportEqualsDeclaration(statement)) { + const moduleName = externalModuleSpecifier(statement)?.text ?? ""; + declareBinding( + scope, + statement.name.text, + moduleName === "path" || moduleName === "node:path" + ? { kind: "path" } + : moduleName === "module" || moduleName === "node:module" + ? { kind: "module-namespace" } + : { kind: "unknown" }, + ); + } + } + } + + function constDeclarationsInStatements( + statements: ts.NodeArray, + ): ts.VariableDeclaration[] { + return statements.flatMap((statement) => + ts.isVariableStatement(statement) && + (statement.declarationList.flags & ts.NodeFlags.Const) !== 0 + ? [...statement.declarationList.declarations] + : [], + ); + } + + function constDeclarationsForScope(node: ts.Node): ts.VariableDeclaration[] { + if (ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node)) { + return constDeclarationsInStatements(node.statements); + } + if (ts.isCaseBlock(node)) { + return node.clauses.flatMap((clause) => constDeclarationsInStatements(clause.statements)); + } + if ( + (ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node)) && + node.initializer && + ts.isVariableDeclarationList(node.initializer) && + (node.initializer.flags & ts.NodeFlags.Const) !== 0 + ) { + return [...node.initializer.declarations]; + } + return []; + } + + function inferConstBindings(node: ts.Node, scope: LexicalScope): void { + const declarations = constDeclarationsForScope(node); + for (let pass = 0; pass <= declarations.length; pass += 1) { + let changed = false; + for (const declaration of declarations) { + for (const [name, inferred] of inferredConstBindings(declaration, scope)) { + if (inferred.kind === "unknown") continue; + const current = scope.bindings.get(name); + if ( + current?.kind !== inferred.kind || + (current.kind === "static-string" && + inferred.kind === "static-string" && + current.value !== inferred.value) + ) { + declareBinding(scope, name, inferred); + changed = true; + } + } + } + if (!changed) break; + } + } + + function predeclareScope(node: ts.Node, scope: LexicalScope): void { + if (ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node)) { + predeclareStatementBindings(node.statements, scope); + } + if (ts.isCaseBlock(node)) { + for (const clause of node.clauses) { + predeclareStatementBindings(clause.statements, scope); + } + } + if (ts.isFunctionLike(node)) { + for (const parameter of node.parameters) declareBindingName(scope, parameter.name); + if (ts.isFunctionExpression(node) && node.name) { + declareBinding(scope, node.name.text, { kind: "unknown" }); + } + } + if (ts.isClassExpression(node) && node.name) { + declareBinding(scope, node.name.text, { kind: "unknown" }); + } + if (ts.isCatchClause(node) && node.variableDeclaration) { + declareBindingName(scope, node.variableDeclaration.name); + } + if ( + (ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node)) && + node.initializer && + ts.isVariableDeclarationList(node.initializer) && + (node.initializer.flags & ts.NodeFlags.BlockScoped) !== 0 + ) { + for (const declaration of node.initializer.declarations) { + declareBindingName(scope, declaration.name); + } + } + if (scope.kind === "root" || scope.kind === "function") { + collectVarBindings(node, scope, node); + } + inferConstBindings(node, scope); + } + + function scopeKind(node: ts.Node): ScopeKind | null { + if ( + ts.isFunctionLike(node) || + ts.isModuleBlock(node) || + ts.isClassStaticBlockDeclaration(node) + ) { + return "function"; + } + if ( + ts.isBlock(node) || + ts.isCatchClause(node) || + ts.isForStatement(node) || + ts.isForInStatement(node) || + ts.isForOfStatement(node) || + ts.isCaseBlock(node) || + ts.isClassExpression(node) + ) { + return "block"; + } + return null; + } + + function inferredConstBinding( + declaration: ts.VariableDeclaration, + scope: LexicalScope, + ): Binding { + if ( + !ts.isIdentifier(declaration.name) || + !declaration.initializer || + !ts.isVariableDeclarationList(declaration.parent) || + (declaration.parent.flags & ts.NodeFlags.Const) === 0 + ) { + return { kind: "unknown" }; + } + const initializer = unwrapExpression(declaration.initializer); + const value = staticString(initializer, scope); + if (value !== undefined) return { kind: "static-string", value }; + if (ts.isIdentifier(initializer)) { + return resolveBinding(scope, initializer.text) ?? { kind: "unknown" }; + } + if (isModuleNamespaceReference(initializer, scope)) return { kind: "module-namespace" }; + if (isPathReference(initializer, scope)) return { kind: "path" }; + if (isCreateRequireReference(initializer, scope)) return { kind: "create-require" }; + const method = pathBuilderMethod(initializer, scope); + if (method) return { kind: "path-builder", method }; + if (isRequireReference(initializer, scope)) return { kind: "require" }; + return { kind: "unknown" }; + } + + function inferredConstBindings( + declaration: ts.VariableDeclaration, + scope: LexicalScope, + ): Array<[string, Binding]> { + if (ts.isIdentifier(declaration.name)) { + return [[declaration.name.text, inferredConstBinding(declaration, scope)]]; + } + if (!ts.isObjectBindingPattern(declaration.name) || !declaration.initializer) { + return []; + } + const initializer = unwrapExpression(declaration.initializer); + const isModuleNamespace = isModuleNamespaceReference(initializer, scope); + const isPathNamespace = isPathReference(initializer, scope); + if (!isModuleNamespace && !isPathNamespace) return []; + + return declaration.name.elements.flatMap((element): Array<[string, Binding]> => { + if (element.dotDotDotToken || !ts.isIdentifier(element.name)) return []; + const importedName = element.propertyName ?? element.name; + if (!(ts.isIdentifier(importedName) || ts.isStringLiteralLike(importedName))) { + return []; + } + if (isModuleNamespace && importedName.text === "createRequire") { + return [[element.name.text, { kind: "create-require" }]]; + } + if (isPathNamespace && (importedName.text === "join" || importedName.text === "resolve")) { + return [[element.name.text, { kind: "path-builder", method: importedName.text }]]; + } + return []; + }); + } + + function add(node: ts.Node, detail: string): void { + const position = scannedFile.getLineAndCharacterOfPosition(node.getStart(scannedFile)); + violations.push({ file, line: position.line + lineOffset + 1, detail }); + } + + function checkSpecifier(node: ts.Node, specifier: string): void { + if (isCompiledInternalSpecifier(specifier)) { + add(node, `imports compiled CLI internals from ${JSON.stringify(specifier)}`); + } + } + + function visit(node: ts.Node, parentScope: LexicalScope): void { + const nestedKind = node === scannedFile ? null : scopeKind(node); + const scope = nestedKind ? createScope(parentScope, nestedKind) : parentScope; + if (nestedKind) predeclareScope(node, scope); + + if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) { + checkSpecifier(node.moduleSpecifier, node.moduleSpecifier.text); + } else if (ts.isImportEqualsDeclaration(node)) { + const specifier = externalModuleSpecifier(node); + if (specifier) checkSpecifier(specifier, specifier.text); + } else if ( + ts.isExportDeclaration(node) && + node.moduleSpecifier && + ts.isStringLiteralLike(node.moduleSpecifier) + ) { + checkSpecifier(node.moduleSpecifier, node.moduleSpecifier.text); + } else if (ts.isImportTypeNode(node)) { + const argument = node.argument; + if (ts.isLiteralTypeNode(argument) && ts.isStringLiteralLike(argument.literal)) { + checkSpecifier(argument.literal, argument.literal.text); + } + } else if (ts.isCallExpression(node)) { + const isRequire = isRequireReference(node.expression, scope); + const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword; + const isRequireResolve = + ts.isPropertyAccessExpression(node.expression) && + isRequireReference(node.expression.expression, scope) && + node.expression.name.text === "resolve"; + const firstArgument = node.arguments[0]; + const specifier = staticString(firstArgument, scope); + if ((isRequire || isDynamicImport || isRequireResolve) && firstArgument && specifier) { + checkSpecifier(firstArgument, specifier); + } + + const pathTarget = compiledPathBuilderTarget(node, scope); + if (pathTarget === "dist/nemoclaw.js") { add(node, "constructs a path to dist/nemoclaw.js"); + } else if (pathTarget) { + add(node, `constructs a path into ${pathTarget}`); } + } else if ( + scanTemplates && + ts.isTaggedTemplateExpression(node) && + isStringRawTag(node.tag, scope) + ) { + const embeddedSource = ts.createSourceFile( + `${file}.embedded.js`, + templateSource(node.template, scope), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.JS, + ); + const templateLine = scannedFile.getLineAndCharacterOfPosition( + node.template.getStart(scannedFile), + ).line; + scan(embeddedSource, lineOffset + templateLine, false); } + ts.forEachChild(node, (child) => { + let childScope = scope; + if ( + ts.isFunctionLike(node) && + (ts.isDecorator(child) || + (node.name && ts.isComputedPropertyName(node.name) && child === node.name)) + ) { + childScope = parentScope; + } else if (ts.isParameter(node) && ts.isDecorator(child)) { + childScope = parentScope.parent ?? parentScope; + } + visit(child, childScope); + }); } - ts.forEachChild(node, visit); - } - visit(sourceFile); - for (const match of source.matchAll(/require\([^\n)]*(?:\.\/|\.\.\/)dist\/(?:lib|commands)\//g)) { - const position = sourceFile.getLineAndCharacterOfPosition(match.index); - violations.push({ - file, - line: position.line + 1, - detail: "embeds a compiled-internal require in generated test code", - }); + const rootScope = createScope(null, "root"); + declareBinding(rootScope, "String", { kind: "string-constructor" }); + declareBinding(rootScope, "JSON", { kind: "json-object" }); + declareBinding(rootScope, "createRequire", { kind: "create-require" }); + declareBinding(rootScope, "path", { kind: "path" }); + declareBinding(rootScope, "require", { kind: "require" }); + predeclareScope(scannedFile, rootScope); + visit(scannedFile, rootScope); } + + scan(sourceFile); return violations.filter( (violation, index, all) => all.findIndex( diff --git a/scripts/gateway-control.sh b/scripts/gateway-control.sh new file mode 100755 index 00000000000..1fd490f4e6d --- /dev/null +++ b/scripts/gateway-control.sh @@ -0,0 +1,128 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -eu + +# This helper is entered directly by a host-side privileged container exec, so +# it must not inherit command resolution from the container environment. Use a +# fixed interpreter and trusted system PATH before invoking any external tool. +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +INSTALLED_CONTROL_HELPER="/usr/local/bin/nemoclaw-gateway-control" +if [ "$0" = "$INSTALLED_CONTROL_HELPER" ]; then + CONTROL_PROC_ROOT="/proc" + CONTROL_MANAGED_HELPER="/usr/local/lib/nemoclaw/managed-gateway-control.py" + CONTROL_CALLER_UID="$(id -u)" +else + # Source-checkout behavior tests use isolated fixtures. The installed helper + # ignores these seams and always binds to the fixed procfs and helper paths. + CONTROL_PROC_ROOT="${NEMOCLAW_TEST_GATEWAY_CONTROL_PROC_ROOT:-/proc}" + CONTROL_MANAGED_HELPER="${NEMOCLAW_TEST_MANAGED_GATEWAY_CONTROL_HELPER:-/usr/local/lib/nemoclaw/managed-gateway-control.py}" + CONTROL_CALLER_UID="${NEMOCLAW_TEST_GATEWAY_CONTROL_CALLER_UID:-$(id -u)}" +fi + +CONTROL_DIR="${NEMOCLAW_GATEWAY_CONTROL_DIR:-/run/nemoclaw/gateway-control}" +REQUEST_FILE="${CONTROL_DIR}/request" +STATUS_FILE="${CONTROL_DIR}/status" +LOCK_DIR="${CONTROL_DIR}/submit.lock" + +fail() { + printf '%s\n' "$1" >&2 + exit 1 +} + +[ "$#" -eq 2 ] || fail "SUPERVISOR_INVALID_REQUEST" +ACTION="$1" +NONCE="$2" +case "$ACTION" in + restart | recover | probe) ;; + *) fail "SUPERVISOR_INVALID_ACTION" ;; +esac +case "$NONCE" in + *[!0-9a-f]* | '') fail "SUPERVISOR_INVALID_NONCE" ;; +esac +[ "${#NONCE}" -eq 64 ] || fail "SUPERVISOR_INVALID_NONCE" +[ "$CONTROL_CALLER_UID" -eq 0 ] || fail "PRIVILEGED_CONTROL_UNAVAILABLE" + +PID1_CMDLINE="$(tr '\0' ' ' <"${CONTROL_PROC_ROOT}/1/cmdline" 2>/dev/null || true)" +PID1_ARGV0="$(tr '\0' '\n' <"${CONTROL_PROC_ROOT}/1/cmdline" 2>/dev/null | sed -n '1p' || true)" +if [ "$PID1_ARGV0" = "/opt/openshell/bin/openshell-sandbox" ]; then + [ -x "$CONTROL_MANAGED_HELPER" ] || fail "SUPERVISOR_REBUILD_REQUIRED" + # Isolated mode ignores Python startup hooks, user-site packages, and + # PYTHON* environment variables before the root helper imports anything. + exec python3 -I "$CONTROL_MANAGED_HELPER" "$ACTION" "$NONCE" +fi +case "$PID1_CMDLINE" in + *nemoclaw-start*) ;; + *) fail "SUPERVISOR_UNAVAILABLE" ;; +esac + +[ -d "$CONTROL_DIR" ] || fail "SUPERVISOR_REBUILD_REQUIRED" +[ "$(stat -c '%U:%G %a' "$CONTROL_DIR" 2>/dev/null || true)" = "root:root 700" ] \ + || fail "SUPERVISOR_UNSAFE_CONTROL_DIR" +mkdir "$LOCK_DIR" 2>/dev/null || fail "SUPERVISOR_BUSY" +# shellcheck disable=SC2317,SC2329 # invoked by the trap below +cleanup() { + [ -z "${REQUEST_TMP:-}" ] || rm -f "$REQUEST_TMP" 2>/dev/null || true + rmdir "$LOCK_DIR" 2>/dev/null || true +} +trap cleanup EXIT +trap 'exit 1' INT TERM + +[ ! -e "$REQUEST_FILE" ] || fail "SUPERVISOR_BUSY" +umask 077 +REQUEST_TMP="${REQUEST_FILE}.tmp.$$" +printf 'v1 %s %s\n' "$NONCE" "$ACTION" >"$REQUEST_TMP" +chmod 600 "$REQUEST_TMP" +# Do not let cancellation strand an unsignalled request between publication +# and the PID 1 wake-up. Signals are ignored only across this tiny critical +# section, then normal abort handling resumes. +trap '' INT TERM +mv -f "$REQUEST_TMP" "$REQUEST_FILE" +if ! kill -USR1 1 2>/dev/null; then + trap 'exit 1' INT TERM + rm -f "$REQUEST_FILE" + fail "SUPERVISOR_SIGNAL_FAILED" +fi +trap 'exit 1' INT TERM + +# Hermes can legitimately need 90 seconds to become healthy and then up to 30 +# seconds to restore a stopped dashboard bridge. Keep the helper above that +# combined budget; the host command applies a slightly larger outer timeout. +for _ in $(seq 1 900); do + if [ -r "$STATUS_FILE" ]; then + IFS=' ' read -r VERSION STATUS_NONCE STATE DETAIL OLD_PID NEW_PID <"$STATUS_FILE" || true + if [ "$VERSION" = "v1" ] && [ "$STATUS_NONCE" = "$NONCE" ]; then + case "$STATE" in + accepted) ;; + complete) + case "$DETAIL" in + ok | already-running) + printf 'v1 %s complete %s %s %s\n' "$NONCE" "$DETAIL" "$OLD_PID" "$NEW_PID" + printf 'GATEWAY_PID=%s\n' "$NEW_PID" + exit 0 + ;; + *) fail "SUPERVISOR_INVALID_STATUS" ;; + esac + ;; + failed) + printf 'v1 %s failed %s %s %s\n' "$NONCE" "$DETAIL" "$OLD_PID" "$NEW_PID" >&2 + case "$DETAIL" in + validator-missing) fail "SECRET_BOUNDARY_VALIDATOR_MISSING" ;; + secret-boundary-refusal) fail "SECRET_BOUNDARY_REFUSED" ;; + unsafe-config) fail "GATEWAY_UNSAFE_CONFIG_PATH" ;; + hash-mismatch) fail "GATEWAY_CONFIG_HASH_MISMATCH" ;; + preload-missing) fail "GATEWAY_GUARDS_MISSING" ;; + health-timeout) fail "GATEWAY_HEALTH_TIMEOUT" ;; + *) fail "GATEWAY_FAILED" ;; + esac + ;; + *) fail "SUPERVISOR_INVALID_STATUS" ;; + esac + fi + fi + sleep 0.2 +done + +fail "SUPERVISOR_TIMEOUT" diff --git a/scripts/lib/gateway-supervisor.sh b/scripts/lib/gateway-supervisor.sh new file mode 100755 index 00000000000..a62a077893a --- /dev/null +++ b/scripts/lib/gateway-supervisor.sh @@ -0,0 +1,308 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Shared PID 1 control primitives for host-requested gateway lifecycle actions. +# The request directory is root-only. Requests are written by the host through +# the registry-scoped privileged Docker exec path; sandbox processes cannot +# submit or alter them. + +NEMOCLAW_GATEWAY_CONTROL_DIR="${NEMOCLAW_GATEWAY_CONTROL_DIR:-/run/nemoclaw/gateway-control}" +NEMOCLAW_GATEWAY_CONTROL_REQUEST="${NEMOCLAW_GATEWAY_CONTROL_DIR}/request" +NEMOCLAW_GATEWAY_CONTROL_STATUS="${NEMOCLAW_GATEWAY_CONTROL_DIR}/status" + +GATEWAY_CONTROL_SIGNAL_PENDING=0 +GATEWAY_CONTROL_NONCE="" +GATEWAY_CONTROL_ACTION="" + +gateway_control_atomic_status() { + local nonce="$1" + shift + local tmp="${NEMOCLAW_GATEWAY_CONTROL_STATUS}.tmp.$$" + umask 077 + printf 'v1 %s %s\n' "$nonce" "$*" >"$tmp" || return 1 + chmod 600 "$tmp" || { + rm -f "$tmp" + return 1 + } + mv -f "$tmp" "$NEMOCLAW_GATEWAY_CONTROL_STATUS" +} + +gateway_control_init() { + [ "$(id -u)" -eq 0 ] || return 1 + # Install the handler before publishing the control directory. Otherwise a + # helper can observe the directory in the few instructions before the caller + # installs its trap and SIGUSR1 would take PID 1's default terminate action. + gateway_control_install_signal_trap + install -d -o root -g root -m 700 "$NEMOCLAW_GATEWAY_CONTROL_DIR" || return 1 + rm -f "$NEMOCLAW_GATEWAY_CONTROL_REQUEST" "$NEMOCLAW_GATEWAY_CONTROL_STATUS" +} + +gateway_control_mark_signal() { + GATEWAY_CONTROL_SIGNAL_PENDING=1 +} + +gateway_control_install_signal_trap() { + trap gateway_control_mark_signal USR1 +} + +gateway_control_take_request() { + local version nonce action extra + [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 1 ] || return 1 + GATEWAY_CONTROL_SIGNAL_PENDING=0 + + if ! IFS=' ' read -r version nonce action extra <"$NEMOCLAW_GATEWAY_CONTROL_REQUEST"; then + return 1 + fi + [ "$version" = "v1" ] || return 1 + case "$nonce" in + *[!0-9a-f]* | '') return 1 ;; + esac + [ "${#nonce}" -eq 64 ] || return 1 + case "$action" in + restart | recover | probe) ;; + *) return 1 ;; + esac + [ -z "${extra:-}" ] || return 1 + + GATEWAY_CONTROL_NONCE="$nonce" + # shellcheck disable=SC2034 # consumed by the sourcing entrypoint + GATEWAY_CONTROL_ACTION="$action" + gateway_control_atomic_status "$nonce" accepted +} + +gateway_control_complete() { + local result="$1" + local old_pid="$2" + local new_pid="$3" + gateway_control_atomic_status "$GATEWAY_CONTROL_NONCE" "complete ${result} ${old_pid} ${new_pid}" + rm -f "$NEMOCLAW_GATEWAY_CONTROL_REQUEST" +} + +gateway_control_fail() { + local code="$1" + local old_pid="${2:-0}" + case "$code" in + validator-missing | secret-boundary-refusal | unsafe-config | hash-mismatch | preload-missing | launch-failed | health-timeout | internal) ;; + *) code=internal ;; + esac + gateway_control_atomic_status "$GATEWAY_CONTROL_NONCE" "failed ${code} ${old_pid} 0" + rm -f "$NEMOCLAW_GATEWAY_CONTROL_REQUEST" +} + +gateway_control_pid_is_live() { + local pid="$1" + local state + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + kill -0 "$pid" 2>/dev/null || return 1 + # kill -0 succeeds for an unreaped zombie. Do not record or trust a process + # that can no longer own a listener or handle a termination signal. + if command -v ps >/dev/null 2>&1; then + state="$(ps -o stat= -p "$pid" 2>/dev/null | awk 'NR == 1 { print $1 }')" + [ -n "$state" ] || return 1 + case "$state" in + Z*) return 1 ;; + esac + elif [ -r "/proc/${pid}/stat" ]; then + state="$(sed -E 's/^[0-9]+ \(.*\) ([^ ]).*/\1/' "/proc/${pid}/stat" 2>/dev/null || true)" + [ "$state" != "Z" ] || return 1 + fi + return 0 +} + +gateway_control_proc_root() { + if [ "${_NEMOCLAW_PROC_ROOT+x}" = x ]; then + printf '%s\n' "$_NEMOCLAW_PROC_ROOT" + elif [ "${_HERMES_PROC_ROOT+x}" = x ]; then + printf '%s\n' "$_HERMES_PROC_ROOT" + else + printf '/proc\n' + fi +} + +gateway_control_proc_root_is_explicit() { + [ "${_NEMOCLAW_PROC_ROOT+x}" = x ] || [ "${_HERMES_PROC_ROOT+x}" = x ] +} + +# Print the process-start identity used by both supervisors. Linux containers +# use /proc//stat field 22. The ps fallback only supports non-Linux +# developer hosts; an explicit proc-root seam must never inspect the host +# namespace instead. +gateway_control_pid_start_identity() { + local pid="$1" + local proc_root stat_line stat_suffix started + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + proc_root="$(gateway_control_proc_root)" || return 1 + if [ -r "${proc_root}/${pid}/stat" ]; then + IFS= read -r stat_line <"${proc_root}/${pid}/stat" || return 1 + stat_suffix="${stat_line##*) }" + [ "$stat_suffix" != "$stat_line" ] || return 1 + # shellcheck disable=SC2086 # intentional field split of proc stat suffix + set -- $stat_suffix + [ "$#" -ge 20 ] || return 1 + case "${20}" in + '' | *[!0-9]*) return 1 ;; + esac + printf '%s\n' "${20}" + return 0 + fi + gateway_control_proc_root_is_explicit && return 1 + command -v ps >/dev/null 2>&1 || return 1 + started="$(LC_ALL=C ps -o lstart= -p "$pid" 2>/dev/null | awk 'NR == 1 { sub(/^[[:space:]]+/, ""); sub(/[[:space:]]+$/, ""); print; exit }')" + [ -n "$started" ] || return 1 + printf 'ps:%s\n' "${started//[[:space:]]/_}" +} + +gateway_control_pid_state() { + local pid="$1" + local proc_root stat_line stat_suffix state + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + proc_root="$(gateway_control_proc_root)" || return 1 + if [ -r "${proc_root}/${pid}/stat" ]; then + IFS= read -r stat_line <"${proc_root}/${pid}/stat" || return 1 + stat_suffix="${stat_line##*) }" + [ "$stat_suffix" != "$stat_line" ] || return 1 + # shellcheck disable=SC2086 # intentional field split of proc stat suffix + set -- $stat_suffix + [ "$#" -ge 1 ] || return 1 + state="$1" + else + gateway_control_proc_root_is_explicit && return 1 + command -v ps >/dev/null 2>&1 || return 1 + state="$(ps -o stat= -p "$pid" 2>/dev/null | awk 'NR == 1 { print $1; exit }')" + fi + [ -n "$state" ] || return 1 + printf '%s\n' "$state" +} + +gateway_control_pid_matches_start_identity() { + local pid="$1" + local expected_start_identity="$2" + local current_start_identity + [ -n "$expected_start_identity" ] || return 1 + current_start_identity="$(gateway_control_pid_start_identity "$pid")" || return 1 + [ "$current_start_identity" = "$expected_start_identity" ] +} + +gateway_control_pid_owns_tcp_listener() { + local pid="$1" + local port="$2" + local proc_root="${3:-/proc}" + local port_hex listener_inodes inode fd_path target listener_inode + case "$port" in + '' | *[!0-9]*) return 1 ;; + esac + [ "$port" -ge 1 ] && [ "$port" -le 65535 ] || return 1 + gateway_control_pid_is_live "$pid" || return 1 + + # Match the listener socket inode to an fd owned by the exact tracked child. + # Callers cross a UID boundary before invoking this helper when PID 1 cannot + # inspect the gateway/dashboard fd directory after dropping CAP_SYS_PTRACE + # and CAP_DAC_OVERRIDE. + port_hex="$(printf '%04X' "$port")" + listener_inodes="$(awk -v expected_port="$port_hex" ' + { + split($2, local_address, ":") + if (toupper(local_address[2]) == expected_port && $4 == "0A") { + print $10 + } + } + ' "${proc_root}/net/tcp" "${proc_root}/net/tcp6" 2>/dev/null || true)" + [ -n "$listener_inodes" ] || return 1 + + for fd_path in "${proc_root}/${pid}"/fd/*; do + [ -L "$fd_path" ] || continue + target="$(readlink "$fd_path" 2>/dev/null || true)" + case "$target" in + 'socket:['*']') + inode="${target#socket:[}" + inode="${inode%]}" + ;; + *) continue ;; + esac + while IFS= read -r listener_inode; do + [ "$inode" = "$listener_inode" ] && return 0 + done </dev/null || true + fi + return 0 + ;; + esac + + # Revalidate immediately before every signal. A numeric PID alone is never + # authority to terminate a process. + gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity" || return 0 + kill -TERM "$pid" 2>/dev/null || true + while [ "$attempts" -lt 50 ]; do + gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity" || return 0 + state="$(gateway_control_pid_state "$pid")" || return 0 + case "$state" in + Z*) + if gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity"; then + wait "$pid" 2>/dev/null || true + fi + return 0 + ;; + esac + sleep 0.1 + attempts=$((attempts + 1)) + done + gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity" || return 0 + state="$(gateway_control_pid_state "$pid")" || return 0 + case "$state" in + Z*) + if gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity"; then + wait "$pid" 2>/dev/null || true + fi + return 0 + ;; + esac + gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity" || return 0 + kill -KILL "$pid" 2>/dev/null || true + + attempts=0 + while [ "$attempts" -lt 50 ]; do + gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity" || return 0 + state="$(gateway_control_pid_state "$pid")" || return 0 + case "$state" in + Z*) + if gateway_control_pid_matches_start_identity "$pid" "$expected_start_identity"; then + wait "$pid" 2>/dev/null || true + fi + return 0 + ;; + esac + sleep 0.1 + attempts=$((attempts + 1)) + done + return 1 +} diff --git a/scripts/managed-gateway-control.py b/scripts/managed-gateway-control.py new file mode 100755 index 00000000000..72bdee38296 --- /dev/null +++ b/scripts/managed-gateway-control.py @@ -0,0 +1,1445 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Root-only lifecycle control for an OpenShell-managed gateway. + +OpenShell is container PID 1 in its managed topology and starts +``nemoclaw-start`` as the unprivileged ``sandbox`` user. The shell entrypoint +still owns and reaps the gateway child, so this helper never launches a second +gateway and never trusts a status file writable by that user. Instead it: + +* verifies a stable OpenShell -> nemoclaw-start -> gateway process tree; +* signals the already-proven gateway through a pidfd; +* waits for the entrypoint's normal respawn loop; and +* independently proves the replacement process, listener, and HTTP health. + +The host enters this helper through registry-scoped ``docker exec --user root``. +The installed copy is root-owned and mode 0500, which is the host request +authentication boundary. No same-UID request or completion channel exists. +Because the managed supervisor, gateway, and agent all share the ``sandbox`` +UID, this process-shape proof prevents PID reuse and accidental cross-process +signalling but cannot establish provenance against a malicious same-UID agent. + +Managed non-root startup has no durable root-owned config hash for mutable +configuration. Hermes therefore gets its canonical secret-boundary checks and +strict hash verification whenever the files are in the locked root-owned +posture, but mutable config retains the same trust/TOCTOU limitations as the +managed cold-start path. Do not describe this branch as equivalent to the +root-PID-1 restart seal. + +This helper also cannot manufacture gateway/agent UID isolation: both remain +``sandbox`` processes in the OpenShell-managed topology. It authenticates the +host lifecycle action and prevents PID-reuse signaling, but the same sandbox +UID can already signal its peers. Full isolation requires a root supervisor +that launches the gateway under a distinct UID. + +This compatibility path cannot fix that upstream process topology locally +without replacing OpenShell's PID 1 ownership contract. Remove it when the +minimum supported OpenShell launches a root-owned lifecycle supervisor or a +gateway under a UID distinct from the agent, then migrate both built-in agents +to that source-of-truth boundary. +""" + +from __future__ import annotations + +import errno +import fcntl +import hashlib +import http.client +import importlib.util +import os +import pwd +import re +import select +import signal +import stat +import subprocess +import sys +import time +from dataclasses import dataclass + + +INSTALLED_HELPER_PATH = "/usr/local/lib/nemoclaw/managed-gateway-control.py" +HERMES_GUARD_PATH = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py" +HERMES_BOUNDARY_PATH = ( + "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py" +) +OPENCLAW_GUARD_PATH = "/usr/local/lib/nemoclaw/openclaw-config-guard.py" +OPENSHELL_ARGV0 = b"/opt/openshell/bin/openshell-sandbox" +NEMOCLAW_START_PATH = b"/usr/local/bin/nemoclaw-start" +MAX_PROC_ENTRIES = 32768 +MAX_PROC_FILE_BYTES = 1024 * 1024 +MAX_ENV_BYTES = 4 * 1024 * 1024 +MAX_CONFIG_BYTES = 16 * 1024 * 1024 +MAX_HASH_BYTES = 64 * 1024 +STOP_GRACE_SECONDS = 5.0 +KILL_GRACE_SECONDS = 5.0 +RECOVERY_TIMEOUT_SECONDS = 150.0 +RECOVER_EXISTING_GRACE_SECONDS = 10.0 +POLL_SECONDS = 0.2 +NEMOCLAW_RUNTIME_DIR = "/run/nemoclaw" +NEMOCLAW_RUNTIME_DIR_MODE = 0o711 +EXPECTED_EXIT_MARKER_NAME = "managed-gateway-expected-exit" +EXPECTED_EXIT_LOCK_NAME = "managed-gateway-expected-exit.lock" +NONCE_RE = re.compile(r"[0-9a-f]{64}\Z") +ENV_KEY_RE = re.compile(rb"[A-Za-z_][A-Za-z0-9_]*\Z") +SHA256_RE = re.compile(r"[0-9a-f]{64}\Z") + + +class ControlError(RuntimeError): + """A failure whose code is part of the existing host marker contract.""" + + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +@dataclass(frozen=True) +class ProcessIdentity: + pid: int + start_time: str + parent_pid: int + state: str + uids: tuple[int, int, int, int] + namespace_pid: int + namespace_inode: int | None + cmdline: tuple[bytes, ...] + proc_device: int + proc_inode: int + + def stable_key(self) -> tuple[object, ...]: + return ( + self.pid, + self.start_time, + self.parent_pid, + self.state == "Z", + self.uids, + self.namespace_pid, + self.namespace_inode, + self.cmdline, + self.proc_device, + self.proc_inode, + ) + + +@dataclass(frozen=True) +class AgentSpec: + name: str + port: int + health_path: str = "/health" + readiness_checks: tuple[tuple[int, str], ...] = () + + +@dataclass(frozen=True) +class ExpectedExitLease: + """Pinned authorization marker and root-only controller lock.""" + + directory_fd: int + lock_fd: int + marker_fd: int + name: str + device: int + inode: int + + +def _source_mode() -> bool: + return os.path.abspath(__file__) != INSTALLED_HELPER_PATH + + +def _source_test_mode() -> bool: + return ( + _source_mode() + and os.environ.get("NEMOCLAW_MANAGED_CONTROL_ALLOW_NONROOT_TEST") == "1" + ) + + +def _proc_root() -> str: + if _source_test_mode(): + return os.environ.get("NEMOCLAW_MANAGED_CONTROL_PROC_ROOT", "/proc") + return "/proc" + + +def _system_root() -> str: + if _source_test_mode(): + return os.environ.get("NEMOCLAW_MANAGED_CONTROL_SYSTEM_ROOT", "/") + return "/" + + +def _system_path(path: str) -> str: + root = os.path.abspath(_system_root()) + if root == "/": + return path + return os.path.join(root, path.lstrip("/")) + + +def _require_root() -> None: + allow_source_test = _source_test_mode() + if os.geteuid() != 0 and not allow_source_test: + raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE") + + +def _validate_trusted_regular(path: str, *, exact_mode: int | None = None) -> None: + """Validate a fixed installed file without following its final component.""" + + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + fd = os.open(path, flags) + except OSError as exc: + raise ControlError("SUPERVISOR_REBUILD_REQUIRED") from exc + try: + metadata = os.fstat(fd) + trusted_uid = 0 if not _source_mode() else os.geteuid() + mode = stat.S_IMODE(metadata.st_mode) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != trusted_uid + or metadata.st_nlink != 1 + or mode & 0o022 + or (exact_mode is not None and mode != exact_mode) + ): + raise ControlError("SUPERVISOR_REBUILD_REQUIRED") + finally: + os.close(fd) + + +def _require_installed_helper_trust() -> None: + if not _source_mode(): + _validate_trusted_regular(INSTALLED_HELPER_PATH, exact_mode=0o500) + + +def _trusted_agent_marker(path: str) -> bool: + mapped = _system_path(path) + if not os.path.exists(mapped): + return False + _validate_trusted_regular(mapped) + return True + + +def _detect_agent() -> str: + hermes = _trusted_agent_marker(HERMES_GUARD_PATH) + openclaw = _trusted_agent_marker(OPENCLAW_GUARD_PATH) + if hermes == openclaw: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return "hermes" if hermes else "openclaw" + + +def _open_directory(path: str) -> int: + flags = ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + return os.open(path, flags) + + +def _trusted_runtime_owner() -> tuple[int, int]: + if _source_mode(): + return os.geteuid(), os.getegid() + return 0, 0 + + +def _open_managed_runtime_directory() -> int: + """Open the fixed root-owned runtime directory, creating it if absent.""" + + runtime_dir = _system_path(NEMOCLAW_RUNTIME_DIR) + parent = os.path.dirname(runtime_dir) + name = os.path.basename(runtime_dir) + expected_uid, expected_gid = _trusted_runtime_owner() + parent_fd = _open_directory(parent) + directory_fd = -1 + try: + parent_stat = os.fstat(parent_fd) + if ( + not stat.S_ISDIR(parent_stat.st_mode) + or parent_stat.st_uid != expected_uid + or parent_stat.st_gid != expected_gid + or stat.S_IMODE(parent_stat.st_mode) & 0o022 + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + try: + os.mkdir(name, NEMOCLAW_RUNTIME_DIR_MODE, dir_fd=parent_fd) + except FileExistsError: + # Another root controller may have created the fixed directory; + # the descriptor-relative owner and mode checks below decide trust. + pass + flags = ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + directory_fd = os.open(name, flags, dir_fd=parent_fd) + directory_stat = os.fstat(directory_fd) + if ( + not stat.S_ISDIR(directory_stat.st_mode) + or directory_stat.st_uid != expected_uid + or directory_stat.st_gid != expected_gid + or stat.S_IMODE(directory_stat.st_mode) & 0o022 + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + if stat.S_IMODE(directory_stat.st_mode) != NEMOCLAW_RUNTIME_DIR_MODE: + os.fchmod(directory_fd, NEMOCLAW_RUNTIME_DIR_MODE) + if stat.S_IMODE(os.fstat(directory_fd).st_mode) != NEMOCLAW_RUNTIME_DIR_MODE: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return directory_fd + except Exception: + if directory_fd >= 0: + os.close(directory_fd) + raise + finally: + os.close(parent_fd) + + +def _lease_path_matches( + directory_fd: int, name: str, device: int, inode: int +) -> bool: + try: + metadata = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + except FileNotFoundError: + return False + except OSError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + return metadata.st_dev == device and metadata.st_ino == inode + + +def _unlink_matching_runtime_file( + directory_fd: int, name: str, device: int, inode: int +) -> None: + if _lease_path_matches(directory_fd, name, device, inode): + os.unlink(name, dir_fd=directory_fd) + + +def _validate_runtime_regular( + metadata: os.stat_result, expected_mode: int +) -> None: + expected_uid, expected_gid = _trusted_runtime_owner() + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != expected_uid + or metadata.st_gid != expected_gid + or metadata.st_nlink != 1 + or stat.S_IMODE(metadata.st_mode) != expected_mode + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + + +def _open_expected_exit_lock(directory_fd: int) -> int: + """Acquire the root-only lock that serializes authorization publication.""" + + base_flags = ( + os.O_RDWR + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + lock_fd = -1 + created = False + for _attempt in range(3): + try: + lock_fd = os.open( + EXPECTED_EXIT_LOCK_NAME, + base_flags | os.O_CREAT | os.O_EXCL, + 0o600, + dir_fd=directory_fd, + ) + created = True + break + except FileExistsError: + try: + lock_fd = os.open( + EXPECTED_EXIT_LOCK_NAME, + base_flags, + dir_fd=directory_fd, + ) + break + except FileNotFoundError: + continue + except OSError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + except OSError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + if lock_fd < 0: + raise ControlError("SUPERVISOR_BUSY") + + try: + if created: + os.fchmod(lock_fd, 0o600) + metadata = os.fstat(lock_fd) + _validate_runtime_regular(metadata, 0o600) + if not _lease_path_matches( + directory_fd, + EXPECTED_EXIT_LOCK_NAME, + metadata.st_dev, + metadata.st_ino, + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + try: + fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise ControlError("SUPERVISOR_BUSY") from exc + locked = os.fstat(lock_fd) + _validate_runtime_regular(locked, 0o600) + if ( + locked.st_dev != metadata.st_dev + or locked.st_ino != metadata.st_ino + or not _lease_path_matches( + directory_fd, + EXPECTED_EXIT_LOCK_NAME, + locked.st_dev, + locked.st_ino, + ) + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + return lock_fd + except Exception: + os.close(lock_fd) + raise + + +def _trusted_expected_exit_marker( + directory_fd: int, +) -> tuple[int, os.stat_result] | None: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + marker_fd = os.open(EXPECTED_EXIT_MARKER_NAME, flags, dir_fd=directory_fd) + except FileNotFoundError: + return None + except OSError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + try: + metadata = os.fstat(marker_fd) + _validate_runtime_regular(metadata, 0o444) + return marker_fd, metadata + except Exception: + os.close(marker_fd) + raise + + +def _controller_process_identity(reader: ProcReader) -> ProcessIdentity: + identity = reader.capture(os.getpid()) + expected_uid, _expected_gid = _trusted_runtime_owner() + if identity.state == "Z" or identity.uids != (expected_uid,) * 4: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return identity + + +def _publish_expected_exit_lease( + identity: ProcessIdentity, + controller: ProcessIdentity, +) -> ExpectedExitLease: + """Authorize one exact gateway exit while this root controller is live.""" + + directory_fd = _open_managed_runtime_directory() + lock_fd = -1 + marker_fd = -1 + try: + lock_fd = _open_expected_exit_lock(directory_fd) + existing = _trusted_expected_exit_marker(directory_fd) + if existing is not None: + existing_fd, metadata = existing + try: + _unlink_matching_runtime_file( + directory_fd, + EXPECTED_EXIT_MARKER_NAME, + metadata.st_dev, + metadata.st_ino, + ) + finally: + os.close(existing_fd) + + payload = ( + f"v1 {identity.pid} {identity.start_time} " + f"{controller.pid} {controller.start_time}\n" + ).encode("ascii") + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + try: + marker_fd = os.open( + EXPECTED_EXIT_MARKER_NAME, + flags, + 0o600, + dir_fd=directory_fd, + ) + except FileExistsError as exc: + raise ControlError("SUPERVISOR_BUSY") from exc + offset = 0 + while offset < len(payload): + written = os.write(marker_fd, payload[offset:]) + if written <= 0: + raise ControlError("SUPERVISOR_UNAVAILABLE") + offset += written + os.fchmod(marker_fd, 0o444) + os.fsync(marker_fd) + metadata = os.fstat(marker_fd) + marker_device = metadata.st_dev + marker_inode = metadata.st_ino + _validate_runtime_regular(metadata, 0o444) + if not _lease_path_matches( + directory_fd, + EXPECTED_EXIT_MARKER_NAME, + marker_device, + marker_inode, + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + except Exception: + try: + if marker_fd >= 0: + metadata = os.fstat(marker_fd) + _unlink_matching_runtime_file( + directory_fd, + EXPECTED_EXIT_MARKER_NAME, + metadata.st_dev, + metadata.st_ino, + ) + except (ControlError, OSError): + # Preserve the original publication failure; cleanup is best effort + # and inode matching prevents this path from removing a replacement. + pass + if marker_fd >= 0: + os.close(marker_fd) + if lock_fd >= 0: + os.close(lock_fd) + os.close(directory_fd) + raise + return ExpectedExitLease( + directory_fd=directory_fd, + lock_fd=lock_fd, + marker_fd=marker_fd, + name=EXPECTED_EXIT_MARKER_NAME, + device=marker_device, + inode=marker_inode, + ) + + +def _clear_expected_exit_lease(lease: ExpectedExitLease) -> None: + try: + _unlink_matching_runtime_file( + lease.directory_fd, + lease.name, + lease.device, + lease.inode, + ) + except (ControlError, OSError): + # The exact exited identity cannot recur. Never delete a path that no + # longer names this authorization merely to clean up an orphan marker. + pass + finally: + os.close(lease.marker_fd) + os.close(lease.lock_fd) + os.close(lease.directory_fd) + + +def _open_pid(proc_fd: int, pid: int) -> int: + flags = ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + return os.open(str(pid), flags, dir_fd=proc_fd) + + +def _read_at(directory_fd: int, name: str, limit: int = MAX_PROC_FILE_BYTES) -> bytes: + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) + fd = os.open(name, flags, dir_fd=directory_fd) + try: + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(65536, limit + 1 - total)) + if not chunk: + return b"".join(chunks) + chunks.append(chunk) + total += len(chunk) + if total > limit: + raise ControlError("SUPERVISOR_UNAVAILABLE") + finally: + os.close(fd) + + +def _namespace_inode(pid_fd: int) -> int | None: + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) + try: + fd = os.open("ns/pid", flags, dir_fd=pid_fd) + except OSError: + # OpenShell's Landlock policy can deny namespace symlink traversal even + # when the same caller can descriptor-pin stat/status/cmdline. The two + # captures in ProcReader must agree on unavailability; parent, UID, + # NSpid, starttime, argv, and proc-dir inode proof remain mandatory. + return None + try: + return os.fstat(fd).st_ino + finally: + os.close(fd) + + +def _parse_stat(raw: bytes) -> tuple[str, int, str]: + try: + text = raw.decode("ascii") + suffix = text.rsplit(") ", 1)[1].split() + state = suffix[0] + parent_pid = int(suffix[1], 10) + start_time = suffix[19] + except (IndexError, UnicodeDecodeError, ValueError) as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + if not start_time.isascii() or not start_time.isdigit() or len(state) != 1: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return state, parent_pid, start_time + + +def _parse_status(raw: bytes, pid: int) -> tuple[tuple[int, int, int, int], int]: + try: + text = raw.decode("ascii") + except UnicodeDecodeError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + uid_line = next((line for line in text.splitlines() if line.startswith("Uid:")), "") + nspid_line = next( + (line for line in text.splitlines() if line.startswith("NSpid:")), "" + ) + try: + uid_values = tuple(int(value, 10) for value in uid_line.split()[1:5]) + namespace_values = tuple(int(value, 10) for value in nspid_line.split()[1:]) + except ValueError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + if len(uid_values) != 4 or not namespace_values or namespace_values[-1] != pid: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return uid_values, namespace_values[-1] + + +def _parse_cmdline(raw: bytes) -> tuple[bytes, ...]: + values = tuple(value for value in raw.split(b"\0") if value) + if not values or sum(len(value) for value in values) > MAX_PROC_FILE_BYTES: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return values + + +class ProcReader: + """Bounded, descriptor-relative reader for one procfs process namespace.""" + + def __init__(self, root: str | None = None): + self.root = root or _proc_root() + self.fd = _open_directory(self.root) + + def close(self) -> None: + os.close(self.fd) + + def __enter__(self) -> ProcReader: + return self + + def __exit__(self, _kind: object, _value: object, _traceback: object) -> None: + self.close() + + def pids(self) -> list[int]: + values: list[int] = [] + observed = 0 + with os.scandir(self.fd) as entries: + for entry in entries: + if not entry.name.isascii() or not entry.name.isdigit(): + continue + observed += 1 + if observed > MAX_PROC_ENTRIES: + raise ControlError("SUPERVISOR_UNAVAILABLE") + values.append(int(entry.name, 10)) + return values + + def capture(self, pid: int) -> ProcessIdentity: + pid_fd = _open_pid(self.fd, pid) + try: + before = os.fstat(pid_fd) + first_stat = _parse_stat(_read_at(pid_fd, "stat")) + first_status = _parse_status(_read_at(pid_fd, "status"), pid) + first_cmdline = _parse_cmdline(_read_at(pid_fd, "cmdline")) + first_namespace = _namespace_inode(pid_fd) + second_stat = _parse_stat(_read_at(pid_fd, "stat")) + second_status = _parse_status(_read_at(pid_fd, "status"), pid) + second_cmdline = _parse_cmdline(_read_at(pid_fd, "cmdline")) + second_namespace = _namespace_inode(pid_fd) + after = os.fstat(pid_fd) + if ( + first_stat[1:] != second_stat[1:] + or (first_stat[0] == "Z") != (second_stat[0] == "Z") + or first_status != second_status + or first_cmdline != second_cmdline + or first_namespace != second_namespace + or before.st_dev != after.st_dev + or before.st_ino != after.st_ino + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + state, parent_pid, start_time = second_stat + uids, namespace_pid = second_status + return ProcessIdentity( + pid=pid, + start_time=start_time, + parent_pid=parent_pid, + state=state, + uids=uids, + namespace_pid=namespace_pid, + namespace_inode=second_namespace, + cmdline=second_cmdline, + proc_device=before.st_dev, + proc_inode=before.st_ino, + ) + finally: + os.close(pid_fd) + + def read_stable_file( + self, identity: ProcessIdentity, name: str, limit: int + ) -> bytes: + pid_fd = _open_pid(self.fd, identity.pid) + try: + pinned = os.fstat(pid_fd) + if ( + pinned.st_dev != identity.proc_device + or pinned.st_ino != identity.proc_inode + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + first = _read_at(pid_fd, name, limit) + second = _read_at(pid_fd, name, limit) + current = self.capture(identity.pid) + if first != second or current.stable_key() != identity.stable_key(): + raise ControlError("SUPERVISOR_UNAVAILABLE") + return first + finally: + os.close(pid_fd) + + +def _basename(value: bytes) -> bytes: + return value.rsplit(b"/", 1)[-1] + + +def _is_openshell(identity: ProcessIdentity) -> bool: + return bool( + identity.pid == 1 + and identity.parent_pid == 0 + and identity.state != "Z" + and identity.uids == (0, 0, 0, 0) + and identity.namespace_pid == 1 + and identity.cmdline[0] == OPENSHELL_ARGV0 + ) + + +def _is_nemoclaw_start(identity: ProcessIdentity, sandbox_uid: int) -> bool: + argv = identity.cmdline + direct = argv in ((b"nemoclaw-start",), (NEMOCLAW_START_PATH,)) + bash = len(argv) == 2 and _basename(argv[0]) == b"bash" and argv[1] in ( + b"nemoclaw-start", + NEMOCLAW_START_PATH, + ) + return bool( + identity.pid > 1 + and identity.parent_pid == 1 + and identity.state != "Z" + and identity.uids == (sandbox_uid,) * 4 + and identity.namespace_pid == identity.pid + and (direct or bash) + ) + + +def _sandbox_uid() -> int: + try: + return pwd.getpwnam("sandbox").pw_uid + except KeyError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + + +def _discover_supervisor(reader: ProcReader) -> ProcessIdentity: + pid1 = reader.capture(1) + if not _is_openshell(pid1): + raise ControlError("SUPERVISOR_UNAVAILABLE") + sandbox_uid = _sandbox_uid() + matches: list[ProcessIdentity] = [] + for pid in reader.pids(): + if pid == 1: + continue + try: + identity = reader.capture(pid) + except (ControlError, FileNotFoundError, ProcessLookupError, PermissionError): + continue + if ( + _is_nemoclaw_start(identity, sandbox_uid) + and ( + pid1.namespace_inode is None + or identity.namespace_inode == pid1.namespace_inode + ) + ): + matches.append(identity) + if len(matches) > 1: + break + if len(matches) != 1: + raise ControlError("SUPERVISOR_UNAVAILABLE") + current_pid1 = reader.capture(1) + current_supervisor = reader.capture(matches[0].pid) + if ( + current_pid1.stable_key() != pid1.stable_key() + or current_supervisor.stable_key() != matches[0].stable_key() + ): + raise ControlError("SUPERVISOR_UNAVAILABLE") + return current_supervisor + + +def _is_hermes_gateway(identity: ProcessIdentity) -> bool: + argv = identity.cmdline + hermes = (b"/usr/local/bin/hermes", b"/usr/local/bin/hermes.real") + if len(argv) == 3: + return argv[0] in hermes and argv[1:] == (b"gateway", b"run") + return bool( + len(argv) == 4 + and _basename(argv[0]) in (b"python", b"python3") + and argv[1] in hermes + and argv[2:] == (b"gateway", b"run") + ) + + +def _is_openclaw_gateway(identity: ProcessIdentity, port: int) -> bool: + argv = identity.cmdline + if len(argv) == 1 and _basename(argv[0]) in (b"openclaw", b"openclaw-gateway"): + return True + command_index = 0 + if len(argv) >= 2 and _basename(argv[0]) in (b"node", b"nodejs"): + command_index = 1 + if command_index >= len(argv) or _basename(argv[command_index]) not in ( + b"openclaw", + b"openclaw.mjs", + ): + return False + arguments = argv[command_index + 1 :] + expected_port = str(port).encode("ascii") + return arguments in ( + (b"gateway", b"run", b"--port", expected_port), + (b"gateway", b"run", b"--port=" + expected_port), + ) + + +def _parse_environment(raw: bytes) -> dict[str, str]: + values: dict[str, str] = {} + for item in raw.split(b"\0"): + if not item: + continue + key, separator, value = item.partition(b"=") + if not separator or not ENV_KEY_RE.fullmatch(key) or key in { + existing.encode("ascii") for existing in values + }: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + try: + values[key.decode("ascii")] = value.decode("utf-8", "surrogateescape") + except UnicodeDecodeError as exc: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") from exc + return values + + +def _openclaw_port(reader: ProcReader, supervisor: ProcessIdentity) -> int: + environment = _parse_environment( + reader.read_stable_file(supervisor, "environ", MAX_ENV_BYTES) + ) + raw = environment.get("NEMOCLAW_DASHBOARD_PORT", "").strip() + if not raw: + chat_url = environment.get("CHAT_UI_URL", "") + match = re.search(r":([0-9]{1,5})(?:/|\Z)", chat_url) + raw = match.group(1) if match else "18789" + try: + port = int(raw, 10) + except ValueError as exc: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") from exc + if port < 1024 or port > 65535: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + return port + + +def _agent_spec( + name: str, reader: ProcReader, supervisor: ProcessIdentity +) -> AgentSpec: + if name == "hermes": + return AgentSpec( + name="hermes", + port=18642, + readiness_checks=((8642, "/health"),), + ) + return AgentSpec(name="openclaw", port=_openclaw_port(reader, supervisor)) + + +def _gateway_matches( + identity: ProcessIdentity, + supervisor: ProcessIdentity, + spec: AgentSpec, +) -> bool: + if not ( + identity.pid > 1 + and identity.parent_pid == supervisor.pid + and identity.state != "Z" + and identity.uids == (_sandbox_uid(),) * 4 + and identity.namespace_pid == identity.pid + and identity.namespace_inode == supervisor.namespace_inode + ): + return False + if spec.name == "hermes": + return _is_hermes_gateway(identity) + return _is_openclaw_gateway(identity, spec.port) + + +def _gateway_candidates( + reader: ProcReader, supervisor: ProcessIdentity, spec: AgentSpec +) -> list[ProcessIdentity]: + matches: list[ProcessIdentity] = [] + for pid in reader.pids(): + if pid in (1, supervisor.pid): + continue + try: + identity = reader.capture(pid) + except (ControlError, FileNotFoundError, ProcessLookupError, PermissionError): + continue + if _gateway_matches(identity, supervisor, spec): + matches.append(identity) + if len(matches) > 1: + break + current_supervisor = reader.capture(supervisor.pid) + if current_supervisor.stable_key() != supervisor.stable_key(): + raise ControlError("SUPERVISOR_UNAVAILABLE") + if len(matches) > 1: + raise ControlError("SUPERVISOR_UNAVAILABLE") + return matches + + +def _listener_inodes( + reader: ProcReader, identity: ProcessIdentity, port: int +) -> set[str]: + expected = f"{port:04X}" + inodes: set[str] = set() + pid_fd = _open_pid(reader.fd, identity.pid) + try: + pinned = os.fstat(pid_fd) + if ( + pinned.st_dev != identity.proc_device + or pinned.st_ino != identity.proc_inode + ): + return set() + for table in ("net/tcp", "net/tcp6"): + try: + raw = _read_at(pid_fd, table, MAX_PROC_FILE_BYTES) + except OSError: + continue + for line in raw.decode("ascii", "ignore").splitlines()[1:]: + fields = line.split() + if len(fields) < 10: + continue + local = fields[1].rsplit(":", 1) + if ( + len(local) == 2 + and local[1].upper() == expected + and fields[3] == "0A" + ): + inodes.add(fields[9]) + if reader.capture(identity.pid).stable_key() != identity.stable_key(): + return set() + finally: + os.close(pid_fd) + return inodes + + +def _owns_listener( + reader: ProcReader, identity: ProcessIdentity, port: int +) -> bool: + current = reader.capture(identity.pid) + if current.stable_key() != identity.stable_key(): + return False + inodes = _listener_inodes(reader, identity, port) + if not inodes: + return False + pid_fd = _open_pid(reader.fd, identity.pid) + try: + pinned = os.fstat(pid_fd) + if ( + pinned.st_dev != identity.proc_device + or pinned.st_ino != identity.proc_inode + ): + return False + flags = ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + fd_dir = os.open("fd", flags, dir_fd=pid_fd) + try: + with os.scandir(fd_dir) as entries: + for entry in entries: + try: + target = os.readlink(entry.name, dir_fd=fd_dir) + except OSError: + continue + match = re.fullmatch(r"socket:\[([0-9]+)\]", target) + if match and match.group(1) in inodes: + return reader.capture(identity.pid).stable_key() == identity.stable_key() + finally: + os.close(fd_dir) + finally: + os.close(pid_fd) + return False + + +def _http_healthy(port: int, path: str) -> bool: + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=2) + try: + connection.request("GET", path) + response = connection.getresponse() + response.read(4096) + return response.status in (200, 401) + except OSError: + return False + finally: + connection.close() + + +def _http_healthy_in_gateway_namespace( + reader: ProcReader, + identity: ProcessIdentity, + port: int, + path: str, +) -> bool: + """Probe loopback from the gateway's network namespace, then restore ours.""" + + setns = getattr(os, "setns", None) + if setns is None: + raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE") + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) + current_namespace = os.open("/proc/self/ns/net", flags) + pid_fd = -1 + target_namespace = -1 + switched = False + try: + pid_fd = _open_pid(reader.fd, identity.pid) + pinned = os.fstat(pid_fd) + if ( + pinned.st_dev != identity.proc_device + or pinned.st_ino != identity.proc_inode + ): + return False + target_namespace = os.open("ns/net", flags, dir_fd=pid_fd) + if reader.capture(identity.pid).stable_key() != identity.stable_key(): + return False + setns(target_namespace, getattr(os, "CLONE_NEWNET", 0x40000000)) + switched = True + return _http_healthy(port, path) + except OSError as exc: + if exc.errno in (errno.ENOENT, errno.ENOTDIR, errno.ESRCH): + return False + raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE") from exc + finally: + if switched: + try: + setns(current_namespace, getattr(os, "CLONE_NEWNET", 0x40000000)) + except OSError as exc: + raise ControlError("GATEWAY_FAILED") from exc + if target_namespace >= 0: + os.close(target_namespace) + if pid_fd >= 0: + os.close(pid_fd) + os.close(current_namespace) + + +def _gateway_healthy( + reader: ProcReader, identity: ProcessIdentity, spec: AgentSpec +) -> bool: + return bool( + _owns_listener(reader, identity, spec.port) + and _http_healthy_in_gateway_namespace( + reader, identity, spec.port, spec.health_path + ) + and _owns_listener(reader, identity, spec.port) + ) + + +def _gateway_auxiliaries_healthy( + reader: ProcReader, identity: ProcessIdentity, spec: AgentSpec +) -> bool: + """Prove the public API relay the host probes before completing control.""" + + for port, path in spec.readiness_checks: + if not _http_healthy_in_gateway_namespace(reader, identity, port, path): + return False + # The public probes can take several seconds. Re-prove the exact gateway + # after them so a replacement that exited during auxiliary repair is never + # reported as the completed child. + return _gateway_healthy(reader, identity, spec) + + +def _run_fixed_validator(script: str, arguments: list[str]) -> None: + _validate_trusted_regular(script) + result = subprocess.run( + [sys.executable, "-I", script, *arguments], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=15, + check=False, + ) + if result.returncode != 0: + raise ControlError("SECRET_BOUNDARY_REFUSED") + + +def _validate_runtime_environment(script: str, environment: dict[str, str]) -> None: + """Validate runtime values without execing a root process under them.""" + + _validate_trusted_regular(script) + spec = importlib.util.spec_from_file_location( + "_nemoclaw_managed_boundary_validator", script + ) + if spec is None or spec.loader is None: + raise ControlError("SECRET_BOUNDARY_VALIDATOR_MISSING") + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + validator = getattr(module, "validate_runtime_env") + result = validator(environment) + except (AttributeError, ImportError, OSError, RuntimeError) as exc: + raise ControlError("SECRET_BOUNDARY_REFUSED") from exc + if result != 0: + raise ControlError("SECRET_BOUNDARY_REFUSED") + + +def _read_regular(path: str, limit: int) -> tuple[bytes, os.stat_result]: + flags = ( + os.O_RDONLY + | getattr(os, "O_NONBLOCK", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + fd = os.open(path, flags) + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(65536, limit + 1 - total)) + if not chunk: + break + chunks.append(chunk) + total += len(chunk) + if total > limit: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + after = os.fstat(fd) + if ( + before.st_dev != after.st_dev + or before.st_ino != after.st_ino + or before.st_size != after.st_size + or before.st_mtime_ns != after.st_mtime_ns + ): + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + return b"".join(chunks), before + finally: + os.close(fd) + + +def _verify_locked_hermes_hash() -> None: + config_path = _system_path("/sandbox/.hermes/config.yaml") + env_path = _system_path("/sandbox/.hermes/.env") + hash_path = _system_path("/etc/nemoclaw/hermes.config-hash") + config, config_stat = _read_regular(config_path, MAX_CONFIG_BYTES) + environment, env_stat = _read_regular(env_path, MAX_ENV_BYTES) + locked = tuple( + item.st_uid == 0 and stat.S_IMODE(item.st_mode) & 0o222 == 0 + for item in (config_stat, env_stat) + ) + if locked == (False, False): + # The managed non-root cold-start path owns only a mutable compatibility + # hash. Treating it as a root trust anchor would let same-UID code bless + # arbitrary drift. The caller still receives the canonical secret + # checks, process proof, pidfd safety, and post-launch health proof. + return + if locked != (True, True): + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + strict, strict_stat = _read_regular(hash_path, MAX_HASH_BYTES) + if strict_stat.st_uid != 0 or stat.S_IMODE(strict_stat.st_mode) & 0o022: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + try: + records = {} + for line in strict.decode("ascii").splitlines(): + digest, pathname = line.split(maxsplit=1) + records[pathname.strip()] = digest.lower() + except (UnicodeDecodeError, ValueError) as exc: + raise ControlError("GATEWAY_CONFIG_HASH_MISMATCH") from exc + expected_paths = { + "/sandbox/.hermes/config.yaml": hashlib.sha256(config).hexdigest(), + "/sandbox/.hermes/.env": hashlib.sha256(environment).hexdigest(), + } + if set(records) != set(expected_paths) or any( + not SHA256_RE.fullmatch(records[path]) + or records[path] != digest + for path, digest in expected_paths.items() + ): + raise ControlError("GATEWAY_CONFIG_HASH_MISMATCH") + + +def _hermes_preflight(reader: ProcReader, supervisor: ProcessIdentity) -> None: + validator = _system_path(HERMES_BOUNDARY_PATH) + if not os.path.exists(validator): + raise ControlError("SECRET_BOUNDARY_VALIDATOR_MISSING") + _run_fixed_validator( + validator, + ["env-file", _system_path("/sandbox/.hermes/.env")], + ) + raw_environment = reader.read_stable_file(supervisor, "environ", MAX_ENV_BYTES) + _validate_runtime_environment(validator, _parse_environment(raw_environment)) + _verify_locked_hermes_hash() + + +def _openclaw_preflight() -> None: + guard = _system_path(OPENCLAW_GUARD_PATH) + _validate_trusted_regular(guard) + result = subprocess.run( + [ + sys.executable, + "-I", + guard, + "preflight-restart", + "--config-dir", + _system_path("/sandbox/.openclaw"), + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=15, + check=False, + ) + if result.returncode != 0: + raise ControlError("GATEWAY_UNSAFE_CONFIG_PATH") + + +def _preflight( + spec: AgentSpec, reader: ProcReader, supervisor: ProcessIdentity +) -> None: + if spec.name == "hermes": + _hermes_preflight(reader, supervisor) + else: + _openclaw_preflight() + + +def _pidfd_open(pid: int) -> int: + opener = getattr(os, "pidfd_open", None) + sender = getattr(signal, "pidfd_send_signal", None) + if opener is None or sender is None: + raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE") + try: + return opener(pid, 0) + except OSError as exc: + raise ControlError("SUPERVISOR_UNAVAILABLE") from exc + + +def _pidfd_exited(pidfd: int, timeout_seconds: float) -> bool: + poller = select.poll() + poller.register(pidfd, select.POLLIN) + return bool(poller.poll(max(0, int(timeout_seconds * 1000)))) + + +def _send_pidfd(pidfd: int, signum: signal.Signals) -> None: + sender = getattr(signal, "pidfd_send_signal", None) + if sender is None: + raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE") + try: + sender(pidfd, signum, None, 0) + except OSError as exc: + raise ControlError("GATEWAY_FAILED") from exc + + +def _terminate_gateway(reader: ProcReader, identity: ProcessIdentity) -> None: + pidfd = _pidfd_open(identity.pid) + try: + current = reader.capture(identity.pid) + if current.stable_key() != identity.stable_key(): + raise ControlError("SUPERVISOR_UNAVAILABLE") + _send_pidfd(pidfd, signal.SIGTERM) + if _pidfd_exited(pidfd, STOP_GRACE_SECONDS): + return + current = reader.capture(identity.pid) + if current.stable_key() != identity.stable_key(): + raise ControlError("SUPERVISOR_UNAVAILABLE") + _send_pidfd(pidfd, signal.SIGKILL) + if not _pidfd_exited(pidfd, KILL_GRACE_SECONDS): + raise ControlError("GATEWAY_FAILED") + finally: + os.close(pidfd) + + +def _wait_for_healthy_gateway( + reader: ProcReader, + supervisor: ProcessIdentity, + spec: AgentSpec, + old_identity: ProcessIdentity | None, + timeout_seconds: float = RECOVERY_TIMEOUT_SECONDS, + require_auxiliary_health: bool = False, +) -> ProcessIdentity: + deadline = time.monotonic() + timeout_seconds + while time.monotonic() < deadline: + try: + candidates = _gateway_candidates(reader, supervisor, spec) + except (FileNotFoundError, ProcessLookupError, PermissionError): + raise ControlError("SUPERVISOR_UNAVAILABLE") + for candidate in candidates: + if old_identity is not None and ( + candidate.pid, + candidate.start_time, + ) == (old_identity.pid, old_identity.start_time): + continue + try: + if _gateway_healthy(reader, candidate, spec) and ( + not require_auxiliary_health + or _gateway_auxiliaries_healthy(reader, candidate, spec) + ): + return candidate + except (FileNotFoundError, ProcessLookupError): + continue + except ControlError as error: + if error.code != "SUPERVISOR_UNAVAILABLE": + raise + time.sleep(POLL_SECONDS) + raise ControlError("GATEWAY_HEALTH_TIMEOUT") + + +def _wait_for_recovery_candidate( + reader: ProcReader, + supervisor: ProcessIdentity, + spec: AgentSpec, + initial_identity: ProcessIdentity, +) -> tuple[ProcessIdentity | None, ProcessIdentity | None]: + """Give the observed candidate, and at most one successor, a full grace.""" + + observed = initial_identity + for _attempt in range(2): + try: + healthy = _wait_for_healthy_gateway( + reader, + supervisor, + spec, + None, + RECOVER_EXISTING_GRACE_SECONDS, + ) + return healthy, None + except ControlError as error: + if error.code != "GATEWAY_HEALTH_TIMEOUT": + raise + + candidates = _gateway_candidates(reader, supervisor, spec) + current = candidates[0] if candidates else None + if current is None: + return None, None + if current.stable_key() == observed.stable_key(): + return None, current + observed = current + + return None, observed + + +def _control(action: str, nonce: str) -> tuple[str, int, int]: + agent = _detect_agent() + with ProcReader() as reader: + supervisor = _discover_supervisor(reader) + spec = _agent_spec(agent, reader, supervisor) + candidates = _gateway_candidates(reader, supervisor, spec) + old_identity = candidates[0] if candidates else None + + _preflight(spec, reader, supervisor) + + if action == "probe": + if old_identity is None: + raise ControlError("GATEWAY_HEALTH_TIMEOUT") + if not _gateway_healthy(reader, old_identity, spec): + raise ControlError("GATEWAY_HEALTH_TIMEOUT") + if not _gateway_auxiliaries_healthy(reader, old_identity, spec): + raise ControlError("GATEWAY_HEALTH_TIMEOUT") + healthy = reader.capture(old_identity.pid) + if healthy.stable_key() != old_identity.stable_key(): + raise ControlError("GATEWAY_HEALTH_TIMEOUT") + return "already-running", old_identity.pid, healthy.pid + + if action == "recover" and old_identity is not None: + # PID 1 continuously supervises the managed gateway. A host + # recovery request can arrive after PID 1 has launched a + # replacement but before its listener is healthy. Give that proven + # child a short grace period. If its identity changes during that + # grace, give the one successor its own bounded grace before any + # signal so recovery cannot churn a newly launched replacement. + original_identity = old_identity + existing, old_identity = _wait_for_recovery_candidate( + reader, + supervisor, + spec, + original_identity, + ) + if existing is not None: + completed = _wait_for_healthy_gateway( + reader, + supervisor, + spec, + None, + RECOVERY_TIMEOUT_SECONDS, + True, + ) + return "already-running", original_identity.pid, completed.pid + + expected_exit_lease = None + try: + if old_identity is not None and spec.name == "hermes": + # The nonroot entrypoint owns the child and its crash budget. + # Publish an exact root-owned authorization before the pidfd + # signal. The marker names this live root controller so a + # delayed reap remains authorized without trusting wall time, + # while an orphaned marker fails closed as an ordinary crash. + controller_identity = _controller_process_identity(reader) + expected_exit_lease = _publish_expected_exit_lease( + old_identity, + controller_identity, + ) + if old_identity is not None: + _terminate_gateway(reader, old_identity) + + replacement = _wait_for_healthy_gateway( + reader, + supervisor, + spec, + old_identity, + RECOVERY_TIMEOUT_SECONDS, + True, + ) + return "ok", old_identity.pid if old_identity else 0, replacement.pid + finally: + if expected_exit_lease is not None: + _clear_expected_exit_lease(expected_exit_lease) + + +def _validate_request(argv: list[str]) -> tuple[str, str]: + if len(argv) != 2: + raise ControlError("SUPERVISOR_INVALID_REQUEST") + action, nonce = argv + if action not in ("restart", "recover", "probe"): + raise ControlError("SUPERVISOR_INVALID_ACTION") + if not NONCE_RE.fullmatch(nonce): + raise ControlError("SUPERVISOR_INVALID_NONCE") + return action, nonce + + +def main(argv: list[str]) -> int: + try: + action, nonce = _validate_request(argv) + _require_root() + _require_installed_helper_trust() + result, old_pid, new_pid = _control(action, nonce) + print(f"v1 {nonce} complete {result} {old_pid} {new_pid}") + print(f"GATEWAY_PID={new_pid}") + return 0 + except ControlError as error: + print(error.code, file=sys.stderr) + return 1 + except (OSError, subprocess.SubprocessError): + print("GATEWAY_FAILED", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index b2483e7937e..8a969b4daad 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -123,6 +123,13 @@ fi # shellcheck source=scripts/lib/sandbox-init.sh source "$_SANDBOX_INIT" +_GATEWAY_SUPERVISOR="/usr/local/lib/nemoclaw/gateway-supervisor.sh" +if [ ! -f "$_GATEWAY_SUPERVISOR" ]; then + _GATEWAY_SUPERVISOR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/gateway-supervisor.sh" +fi +# shellcheck source=scripts/lib/gateway-supervisor.sh +source "$_GATEWAY_SUPERVISOR" + # Harden RLIMITs (nproc #809 + nofile #4527) as root PID 1, before the capsh # drop and the setpriv step-down, so the caps are inherited and unraisable. harden_resource_limits @@ -248,19 +255,109 @@ NEMOCLAW_CMD=("$@") # not documented as a public env API; production always keeps the default path. GATEWAY_PID_FILE=/tmp/nemoclaw-gateway.pid +# A numeric PID is not a process identity: Linux may reuse it immediately +# after the child is reaped. Capture `/proc//stat` field 22 (starttime) +# for every supervised process and require the pair to keep matching before +# admitting, probing, or signalling that process. The `ps` fallback exists +# only so the shell helpers remain testable on non-Linux developer hosts; +# production containers always use the strict `/proc` identity. +GATEWAY_PID_START_IDENTITY="" +AUTO_PAIR_PID_START_IDENTITY="" +GATEWAY_LOG_TAIL_PID_START_IDENTITY="" +GATEWAY_LOG_PERSIST_PID_START_IDENTITY="" +PLUGIN_REFRESH_PID_START_IDENTITY="" +GATEWAY_WATCHDOG_PID_START_IDENTITY="" + +openclaw_load_pid_identity() { + local pid="$1" + local proc_root="${_NEMOCLAW_PROC_ROOT:-/proc}" + local stat_line rest parent_pid start_identity started + + OPENCLAW_OBSERVED_PARENT_PID="" + OPENCLAW_OBSERVED_START_IDENTITY="" + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + + if [ -r "${proc_root}/${pid}/stat" ]; then + IFS= read -r stat_line <"${proc_root}/${pid}/stat" || return 1 + rest="${stat_line##*) }" + [ "$rest" != "$stat_line" ] || return 1 + # After `pid (comm)` is removed, state is $1, ppid is $2, and Linux + # starttime (the original field 22) is $20. `##*) ` deliberately uses + # the final closing parenthesis because comm itself may contain `)`. + # shellcheck disable=SC2086 # intentional field split of proc stat suffix + set -- $rest + [ "$#" -ge 20 ] || return 1 + parent_pid="$2" + start_identity="${20}" + case "$parent_pid" in + '' | *[!0-9]*) return 1 ;; + esac + case "$start_identity" in + '' | *[!0-9]*) return 1 ;; + esac + else + # An explicitly supplied proc root is a fail-closed test seam: never fall + # through to host `ps`, which would inspect a different process namespace. + [ "${_NEMOCLAW_PROC_ROOT+x}" != x ] || return 1 + command -v ps >/dev/null 2>&1 || return 1 + parent_pid="$(ps -o ppid= -p "$pid" 2>/dev/null | awk 'NR == 1 { gsub(/[[:space:]]/, "", $0); print; exit }')" + started="$(LC_ALL=C ps -o lstart= -p "$pid" 2>/dev/null | awk 'NR == 1 { sub(/^[[:space:]]+/, ""); sub(/[[:space:]]+$/, ""); print; exit }')" + case "$parent_pid" in + '' | *[!0-9]*) return 1 ;; + esac + [ -n "$started" ] || return 1 + start_identity="ps:${started//[[:space:]]/_}" + fi + + OPENCLAW_OBSERVED_PARENT_PID="$parent_pid" + OPENCLAW_OBSERVED_START_IDENTITY="$start_identity" +} + +openclaw_pid_start_identity() { + openclaw_load_pid_identity "$1" || return 1 + printf '%s\n' "$OPENCLAW_OBSERVED_START_IDENTITY" +} + +capture_openclaw_pid_start_identity() { + local pid="$1" + local output_var="$2" + local identity + identity="$(openclaw_pid_start_identity "$pid")" || return 1 + [ -n "$identity" ] || return 1 + printf -v "$output_var" '%s' "$identity" +} + +openclaw_supervised_pid_is_live() { + local pid="$1" + local expected_identity="$2" + [ -n "$expected_identity" ] || return 1 + gateway_control_pid_is_live "$pid" || return 1 + openclaw_load_pid_identity "$pid" || return 1 + [ "$OPENCLAW_OBSERVED_PARENT_PID" = "$$" ] \ + && [ "$OPENCLAW_OBSERVED_START_IDENTITY" = "$expected_identity" ] +} + # Best-effort: a write failure must never block startup. mark_in_container_gateway() { _nemoclaw_safe_create_tmp_file /tmp/nemoclaw-gateway-local 600 "" best-effort 2>/dev/null || true } -# Record the PID of the live in-container gateway so the Docker HEALTHCHECK +# Record the PID/starttime identity of the live in-container gateway so the +# Docker HEALTHCHECK # can confirm the actual gateway process (not merely *some* `openclaw` # process) is still alive when the in-container curl probe cannot reach the # dashboard port (#4952). Refreshed on every (re)launch so a respawned gateway # is tracked and a window where the gateway is down reads as unhealthy. # Best-effort: a write failure must never block startup. record_gateway_pid() { - printf '%s\n' "${1:-}" | _nemoclaw_safe_replace_tmp_file "$GATEWAY_PID_FILE" 600 "" best-effort 2>/dev/null || true + printf '%s %s\n' "${1:-}" "${2:-}" \ + | _nemoclaw_safe_replace_tmp_file "$GATEWAY_PID_FILE" 600 "" best-effort 2>/dev/null || true +} + +clear_gateway_pid_record() { + printf '' | _nemoclaw_safe_replace_tmp_file "$GATEWAY_PID_FILE" 600 "" best-effort 2>/dev/null || true } _chat_ui_url_port() { @@ -450,6 +547,16 @@ openclaw_config_dir_owner() { stat -c '%U' "$config_dir" 2>/dev/null || stat -f '%Su' "$config_dir" 2>/dev/null || echo unknown } +openclaw_locked_parent_is_protected() { + local owner mode + owner="$(stat -c '%U:%G' /sandbox 2>/dev/null || stat -f '%Su:%Sg' /sandbox 2>/dev/null || true)" + mode="$(stat -c '%a' /sandbox 2>/dev/null || stat -f '%Lp' /sandbox 2>/dev/null || true)" + case "${owner} ${mode}" in + "root:sandbox 1775" | "root:sandbox 01775") return 0 ;; + *) return 1 ;; + esac +} + prepare_openclaw_config_for_write() { local config_file="$1" local hash_file="$2" @@ -806,6 +913,14 @@ apply_model_override() { local config_file="/sandbox/.openclaw/openclaw.json" local hash_file="/sandbox/.openclaw/.config-hash" + # A shields-up pair is a host-sealed trust anchor. Startup/restart may read + # it, but must never temporarily chmod or rewrite it behind the host's + # persisted content seal. Apply host overrides after shields-down instead. + if [ "$(openclaw_config_dir_owner "$(dirname "$config_file")")" = "root" ]; then + printf '[config] Shields are up; deferring model/inference overrides until config is mutable\n' >&2 + return 0 + fi + # SECURITY: Refuse to write through symlinks to prevent symlink-following attacks. # Legacy-layout migration rejects symlinked config paths before overrides; guard here too. if [ -L "$config_file" ] || [ -L "$hash_file" ]; then @@ -959,6 +1074,11 @@ reconcile_agent_model_with_provider() { [ -f "$config_file" ] || return 0 + if [ "$(openclaw_config_dir_owner "$(dirname "$config_file")")" = "root" ]; then + printf '[config] Shields are up; skipping provider-model reconciliation for the sealed config\n' >&2 + return 0 + fi + if [ -L "$config_file" ] || [ -L "$hash_file" ]; then return 0 fi @@ -1117,6 +1237,11 @@ apply_cors_override() { local config_file="/sandbox/.openclaw/openclaw.json" local hash_file="/sandbox/.openclaw/.config-hash" + if [ "$(openclaw_config_dir_owner "$(dirname "$config_file")")" = "root" ]; then + printf '[config] Shields are up; deferring the CORS override until config is mutable\n' >&2 + return 0 + fi + if [ -L "$config_file" ] || [ -L "$hash_file" ]; then printf '[SECURITY] Refusing CORS override — config or hash path is a symlink\n' >&2 return 1 @@ -1183,6 +1308,11 @@ refresh_openclaw_provider_placeholders() { local hash_file="/sandbox/.openclaw/.config-hash" [ -f "$config_file" ] || return 0 + if [ "$(openclaw_config_dir_owner "$(dirname "$config_file")")" = "root" ]; then + printf '[config] Shields are up; preserving sealed provider placeholders unchanged\n' >&2 + return 0 + fi + local keys keys="$( python3 - "$config_file" <<'PYPLACEHOLDERKEYS' @@ -1753,6 +1883,29 @@ PYMESSAGINGALIASES done <<<"$_rows" } +node_options_has_require() { + local wanted="$1" + local previous="" + local token + local tokens=() + IFS=$' \t\n' read -r -a tokens <<<"${NODE_OPTIONS:-}" + for token in "${tokens[@]}"; do + if [ "$previous" = "--require" ] && [ "$token" = "$wanted" ]; then + return 0 + fi + [ "$token" = "--require=$wanted" ] && return 0 + previous="$token" + done + return 1 +} + +append_node_require_once() { + local wanted="$1" + if ! node_options_has_require "$wanted"; then + export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $wanted" + fi +} + install_messaging_runtime_preloads() { [ -f "$_MESSAGING_RUNTIME_SETUP_PLAN" ] || return 0 local _rows @@ -1785,10 +1938,10 @@ PYMESSAGINGPRELOADS return 1 fi [ -n "$_install_message" ] && printf '%s\n' "$_install_message" >&2 - emit_sandbox_sourced_file "$_target" <"$_source" + emit_sandbox_sourced_file "$_target" <"$_source" || return 1 case ",$_inject_into," in *,boot,*) - export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_target" + append_node_require_once "$_target" ;; esac case ",$_inject_into," in @@ -1801,9 +1954,10 @@ PYMESSAGINGPRELOADS fi if [ "${#_connect_preloads[@]}" -gt 0 ]; then - printf '%s\n' "${_connect_preloads[@]}" | emit_sandbox_sourced_file "$_MESSAGING_CONNECT_PRELOADS_FILE" + printf '%s\n' "${_connect_preloads[@]}" \ + | emit_sandbox_sourced_file "$_MESSAGING_CONNECT_PRELOADS_FILE" || return 1 else - : | emit_sandbox_sourced_file "$_MESSAGING_CONNECT_PRELOADS_FILE" + : | emit_sandbox_sourced_file "$_MESSAGING_CONNECT_PRELOADS_FILE" || return 1 fi } @@ -2184,6 +2338,11 @@ start_persistent_gateway_log_mirror() { { tail -n +1 -F /tmp/gateway.log 2>/dev/null >>"$log_file"; } & GATEWAY_LOG_PERSIST_PID=$! + if ! capture_openclaw_pid_start_identity \ + "$GATEWAY_LOG_PERSIST_PID" GATEWAY_LOG_PERSIST_PID_START_IDENTITY; then + echo "[gateway] could not capture persistent-log process identity" >&2 + return 1 + fi } start_auto_pair() { @@ -2520,6 +2679,10 @@ else: print(f'[auto-pair] watcher deadline reached approvals={APPROVED}') PYAUTOPAIR AUTO_PAIR_PID=$! + if ! capture_openclaw_pid_start_identity "$AUTO_PAIR_PID" AUTO_PAIR_PID_START_IDENTITY; then + echo "[gateway] could not capture auto-pair process identity" >&2 + return 1 + fi echo "[gateway] auto-pair watcher launched (pid $AUTO_PAIR_PID)" >&2 } @@ -2593,15 +2756,9 @@ fi # preserved so errors surface promptly to users running short-lived tools. _SANDBOX_SAFETY_NET="/tmp/nemoclaw-sandbox-safety-net.js" _SANDBOX_SAFETY_NET_SOURCE="/usr/local/lib/nemoclaw/preloads/sandbox-safety-net.js" -emit_sandbox_sourced_file "$_SANDBOX_SAFETY_NET" <"$_SANDBOX_SAFETY_NET_SOURCE" -export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_SANDBOX_SAFETY_NET" _PROXY_FIX_SCRIPT="/tmp/nemoclaw-http-proxy-fix.js" _PROXY_FIX_SOURCE="/usr/local/lib/nemoclaw/preloads/http-proxy-fix.js" -if [ "${NODE_USE_ENV_PROXY:-}" = "1" ]; then - emit_sandbox_sourced_file "$_PROXY_FIX_SCRIPT" <"$_PROXY_FIX_SOURCE" - export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_PROXY_FIX_SCRIPT" -fi # NVIDIA endpoint model-specific inference parameter injection # (NemoClaw#1193, NemoClaw#2051). @@ -2628,8 +2785,6 @@ fi # regression proof, and removal condition. _NEMOTRON_FIX_SCRIPT="/tmp/nemoclaw-nemotron-inference-fix.js" _NEMOTRON_FIX_SOURCE="/usr/local/lib/nemoclaw/preloads/nemotron-inference-fix.js" -emit_sandbox_sourced_file "$_NEMOTRON_FIX_SCRIPT" <"$_NEMOTRON_FIX_SOURCE" -export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_NEMOTRON_FIX_SCRIPT" # mDNS / ciao network interface guard. # The @homebridge/ciao mDNS library calls os.networkInterfaces() which @@ -2641,8 +2796,6 @@ export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_NEMOTRON_FIX_SCR # Ref: https://github.com/NVIDIA/NemoClaw/issues/2340 _CIAO_GUARD_SCRIPT="/tmp/nemoclaw-ciao-network-guard.js" _CIAO_GUARD_SOURCE="/usr/local/lib/nemoclaw/preloads/ciao-network-guard.js" -emit_sandbox_sourced_file "$_CIAO_GUARD_SCRIPT" <"$_CIAO_GUARD_SOURCE" -export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_CIAO_GUARD_SCRIPT" # WebSocket CONNECT tunnel fix (NemoClaw#1570). # The `ws` library calls https.request() for wss:// WebSocket upgrades. @@ -2654,12 +2807,6 @@ export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_CIAO_GUARD_SCRIP # script itself guards on the env var). _WS_FIX_SOURCE="/usr/local/lib/nemoclaw/preloads/ws-proxy-fix.js" _WS_FIX_SCRIPT="/tmp/nemoclaw-ws-proxy-fix.js" -if [ -f "$_WS_FIX_SOURCE" ]; then - # Copy to /tmp so the sandbox user can read it — /usr/local/lib/ may be - # Landlock-restricted in some runtimes. Same pattern as the other preloads. - emit_sandbox_sourced_file "$_WS_FIX_SCRIPT" <"$_WS_FIX_SOURCE" - export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_WS_FIX_SCRIPT" -fi # ── Seccomp syscall guard ───────────────────────────────────── # OpenShell ≥0.0.36 seccomp policy blocks syscalls like getifaddrs @@ -2674,8 +2821,38 @@ fi # seccomp-blocked syscalls affect all sandboxes, not just Slack ones. _SECCOMP_GUARD_SCRIPT="/tmp/nemoclaw-seccomp-guard.js" _SECCOMP_GUARD_SOURCE="/usr/local/lib/nemoclaw/preloads/seccomp-guard.js" -emit_sandbox_sourced_file "$_SECCOMP_GUARD_SCRIPT" <"$_SECCOMP_GUARD_SOURCE" -export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--require $_SECCOMP_GUARD_SCRIPT" + +# Stage the immutable, image-packaged preload set into /tmp. Startup and +# authenticated PID 1 recovery share this exact path so a pod-recreate-style +# /tmp wipe cannot drift from the initial security boundary. The shared emit +# helper atomically replaces each target as root:root 0444 in root mode. +install_core_runtime_preloads() { + emit_sandbox_sourced_file "$_SANDBOX_SAFETY_NET" <"$_SANDBOX_SAFETY_NET_SOURCE" || return 1 + append_node_require_once "$_SANDBOX_SAFETY_NET" + + if [ "${NODE_USE_ENV_PROXY:-}" = "1" ]; then + emit_sandbox_sourced_file "$_PROXY_FIX_SCRIPT" <"$_PROXY_FIX_SOURCE" || return 1 + append_node_require_once "$_PROXY_FIX_SCRIPT" + fi + + emit_sandbox_sourced_file "$_NEMOTRON_FIX_SCRIPT" <"$_NEMOTRON_FIX_SOURCE" || return 1 + append_node_require_once "$_NEMOTRON_FIX_SCRIPT" + + emit_sandbox_sourced_file "$_CIAO_GUARD_SCRIPT" <"$_CIAO_GUARD_SOURCE" || return 1 + append_node_require_once "$_CIAO_GUARD_SCRIPT" + + if [ -f "$_WS_FIX_SOURCE" ]; then + # Copy to /tmp so the sandbox user can read it under Landlock-constrained + # runtimes. The missing optional source keeps the historical no-op. + emit_sandbox_sourced_file "$_WS_FIX_SCRIPT" <"$_WS_FIX_SOURCE" || return 1 + append_node_require_once "$_WS_FIX_SCRIPT" + fi + + emit_sandbox_sourced_file "$_SECCOMP_GUARD_SCRIPT" <"$_SECCOMP_GUARD_SOURCE" || return 1 + append_node_require_once "$_SECCOMP_GUARD_SCRIPT" +} + +install_core_runtime_preloads || exit 1 # OpenShell re-injects narrow NO_PROXY/no_proxy=127.0.0.1,localhost,::1 every # time a user connects via `openshell sandbox connect`. Dynamic connect-session @@ -3803,6 +3980,11 @@ start_plugin_registry_refresh() { fi ) & PLUGIN_REFRESH_PID=$! + if ! capture_openclaw_pid_start_identity "$PLUGIN_REFRESH_PID" PLUGIN_REFRESH_PID_START_IDENTITY; then + # The best-effort refresh may legitimately finish before PID 1 can read + # its stat record. An uncaptured PID is never admitted or signalled. + PLUGIN_REFRESH_PID_START_IDENTITY="" + fi } # Watchdog for the in-container gateway HTTP listener (#4710). OpenClaw's @@ -3820,8 +4002,7 @@ start_plugin_registry_refresh() { # boots stay the respawn loop's and HEALTHCHECK's job. # PID-reuse / tamper defense: only kill a process whose cmdline still looks -# like the OpenClaw gateway. Same pattern family as the host-side recovery -# script (src/lib/agent/runtime.ts): matches the launch argv +# like the OpenClaw gateway. Match the PID 1 launch argv # ("... openclaw gateway run --port N") and the rewritten process titles # ("openclaw-gateway", bare "openclaw"). gateway_pid_is_openclaw_gateway() { @@ -3844,7 +4025,8 @@ gateway_watchdog_positive_int_ok() { start_gateway_serving_watchdog() { ( - local interval refused_threshold armed=0 refused_streak=0 pid last_pid="" rc msg + local interval refused_threshold armed=0 refused_streak=0 + local pid start_identity extra tracked_identity last_identity="" rc msg interval="${NEMOCLAW_GATEWAY_WATCHDOG_INTERVAL_SECONDS:-30}" refused_threshold="${NEMOCLAW_GATEWAY_WATCHDOG_REFUSED_THRESHOLD:-4}" # Both knobs must be positive integers: a zero/garbage interval would @@ -3863,26 +4045,44 @@ start_gateway_serving_watchdog() { [ -n "${_DASHBOARD_PORT:-}" ] || exit 0 while :; do sleep "$interval" - pid="$(cat "$GATEWAY_PID_FILE" 2>/dev/null)" || pid="" + pid="" + start_identity="" + extra="" + IFS=' ' read -r pid start_identity extra <"$GATEWAY_PID_FILE" 2>/dev/null || true case "$pid" in '' | *[!0-9]*) - last_pid="" + last_identity="" armed=0 refused_streak=0 continue ;; esac + case "$start_identity" in + '' | *[!0-9]*) + last_identity="" + armed=0 + refused_streak=0 + continue + ;; + esac + if [ -n "$extra" ]; then + last_identity="" + armed=0 + refused_streak=0 + continue + fi + tracked_identity="${pid}:${start_identity}" # A respawned gateway must earn its own armed state — never inherit - # the previous PID's serve history, or a booting replacement could be - # killed for refusals that belong to its predecessor. - if [ "$pid" != "$last_pid" ]; then - last_pid="$pid" + # the previous process identity's serve history, even if the kernel has + # already recycled the same numeric PID for the replacement. + if [ "$tracked_identity" != "$last_identity" ]; then + last_identity="$tracked_identity" armed=0 refused_streak=0 fi - if ! kill -0 "$pid" 2>/dev/null; then + if ! openclaw_supervised_pid_is_live "$pid" "$start_identity"; then # Process exit is the respawn loop's signal, not ours. - last_pid="" + last_identity="" armed=0 refused_streak=0 continue @@ -3906,6 +4106,13 @@ start_gateway_serving_watchdog() { refused_streak=0 continue fi + if ! openclaw_supervised_pid_is_live "$pid" "$start_identity"; then + echo "[gateway-watchdog] pid $pid start identity changed; not killing (#4710)" >&2 + last_identity="" + armed=0 + refused_streak=0 + continue + fi msg="[gateway-watchdog] CRITICAL: gateway pid $pid is alive but dropped its HTTP listener on port ${_DASHBOARD_PORT} ($refused_streak consecutive refused probes); killing it so the respawn loop can relaunch (#4710)" echo "$msg" >&2 # _NEMOCLAW_GATEWAY_LOG is a test seam; production always appends to @@ -3913,10 +4120,10 @@ start_gateway_serving_watchdog() { echo "$msg" >>"${_NEMOCLAW_GATEWAY_LOG:-/tmp/gateway.log}" 2>/dev/null || true kill -TERM "$pid" 2>/dev/null || true for _ in 1 2 3 4 5 6 7 8 9 10; do - kill -0 "$pid" 2>/dev/null || break + openclaw_supervised_pid_is_live "$pid" "$start_identity" || break sleep 1 done - if kill -0 "$pid" 2>/dev/null; then + if openclaw_supervised_pid_is_live "$pid" "$start_identity"; then kill -KILL "$pid" 2>/dev/null || true fi armed=0 @@ -3924,10 +4131,522 @@ start_gateway_serving_watchdog() { done ) & GATEWAY_WATCHDOG_PID=$! + if ! capture_openclaw_pid_start_identity "$GATEWAY_WATCHDOG_PID" GATEWAY_WATCHDOG_PID_START_IDENTITY; then + echo "[gateway-watchdog] could not capture watchdog process identity" >&2 + return 1 + fi +} + +openclaw_gateway_pid_owns_listener() { + local pid="$1" + local port="$2" + if [ "$(id -u)" -ne 0 ]; then + gateway_control_pid_owns_tcp_listener "$pid" "$port" + return $? + fi + # shellcheck disable=SC2016 # positional args expand in the inner bash + "${STEP_DOWN_PREFIX_GATEWAY[@]}" env -u BASH_ENV \ + bash --noprofile --norc -c \ + 'source "$1"; gateway_control_pid_owns_tcp_listener "$2" "$3"' \ + bash "$_GATEWAY_SUPERVISOR" "$pid" "$port" +} + +openclaw_gateway_healthy() { + local pid="$1" + local expected_identity="$2" + local code + openclaw_supervised_pid_is_live "$pid" "$expected_identity" || return 1 + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 "http://127.0.0.1:${_DASHBOARD_PORT}/health" 2>/dev/null || true)" + case "$code" in + 200 | 401) + openclaw_supervised_pid_is_live "$pid" "$expected_identity" \ + && openclaw_gateway_pid_owns_listener "$pid" "$_DASHBOARD_PORT" \ + && openclaw_supervised_pid_is_live "$pid" "$expected_identity" + ;; + *) return 1 ;; + esac +} + +wait_for_openclaw_gateway_internal() { + local pid="$1" + local expected_identity="$2" + local deadline=$((SECONDS + 90)) + while [ "$SECONDS" -lt "$deadline" ]; do + openclaw_supervised_pid_is_live "$pid" "$expected_identity" || return 1 + openclaw_gateway_healthy "$pid" "$expected_identity" && return 0 + sleep 1 + done + return 1 +} + +launch_openclaw_gateway() { + mark_in_container_gateway + nohup "${STEP_DOWN_PREFIX_GATEWAY[@]}" sh -c \ + 'umask 0007; exec "$@" >>/tmp/gateway.log 2>&1' sh \ + "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" & + GATEWAY_PID=$! + if ! capture_openclaw_pid_start_identity "$GATEWAY_PID" GATEWAY_PID_START_IDENTITY; then + # An uncaptured numeric PID is never safe to signal: Bash may already have + # reaped the short-lived child and the kernel may have reused its PID. Fail + # PID 1 so the container/runtime tears down any surviving untracked child. + GATEWAY_PID=0 + GATEWAY_PID_START_IDENTITY="" + clear_gateway_pid_record + echo "[gateway] could not capture gateway process identity" >&2 + exit 1 + fi + record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" + # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh + SANDBOX_WAIT_PID="$GATEWAY_PID" + echo "[gateway] openclaw gateway launched as 'gateway' user (pid $GATEWAY_PID)" >&2 +} + +openclaw_supervised_aux_pid_is_live() { + local pid="$1" + local expected_identity="$2" + openclaw_supervised_pid_is_live "$pid" "$expected_identity" +} + +stop_openclaw_supervised_gateway() { + local pid="$1" + local expected_identity="$2" + openclaw_supervised_pid_is_live "$pid" "$expected_identity" || return 1 + gateway_control_stop_tracked_pid "$pid" "$expected_identity" || return 1 + if kill -0 "$pid" 2>/dev/null; then + # The shared helper returns success when a later identity read says the + # numeric PID changed. Before clearing the gateway identity or relaunching, + # require the stronger postcondition that no process occupies that PID. + echo "[SECURITY] OpenClaw gateway pid ${pid} remains live after tracked stop; refusing to treat it as stopped" >&2 + return 1 + fi +} + +refresh_openclaw_supervised_child_pids() { + SANDBOX_CHILD_PIDS=() + openclaw_supervised_pid_is_live \ + "${GATEWAY_PID:-}" "${GATEWAY_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_PID") + openclaw_supervised_aux_pid_is_live \ + "${AUTO_PAIR_PID:-}" "${AUTO_PAIR_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$AUTO_PAIR_PID") + openclaw_supervised_aux_pid_is_live \ + "${GATEWAY_LOG_TAIL_PID:-}" "${GATEWAY_LOG_TAIL_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") + openclaw_supervised_aux_pid_is_live \ + "${GATEWAY_LOG_PERSIST_PID:-}" "${GATEWAY_LOG_PERSIST_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_PERSIST_PID") + openclaw_supervised_aux_pid_is_live \ + "${PLUGIN_REFRESH_PID:-}" "${PLUGIN_REFRESH_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$PLUGIN_REFRESH_PID") + openclaw_supervised_aux_pid_is_live \ + "${GATEWAY_WATCHDOG_PID:-}" "${GATEWAY_WATCHDOG_PID_START_IDENTITY:-}" \ + && SANDBOX_CHILD_PIDS+=("$GATEWAY_WATCHDOG_PID") + return 0 +} + +mark_openclaw_gateway_stopped() { + GATEWAY_PID=0 + GATEWAY_PID_START_IDENTITY="" + [ -n "${GATEWAY_PID_FILE:-}" ] && clear_gateway_pid_record + # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh + SANDBOX_WAIT_PID="" + refresh_openclaw_supervised_child_pids +} + +stop_openclaw_gateway_fail_closed() { + if ! stop_openclaw_supervised_gateway \ + "${GATEWAY_PID:-0}" "${GATEWAY_PID_START_IDENTITY:-}"; then + echo "[CRITICAL] OpenClaw gateway revocation could not prove and stop the tracked child; exiting PID 1 for whole-container cleanup without signaling the unproven PID" >&2 + exit 1 + fi + mark_openclaw_gateway_stopped +} + +OPENCLAW_REAP_EXIT_STATUS=0 +openclaw_reap_exited_gateway() { + local pid="${GATEWAY_PID:-0}" + local expected_start_identity="${GATEWAY_PID_START_IDENTITY:-}" + local current_start_identity state + local rc=0 + case "$pid" in + '' | 0 | 1 | *[!0-9]*) return 1 ;; + esac + [ -n "$expected_start_identity" ] || return 1 + + current_start_identity="$(openclaw_pid_start_identity "$pid" 2>/dev/null || true)" + if [ -n "$current_start_identity" ] \ + && [ "$current_start_identity" != "$expected_start_identity" ]; then + echo "[SECURITY] OpenClaw gateway pid $pid no longer matches its captured start identity; refusing to poll or reap it" >&2 + return 2 + fi + + # kill -0 also succeeds for zombies. Only that exact matching zombie is + # safe to reap. A live process, or a process whose state/identity cannot be + # proven, must not send PID 1 into an unbounded wait on a recycled PID. + if kill -0 "$pid" 2>/dev/null; then + state="$(gateway_control_pid_state "$pid" 2>/dev/null || true)" + case "$state" in + Z*) [ "$current_start_identity" = "$expected_start_identity" ] || return 2 ;; + *) + if [ "${GATEWAY_CONTROL_SIGNAL_PENDING:-0}" -eq 1 ] \ + && openclaw_supervised_pid_is_live "$pid" "$expected_start_identity" \ + && gateway_pid_is_openclaw_gateway "$pid"; then + return 3 + fi + echo "[SECURITY] OpenClaw gateway pid $pid cannot be proven exited with its captured start identity; refusing to reap it" >&2 + return 2 + ;; + esac + fi + + wait "$pid" 2>/dev/null || rc=$? + # USR1 may interrupt wait without reaping the exact tracked child. Leave its + # identity intact so the authenticated request handler can stop it. + if [ "${GATEWAY_CONTROL_SIGNAL_PENDING:-0}" -eq 1 ] \ + && openclaw_supervised_pid_is_live "$pid" "$expected_start_identity" \ + && gateway_pid_is_openclaw_gateway "$pid"; then + return 3 + fi + OPENCLAW_REAP_EXIT_STATUS="$rc" + mark_openclaw_gateway_stopped +} + +cleanup_openclaw_on_signal() { + # Revalidate every PID immediately before the shared cleanup helper signals + # it. Clear the primary wait PID too if the tracked gateway identity has + # disappeared or the numeric PID was recycled. + if ! openclaw_supervised_pid_is_live \ + "${GATEWAY_PID:-}" "${GATEWAY_PID_START_IDENTITY:-}"; then + SANDBOX_WAIT_PID="" + fi + refresh_openclaw_supervised_child_pids + cleanup_on_signal +} + +OPENCLAW_RESTART_FAILURE_CODE=internal +_OPENCLAW_CONFIG_GUARD=/usr/local/lib/nemoclaw/openclaw-config-guard.py +_OPENCLAW_STATE_DIR_GUARD=/usr/local/lib/nemoclaw/state-dir-guard.py +OPENCLAW_CONFIG_GUARD_LAST_OUTPUT="" +run_openclaw_config_guard() { + local action="$1" + local startup_owner=0 + local arg output_file rc + shift + for arg in "$@"; do + [ "$arg" = "--startup-owner" ] && startup_owner=1 + done + if [ "$startup_owner" -eq 1 ]; then + # The readiness contract authenticates this helper as a direct PID 1 + # child. A `timeout` wrapper or command substitution would become Python's + # parent and invalidate that identity, so capture through a root-private + # file while invoking Python directly. + install -d -o root -g root -m 700 /run/nemoclaw || return 1 + output_file="/run/nemoclaw/.openclaw-config-guard.$$.output" + : >"$output_file" + chmod 600 "$output_file" + rc=0 + python3 -I "$_OPENCLAW_CONFIG_GUARD" "$action" \ + --config-dir /sandbox/.openclaw "$@" >"$output_file" 2>&1 || rc=$? + OPENCLAW_CONFIG_GUARD_LAST_OUTPUT="$(<"$output_file")" + rm -f "$output_file" + if [ "$rc" -ne 0 ]; then + printf '[config-guard] %s failed: %s\n' "$action" "$OPENCLAW_CONFIG_GUARD_LAST_OUTPUT" >&2 + return "$rc" + fi + return 0 + fi + OPENCLAW_CONFIG_GUARD_LAST_OUTPUT="$( + timeout --signal=TERM --kill-after=5s 5m \ + python3 -I "$_OPENCLAW_CONFIG_GUARD" "$action" \ + --config-dir /sandbox/.openclaw "$@" 2>&1 + )" || { + printf '[config-guard] %s failed: %s\n' "$action" "$OPENCLAW_CONFIG_GUARD_LAST_OUTPUT" >&2 + return 1 + } +} + +restore_openclaw_restart_config() { + run_openclaw_config_guard unseal-restart \ + || run_openclaw_config_guard recover +} + +cleanup_openclaw_gateway_locks() { + timeout --signal=TERM --kill-after=1s 5s python3 -I - <<'PYLOCKS' +import os +import re +import stat +import sys +import time + +deadline = time.monotonic() + 3 +parent_limit = 64 +entry_limit = 10000 +lock_limit = 128 +lock_pattern = re.compile(r"gateway[.][^/]+[.]lock\Z") +directory_flags = ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) +) +tmp_fd = os.open("/tmp", directory_flags) +tmp_stat = os.fstat(tmp_fd) +parents = 0 +locks = 0 +observed = 0 +try: + with os.scandir(tmp_fd) as entries: + for entry in entries: + observed += 1 + if observed > entry_limit or time.monotonic() > deadline: + raise RuntimeError("bounded /tmp gateway-lock inventory exceeded") + if not entry.name.startswith("openclaw-"): + continue + parents += 1 + if parents > parent_limit: + raise RuntimeError("too many OpenClaw lock directories") + parent_fd = os.open(entry.name, directory_flags, dir_fd=tmp_fd) + try: + parent_stat = os.fstat(parent_fd) + if parent_stat.st_dev != tmp_stat.st_dev: + print( + f"[gateway] refusing cross-device lock directory: /tmp/{entry.name}", + file=sys.stderr, + ) + continue + child_observed = 0 + with os.scandir(parent_fd) as children: + for child in children: + child_observed += 1 + if child_observed > entry_limit or time.monotonic() > deadline: + raise RuntimeError("bounded gateway-lock directory inventory exceeded") + if not lock_pattern.fullmatch(child.name): + continue + locks += 1 + if locks > lock_limit: + raise RuntimeError("too many gateway lock entries") + metadata = os.stat( + child.name, dir_fd=parent_fd, follow_symlinks=False + ) + if ( + metadata.st_dev != parent_stat.st_dev + or not stat.S_ISREG(metadata.st_mode) + ): + print( + f"[gateway] refusing non-regular lock entry: /tmp/{entry.name}/{child.name}", + file=sys.stderr, + ) + continue + os.unlink(child.name, dir_fd=parent_fd) + os.fsync(parent_fd) + finally: + os.close(parent_fd) +finally: + os.close(tmp_fd) +PYLOCKS +} + +openclaw_runtime_guard_chain_complete() { + local targets=( + "$_SANDBOX_SAFETY_NET" + "$_NEMOTRON_FIX_SCRIPT" + "$_CIAO_GUARD_SCRIPT" + "$_SECCOMP_GUARD_SCRIPT" + "$_RUNTIME_SHELL_ENV_FILE" + ) + local target + [ "${NODE_USE_ENV_PROXY:-}" = "1" ] && targets+=("$_PROXY_FIX_SCRIPT") + [ -f "$_WS_FIX_SOURCE" ] && targets+=("$_WS_FIX_SCRIPT") + for target in "${targets[@]}"; do + [ -f "$target" ] && [ ! -L "$target" ] || return 1 + done +} + +restore_openclaw_runtime_guard_chain() { + if ! openclaw_runtime_guard_chain_complete; then + echo "[gateway-recovery] WARNING: /tmp guard chain missing or unsafe - restoring library guards from packaged preloads (#2478/#2701)" >&2 + fi + + # Preserve startup ordering: immutable core preloads first, then the + # manifest-declared messaging layer, then the shell environment that refers + # to both. Permission validation is the final gate before any relaunch. + install_core_runtime_preloads || return 1 + write_messaging_runtime_setup_plan || return 1 + install_messaging_runtime_preloads || return 1 + verify_messaging_runtime_secret_scans || return 1 + write_runtime_shell_env || return 1 + validate_nemoclaw_tmp_permissions || return 1 +} + +prepare_openclaw_automatic_respawn() { + if restore_openclaw_runtime_guard_chain; then + return 0 + fi + echo "[gateway] CRITICAL: runtime guard restoration failed; refusing automatic respawn" >&2 + return 1 +} + +prepare_openclaw_gateway_restart() { + OPENCLAW_RESTART_FAILURE_CODE=unsafe-config + # Restart preflight is deliberately read-only. The gateway and sandbox code + # may still hold descriptors into a mutable tree, so pathname recovery, + # chmod/chown normalization, and placeholder rewrites here would be root + # TOCTOU primitives. The descriptor guard validates the exact config/hash + # pair and refuses incoherent or substituted paths; mutation belongs to a + # serialized host config command before restart. + run_openclaw_config_guard preflight-restart || return 1 + OPENCLAW_RESTART_FAILURE_CODE=preload-missing + restore_openclaw_runtime_guard_chain || return 1 +} + +retire_openclaw_supervised_gateway() { + local pid="$1" + local expected_identity="$2" + local reap_status=0 + + # A recover request can arrive after the respawn loop has already reaped the + # failed child and entered its backoff. Only the canonical stopped state may + # bypass retirement; every nonzero tracked PID must still be stopped or + # identity-safely reaped before a replacement is launched. + [ "${GATEWAY_PID:-0}" = "$pid" ] \ + && [ "${GATEWAY_PID_START_IDENTITY:-}" = "$expected_identity" ] \ + || return 1 + if [ "$pid" = "0" ] \ + && [ -z "$expected_identity" ] \ + && [ -z "${SANDBOX_WAIT_PID:-}" ]; then + return 0 + fi + if openclaw_supervised_pid_is_live "$pid" "$expected_identity" \ + && stop_openclaw_supervised_gateway "$pid" "$expected_identity"; then + return 0 + fi + openclaw_reap_exited_gateway || reap_status=$? + [ "$reap_status" -eq 0 ] \ + && [ "${GATEWAY_PID:-0}" = "0" ] \ + && [ -z "${GATEWAY_PID_START_IDENTITY:-}" ] \ + && [ -z "${SANDBOX_WAIT_PID:-}" ] +} + +handle_openclaw_gateway_control_request() { + gateway_control_take_request || return 1 + local old_pid="${GATEWAY_PID:-0}" + local old_identity="${GATEWAY_PID_START_IDENTITY:-}" + + if [ "$GATEWAY_CONTROL_ACTION" = "probe" ]; then + if ! run_openclaw_config_guard preflight-restart; then + gateway_control_fail unsafe-config "$old_pid" + return 1 + fi + if ! openclaw_gateway_healthy "$old_pid" "$old_identity"; then + gateway_control_fail health-timeout "$old_pid" + return 1 + fi + gateway_control_complete already-running "$old_pid" "$old_pid" + return 0 + fi + + if [ "$GATEWAY_CONTROL_ACTION" = "recover" ] \ + && openclaw_gateway_healthy "$old_pid" "$old_identity"; then + if ! run_openclaw_config_guard recover; then + gateway_control_fail unsafe-config "$old_pid" + return 1 + fi + gateway_control_complete already-running "$old_pid" "$old_pid" + return 0 + fi + + # Validate every mutable/security input while the currently healthy gateway + # is still serving. Refusal must not turn a recoverable config error into an + # outage. + if ! prepare_openclaw_gateway_restart; then + gateway_control_fail "$OPENCLAW_RESTART_FAILURE_CODE" "$old_pid" + return 1 + fi + + # Seal while the old healthy gateway is still serving. This fresh-replaces + # the canonical config/hash pair and revokes old writable descriptors before + # any outage is introduced. The journal records whether the original posture + # was mutable or shields-locked so unseal restores it exactly. + if ! run_openclaw_config_guard seal-restart; then + if ! restore_openclaw_restart_config; then + echo "[SECURITY] OpenClaw restart seal failed and deterministic recovery also failed; stopping the old gateway to revoke stale config descriptors" >&2 + stop_openclaw_gateway_fail_closed + fi + gateway_control_fail unsafe-config "$old_pid" + return 1 + fi + + if ! retire_openclaw_supervised_gateway "$old_pid" "$old_identity"; then + restore_openclaw_restart_config || true + gateway_control_fail internal "$old_pid" + return 1 + fi + mark_openclaw_gateway_stopped + cleanup_openclaw_gateway_locks \ + || echo "[gateway] warning: bounded stale gateway-lock cleanup was incomplete" >&2 + + if ! launch_openclaw_gateway; then + stop_openclaw_gateway_fail_closed + restore_openclaw_restart_config || true + gateway_control_fail health-timeout "$old_pid" + return 1 + fi + # Register the replacement before its bounded health wait. A container stop + # in this window must signal the new child, never the already-reaped old PID. + refresh_openclaw_supervised_child_pids + if ! wait_for_openclaw_gateway_internal \ + "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY"; then + stop_openclaw_gateway_fail_closed + restore_openclaw_restart_config || true + gateway_control_fail health-timeout "$old_pid" + return 1 + fi + + if ! restore_openclaw_restart_config; then + # The replacement is healthy and the canonical pair remains fail-closed, + # but the original mutable/locked posture could not be restored. Keep the + # service running and make the host operation fail loudly for recovery. + refresh_openclaw_supervised_child_pids + gateway_control_fail unsafe-config "$old_pid" + return 1 + fi + + # PLUGIN_REFRESH_PID remains set after its best-effort background job exits. + # Never signal that potentially stale PID during a later gateway restart: + # PID reuse could otherwise terminate an unrelated process. A still-running + # prior refresh is harmless and will exit on its own. + start_plugin_registry_refresh + refresh_openclaw_supervised_child_pids + gateway_control_complete ok "$old_pid" "$GATEWAY_PID" } # ── Main ───────────────────────────────────────────────────────── +# Begin the root PID 1 readiness lease before any startup path reads or mutates +# OpenClaw config. Recovery runs before the locked-parent discriminator so a +# crash in a prior config write/restart/handoff can complete deterministically. +if [ "$(id -u)" -eq 0 ]; then + run_openclaw_config_guard revoke-startup-ready --startup-owner || exit 1 + run_openclaw_config_guard recover --startup-owner || exit 1 + if [ "$(stat -c '%a %U:%G' /sandbox/.openclaw 2>/dev/null || true)" = "500 root:root" ]; then + echo "[config-guard] resuming interrupted recursive OpenClaw state lock" >&2 + timeout --signal=TERM --kill-after=5s 12m \ + python3 -I "$_OPENCLAW_STATE_DIR_GUARD" lock \ + --config-dir /sandbox/.openclaw || exit 1 + fi +fi + +# A root-owned config directory is the shields-up discriminator. Its parent +# must be sticky and root-owned too; otherwise the sandbox identity can rename +# the entire `.openclaw` entry and replace the pathname with mutable content. +# Refuse before migration or any config read. PID 1 cannot repair this posture +# after startup has failed, so recovery requires a trusted snapshot/recreate. +if [ "$(openclaw_config_dir_owner /sandbox/.openclaw)" = "root" ] \ + && ! openclaw_locked_parent_is_protected; then + echo "[SECURITY] OPENCLAW_LOCKED_PARENT_UNPROTECTED: /sandbox must be root:sandbox 1775 while OpenClaw shields are up; restore from a trusted backup and recreate the sandbox" >&2 + exit 1 +fi + # Migrate legacy symlink layout before anything else reads .openclaw migrate_legacy_layout "/sandbox/.openclaw" "/sandbox/.openclaw-data" "openclaw" || exit 1 @@ -4036,12 +4755,15 @@ if [ "$(id -u)" -ne 0 ]; then mark_in_container_gateway nohup "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >/tmp/gateway.log 2>&1 & GATEWAY_PID=$! - record_gateway_pid "$GATEWAY_PID" + capture_openclaw_pid_start_identity "$GATEWAY_PID" GATEWAY_PID_START_IDENTITY || exit 1 + record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" echo "[gateway] openclaw gateway launched (pid $GATEWAY_PID)" >&2 # Diagnostic: mirror gateway log to PID 1's stderr — see root-mode block # below for rationale (NVIDIA/NemoClaw#2484). { tail -n +1 -F /tmp/gateway.log 2>/dev/null | sed -u 's/^/[gateway-log:] /' >&2; } & GATEWAY_LOG_TAIL_PID=$! + capture_openclaw_pid_start_identity \ + "$GATEWAY_LOG_TAIL_PID" GATEWAY_LOG_TAIL_PID_START_IDENTITY || exit 1 # Persistent mirror: see root-mode block for rationale. start_persistent_gateway_log_mirror || exit 1 start_auto_pair @@ -4050,15 +4772,10 @@ if [ "$(id -u)" -ne 0 ]; then # NOTE: PIDs are collected after launch; a signal arriving between trap # registration and the final append is a small race window (same as before # the shared-library refactor). Acceptable for entrypoint-level cleanup. - SANDBOX_CHILD_PIDS=("$GATEWAY_PID") - [ -n "${AUTO_PAIR_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$AUTO_PAIR_PID") - [ -n "${GATEWAY_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") - [ -n "${GATEWAY_LOG_PERSIST_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_PERSIST_PID") - [ -n "${PLUGIN_REFRESH_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$PLUGIN_REFRESH_PID") - [ -n "${GATEWAY_WATCHDOG_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_WATCHDOG_PID") + refresh_openclaw_supervised_child_pids # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" - trap cleanup_on_signal SIGTERM SIGINT + trap cleanup_openclaw_on_signal SIGTERM SIGINT print_dashboard_urls # Auto-respawn gateway on unexpected death (NVIDIA/NemoClaw#2757). Without @@ -4073,7 +4790,9 @@ if [ "$(id -u)" -ne 0 ]; then # line 33) would otherwise exit PID 1 the instant the gateway returns # non-zero, defeating the respawn loop entirely. RC=0 - wait "$GATEWAY_PID" || RC=$? + EXITED_GATEWAY_PID="$GATEWAY_PID" + wait "$EXITED_GATEWAY_PID" || RC=$? + mark_openclaw_gateway_stopped if [ "$RC" -eq 0 ]; then exit 0 fi @@ -4088,14 +4807,16 @@ if [ "$(id -u)" -ne 0 ]; then if [ "$RESPAWN_COUNT" -ge 5 ]; then echo "[gateway] CRITICAL: $RESPAWN_COUNT respawns in 60s window — gateway likely unstable; check /tmp/gateway.log" >&2 fi - echo "[gateway] pid $GATEWAY_PID exited (rc=$RC); respawning (#$RESPAWN_COUNT in 60s window) in 2s" >&2 + echo "[gateway] pid $EXITED_GATEWAY_PID exited (rc=$RC); respawning (#$RESPAWN_COUNT in 60s window) in 2s" >&2 sleep 2 + prepare_openclaw_automatic_respawn || exit 1 nohup "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >>/tmp/gateway.log 2>&1 & GATEWAY_PID=$! - record_gateway_pid "$GATEWAY_PID" + capture_openclaw_pid_start_identity "$GATEWAY_PID" GATEWAY_PID_START_IDENTITY || exit 1 + record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" - SANDBOX_CHILD_PIDS+=("$GATEWAY_PID") + refresh_openclaw_supervised_child_pids echo "[gateway] respawned (pid $GATEWAY_PID)" >&2 done fi @@ -4252,14 +4973,10 @@ validate_nemoclaw_tmp_permissions # SECURITY: The sandbox user cannot kill this process because it runs # under a different UID. The fake-HOME attack no longer works because # the agent cannot restart the gateway with a tampered config. -# Mark the in-container gateway path so the Docker HEALTHCHECK probes it -# rather than short-circuiting to healthy — see mark_in_container_gateway -# comment near the top of this file for the #4710 rationale. -mark_in_container_gateway -nohup "${STEP_DOWN_PREFIX_GATEWAY[@]}" "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >/tmp/gateway.log 2>&1 & -GATEWAY_PID=$! -record_gateway_pid "$GATEWAY_PID" -echo "[gateway] openclaw gateway launched as 'gateway' user (pid $GATEWAY_PID)" >&2 +# Marking, privilege step-down, log redirection, and PID recording are kept in +# one reusable launch primitive so PID 1 owns initial start, crash respawn, and +# host-requested restart identically. +launch_openclaw_gateway # Diagnostic: mirror gateway log to PID 1's stderr so its content surfaces in # docker logs. /tmp/gateway.log is otherwise only readable from inside the @@ -4270,6 +4987,8 @@ echo "[gateway] openclaw gateway launched as 'gateway' user (pid $GATEWAY_PID)" # Ref: NVIDIA/NemoClaw#2484 (TC-SBX-02 hang investigation) { tail -n +1 -F /tmp/gateway.log 2>/dev/null | sed -u 's/^/[gateway-log:] /' >&2; } & GATEWAY_LOG_TAIL_PID=$! +capture_openclaw_pid_start_identity \ + "$GATEWAY_LOG_TAIL_PID" GATEWAY_LOG_TAIL_PID_START_IDENTITY || exit 1 # Persistent mirror: append /tmp/gateway.log content to a file under # /sandbox/.openclaw/logs which is volume-mounted by openshell and @@ -4303,15 +5022,19 @@ start_gateway_serving_watchdog # NOTE: PIDs are collected after launch; a signal arriving between trap # registration and the final append is a small race window (same as before # the shared-library refactor). Acceptable for entrypoint-level cleanup. -SANDBOX_CHILD_PIDS=("$GATEWAY_PID") -[ -n "${AUTO_PAIR_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$AUTO_PAIR_PID") -[ -n "${GATEWAY_LOG_TAIL_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_TAIL_PID") -[ -n "${GATEWAY_LOG_PERSIST_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_LOG_PERSIST_PID") -[ -n "${PLUGIN_REFRESH_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$PLUGIN_REFRESH_PID") -[ -n "${GATEWAY_WATCHDOG_PID:-}" ] && SANDBOX_CHILD_PIDS+=("$GATEWAY_WATCHDOG_PID") +refresh_openclaw_supervised_child_pids # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh SANDBOX_WAIT_PID="$GATEWAY_PID" -trap cleanup_on_signal SIGTERM SIGINT +trap cleanup_openclaw_on_signal SIGTERM SIGINT +if ! gateway_control_init; then + echo "[gateway-control] privileged gateway control unavailable" >&2 +fi +if ! run_openclaw_config_guard publish-startup-ready --startup-owner; then + echo "[SECURITY] OpenClaw config readiness lease could not be published; refusing to keep the gateway running" >&2 + stop_openclaw_supervised_gateway \ + "${GATEWAY_PID:-0}" "${GATEWAY_PID_START_IDENTITY:-}" || true + exit 1 +fi print_dashboard_urls # Keep container running by waiting on the gateway process. @@ -4324,11 +5047,35 @@ print_dashboard_urls # window boundary still trigger the >=5 alarm. RESPAWN_TIMES=() while :; do - # `wait` must be guarded with `|| RC=$?` because errexit (set -e on - # line 33) would otherwise exit PID 1 the instant the gateway returns - # non-zero, defeating the respawn loop entirely. - RC=0 - wait "$GATEWAY_PID" || RC=$? + # Poll the tracked child instead of entering an unbounded wait immediately. + # A USR1 that lands just before `wait` would otherwise set the trap flag and + # then leave PID 1 blocked forever because there is no second signal to + # interrupt that wait. + while openclaw_supervised_pid_is_live \ + "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" \ + && [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 0 ]; do + sleep 1 || true + done + if [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 1 ]; then + handle_openclaw_gateway_control_request || true + continue + fi + + EXITED_GATEWAY_PID="$GATEWAY_PID" + REAP_STATUS=0 + openclaw_reap_exited_gateway || REAP_STATUS=$? + if [ "$REAP_STATUS" -eq 3 ]; then + handle_openclaw_gateway_control_request || true + continue + fi + if [ "$REAP_STATUS" -ne 0 ]; then + exit 1 + fi + RC="$OPENCLAW_REAP_EXIT_STATUS" + if [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 1 ]; then + handle_openclaw_gateway_control_request || true + continue + fi if [ "$RC" -eq 0 ]; then exit 0 fi @@ -4343,13 +5090,17 @@ while :; do if [ "$RESPAWN_COUNT" -ge 5 ]; then echo "[gateway] CRITICAL: $RESPAWN_COUNT respawns in 60s window — gateway likely unstable; check /tmp/gateway.log" >&2 fi - echo "[gateway] pid $GATEWAY_PID exited (rc=$RC); respawning (#$RESPAWN_COUNT in 60s window) in 2s" >&2 - sleep 2 - nohup "${STEP_DOWN_PREFIX_GATEWAY[@]}" "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >>/tmp/gateway.log 2>&1 & - GATEWAY_PID=$! - record_gateway_pid "$GATEWAY_PID" - # shellcheck disable=SC2034 # read by cleanup_on_signal from sandbox-init.sh - SANDBOX_WAIT_PID="$GATEWAY_PID" - SANDBOX_CHILD_PIDS+=("$GATEWAY_PID") + echo "[gateway] pid $EXITED_GATEWAY_PID exited (rc=$RC); respawning (#$RESPAWN_COUNT in 60s window) in 2s" >&2 + sleep 2 || true + # A host request can arrive during the crash backoff. Service it before the + # automatic relaunch so PID 1 never launches an untracked extra gateway and + # immediately replaces it again. + if [ "$GATEWAY_CONTROL_SIGNAL_PENDING" -eq 1 ]; then + handle_openclaw_gateway_control_request || true + continue + fi + prepare_openclaw_automatic_respawn || exit 1 + launch_openclaw_gateway + refresh_openclaw_supervised_child_pids echo "[gateway] respawned (pid $GATEWAY_PID)" >&2 done diff --git a/scripts/openclaw-config-guard.py b/scripts/openclaw-config-guard.py new file mode 100755 index 00000000000..b5ebfdba59a --- /dev/null +++ b/scripts/openclaw-config-guard.py @@ -0,0 +1,4201 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Descriptor-safe OpenClaw top-level config shields transitions. + +This helper is deliberately self-contained so the host can invoke the installed +root-only copy or inject the same source through ``python3 -`` into an older +container. It mutates only ``openclaw.json`` and ``.config-hash``. All path +resolution is rooted in directory descriptors and uses ``O_NOFOLLOW``. + +``write-config`` accepts the replacement document on stdin. NemoClaw's current +writers serialize strict JSON, so the helper intentionally uses Python's +trusted standard-library JSON parser and rejects JSON5-only syntax rather than +shipping a second parser into the privileged boundary. +""" + +from __future__ import annotations + +import argparse +import base64 +import binascii +import errno +import fcntl +import grp +import hashlib +import json +import os +import posixpath +import pwd +import re +import secrets +import stat +import struct +import subprocess +import sys +import time +from dataclasses import dataclass +from typing import Literal + + +Action = Literal[ + "preflight", + "preflight-restart", + "lock", + "unlock", + "seal-restart", + "unseal-restart", + "revoke-startup-ready", + "publish-startup-ready", + "write-config", + "recover", +] +StartupIdentity = tuple[int, str, int] +CONFIG_FILES = ("openclaw.json", ".config-hash") +PRODUCTION_CONFIG_DIR = "/sandbox/.openclaw" +MAX_FILE_BYTES = { + "openclaw.json": 16 * 1024 * 1024, + ".config-hash": 64 * 1024, +} +JOURNAL_PATH = "/etc/nemoclaw/openclaw-config-transaction.json" +PERSISTENT_JOURNAL_NAME = ".nemoclaw-config-transaction.json" +MAX_JOURNAL_BYTES = 48 * 1024 * 1024 +MUTEX_PATH = "/run/nemoclaw/openclaw-config-mutation.lock" +MAX_MUTEX_BYTES = 16 * 1024 +STARTUP_READY_PATH = "/run/nemoclaw/openclaw-config-ready.json" +STARTUP_CAPABILITY_PATH = "/run/nemoclaw/openclaw-config-ready-v1.capability.json" +MAX_READY_BYTES = 4096 +PROC_ROOT = "/proc" +MAX_PROC_ENTRIES = 32768 +NEMOCLAW_START_ARGV = (b"nemoclaw-start", b"/usr/local/bin/nemoclaw-start") +OPENSHELL_SUPERVISOR_ARGV0 = b"/opt/openshell/bin/openshell-sandbox" +NODE_BINARY_PATH = "/usr/local/bin/node" +JSON5_MODULE_PATH = "/opt/nemoclaw/node_modules/json5" +JSON5_VALIDATION_TIMEOUT_SECONDS = 5 +INSTALLED_HELPER_PATH = "/usr/local/lib/nemoclaw/openclaw-config-guard.py" +COPY_BUFFER_BYTES = 1024 * 1024 +STABLE_READ_ATTEMPTS = 3 +FS_IMMUTABLE_FL = 0x00000010 +FS_APPEND_FL = 0x00000020 +FS_IOC_GETFLAGS = 0x80086601 +FS_IOC_SETFLAGS = 0x40086602 +SHA256_RECORD = re.compile(r"([0-9a-fA-F]{64}) ([ *])([^\r\n]+)\n?\Z") + + +@dataclass(frozen=True) +class Identity: + root_uid: int + root_gid: int + sandbox_uid: int + sandbox_gid: int + + +@dataclass(frozen=True) +class FileSnapshot: + name: str + dev: int + ino: int + uid: int + gid: int + mode: int + atime_ns: int + mtime_ns: int + ctime_ns: int + size: int + data: bytes + xattrs: tuple[tuple[str, bytes], ...] + inode_flags: int | None + + +@dataclass +class OpenConfig: + config_path: str + parent_path: str + config_name: str + parent_fd: int + config_fd: int + parent_stat: os.stat_result + config_stat: os.stat_result + + def close(self) -> None: + os.close(self.config_fd) + os.close(self.parent_fd) + + +@dataclass +class MutationMutex: + fd: int + parent_fd: int + token: str + exclusive: bool + + def close(self) -> None: + os.close(self.fd) + os.close(self.parent_fd) + + +class GuardError(RuntimeError): + def __init__(self, code: str, path: str, detail: str): + super().__init__(detail) + self.code = code + self.path = path + self.detail = detail + + def as_json(self) -> dict[str, str]: + return { + "type": "issue", + "code": self.code, + "path": self.path, + "detail": self.detail, + } + + +class MutableHandoffError(GuardError): + """A failure after sandbox write access has become irreversible.""" + + +def _stored_file( + snapshot: FileSnapshot, + *, + data: bytes | None = None, + uid: int | None = None, + gid: int | None = None, + mode: int | None = None, + mtime_ns: int | None = None, + inode_flags: int | None = None, +) -> dict[str, object]: + stored_data = snapshot.data if data is None else data + return { + "name": snapshot.name, + "uid": snapshot.uid if uid is None else uid, + "gid": snapshot.gid if gid is None else gid, + "mode": snapshot.mode if mode is None else mode, + "atimeNs": snapshot.atime_ns, + "mtimeNs": snapshot.mtime_ns if mtime_ns is None else mtime_ns, + "data": base64.b64encode(stored_data).decode("ascii"), + "xattrs": [ + [name, base64.b64encode(value).decode("ascii")] + for name, value in snapshot.xattrs + ], + "inodeFlags": snapshot.inode_flags if inode_flags is None else inode_flags, + } + + +def _decode_stored_file(value: object) -> FileSnapshot: + if not isinstance(value, dict): + raise GuardError( + "invalid-journal", JOURNAL_PATH, "stored file is not an object" + ) + name = value.get("name") + if name not in CONFIG_FILES: + raise GuardError("invalid-journal", JOURNAL_PATH, "stored file name is invalid") + try: + uid = int(value["uid"]) + gid = int(value["gid"]) + mode = int(value["mode"]) + atime_ns = int(value["atimeNs"]) + mtime_ns = int(value["mtimeNs"]) + data = base64.b64decode(str(value["data"]), validate=True) + raw_xattrs = value["xattrs"] + raw_flags = value.get("inodeFlags") + inode_flags = None if raw_flags is None else int(raw_flags) + except (KeyError, TypeError, ValueError, binascii.Error) as exc: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "stored file metadata is invalid" + ) from exc + if len(data) > MAX_FILE_BYTES[str(name)]: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "stored file exceeds its size cap" + ) + if not isinstance(raw_xattrs, list): + raise GuardError("invalid-journal", JOURNAL_PATH, "stored xattrs are invalid") + xattrs: list[tuple[str, bytes]] = [] + for entry in raw_xattrs: + if ( + not isinstance(entry, list) + or len(entry) != 2 + or not isinstance(entry[0], str) + ): + raise GuardError("invalid-journal", JOURNAL_PATH, "stored xattr is invalid") + try: + xattrs.append((entry[0], base64.b64decode(str(entry[1]), validate=True))) + except (ValueError, binascii.Error) as exc: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "stored xattr is invalid" + ) from exc + if uid < 0 or gid < 0 or mode < 0 or mode > 0o7777 or atime_ns < 0 or mtime_ns < 0: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "stored metadata is out of range" + ) + return FileSnapshot( + name=str(name), + dev=0, + ino=0, + uid=uid, + gid=gid, + mode=mode, + atime_ns=atime_ns, + mtime_ns=mtime_ns, + ctime_ns=0, + size=len(data), + data=data, + xattrs=tuple(xattrs), + inode_flags=inode_flags, + ) + + +def _directory_flags() -> int: + nofollow = getattr(os, "O_NOFOLLOW", 0) + directory = getattr(os, "O_DIRECTORY", 0) + if not nofollow or not directory: + raise GuardError( + "unsupported-platform", "", "O_NOFOLLOW and O_DIRECTORY are required" + ) + return os.O_RDONLY | nofollow | directory | getattr(os, "O_CLOEXEC", 0) + + +def _file_flags() -> int: + nofollow = getattr(os, "O_NOFOLLOW", 0) + if not nofollow: + raise GuardError("unsupported-platform", "", "O_NOFOLLOW is required") + # O_NONBLOCK prevents a stat->FIFO substitution from hanging the privileged + # helper in open(2); the immediate fstat/inode checks still reject it. + return ( + os.O_RDONLY + | nofollow + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NONBLOCK", 0) + ) + + +def _same_inode(first: os.stat_result, second: os.stat_result) -> bool: + return first.st_dev == second.st_dev and first.st_ino == second.st_ino + + +def _stable_metadata(first: os.stat_result, second: os.stat_result) -> bool: + return ( + _same_inode(first, second) + and first.st_size == second.st_size + and first.st_mtime_ns == second.st_mtime_ns + and first.st_ctime_ns == second.st_ctime_ns + ) + + +def _kind(st: os.stat_result) -> str: + if stat.S_ISREG(st.st_mode): + return "regular file" + if stat.S_ISDIR(st.st_mode): + return "directory" + if stat.S_ISLNK(st.st_mode): + return "symlink" + if stat.S_ISFIFO(st.st_mode): + return "FIFO" + if stat.S_ISSOCK(st.st_mode): + return "socket" + if stat.S_ISCHR(st.st_mode): + return "character device" + if stat.S_ISBLK(st.st_mode): + return "block device" + return "special entry" + + +def _open_absolute_dir(path: str) -> int: + if not posixpath.isabs(path): + raise GuardError("invalid-config-path", path, "path must be absolute") + fd = os.open("/", _directory_flags()) + try: + for component in posixpath.normpath(path).split("/"): + if not component: + continue + before = os.stat(component, dir_fd=fd, follow_symlinks=False) + if not stat.S_ISDIR(before.st_mode): + raise GuardError( + "unsafe-path-component", + path, + f"path component {component!r} is a {_kind(before)}", + ) + next_fd = os.open(component, _directory_flags(), dir_fd=fd) + after = os.fstat(next_fd) + if not _same_inode(before, after): + os.close(next_fd) + raise GuardError( + "entry-raced", + path, + f"path component {component!r} changed while opening", + ) + os.close(fd) + fd = next_fd + return fd + except Exception: + os.close(fd) + raise + + +def _open_private_state_dir( + state_dir: str, identity: Identity, create: bool +) -> int | None: + parent_path = posixpath.dirname(state_dir) + state_name = posixpath.basename(state_dir) + parent_fd = _open_absolute_dir(parent_path) + try: + try: + before = os.stat(state_name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + if not create: + return None + os.mkdir(state_name, 0o700, dir_fd=parent_fd) + os.fsync(parent_fd) + before = os.stat(state_name, dir_fd=parent_fd, follow_symlinks=False) + if not stat.S_ISDIR(before.st_mode): + raise GuardError( + "unsafe-state-path", state_dir, "state parent is not a directory" + ) + fd = os.open(state_name, _directory_flags(), dir_fd=parent_fd) + actual = os.fstat(fd) + if not _same_inode(before, actual): + os.close(fd) + raise GuardError( + "entry-raced", state_dir, "state directory changed while opening" + ) + if ( + actual.st_uid != identity.root_uid + or actual.st_gid != identity.root_gid + or stat.S_IMODE(actual.st_mode) & 0o022 + ): + os.close(fd) + raise GuardError( + "unsafe-state-path", + state_dir, + "state directory must be root-owned and not group/world-writable", + ) + return fd + finally: + os.close(parent_fd) + + +def _open_journal_dir(identity: Identity, create: bool) -> int | None: + return _open_private_state_dir(posixpath.dirname(JOURNAL_PATH), identity, create) + + +def _read_fd_bounded(fd: int, maximum: int, path: str) -> bytes: + os.lseek(fd, 0, os.SEEK_SET) + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(COPY_BUFFER_BYTES, maximum + 1 - total)) + if not chunk: + return b"".join(chunks) + total += len(chunk) + if total > maximum: + raise GuardError("state-too-large", path, "state file exceeds its size cap") + chunks.append(chunk) + + +def _parse_process_start_time(raw: bytes) -> str | None: + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + return None + closing_paren = text.rfind(")") + if closing_paren < 0: + return None + fields_after_comm = text[closing_paren + 2 :].split() + if len(fields_after_comm) <= 19: + return None + return fields_after_comm[19] + + +def _open_proc_root() -> int: + return os.open( + PROC_ROOT, + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + ) + + +def _open_proc_pid(proc_root_fd: int, pid: int | str) -> int: + return os.open( + str(pid), + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + dir_fd=proc_root_fd, + ) + + +def _read_proc_pid_file( + proc_pid_fd: int, name: str, display_path: str +) -> bytes: + fd = os.open( + name, + os.O_RDONLY + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + dir_fd=proc_pid_fd, + ) + try: + return _read_fd_bounded(fd, 64 * 1024, display_path) + finally: + os.close(fd) + + +def _proc_pid_namespace_inode(proc_pid_fd: int) -> int | None: + ns_fd = -1 + try: + ns_fd = os.open( + "ns", + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + dir_fd=proc_pid_fd, + ) + inode = os.stat("pid", dir_fd=ns_fd, follow_symlinks=True).st_ino + return inode if inode > 0 else None + except OSError: + return None + finally: + if ns_fd >= 0: + os.close(ns_fd) + + +def _process_start_time(pid: int) -> str | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + raw = _read_proc_pid_file(proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat") + except OSError: + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + return _parse_process_start_time(raw) + + +def _process_namespace_inode(pid: int) -> int | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + return _proc_pid_namespace_inode(proc_pid_fd) + except OSError: + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _open_mutex_file(identity: Identity) -> tuple[int, int]: + parent_fd = _open_private_state_dir(posixpath.dirname(MUTEX_PATH), identity, True) + if parent_fd is None: + raise GuardError( + "mutex-open-failed", MUTEX_PATH, "mutation mutex directory is missing" + ) + name = posixpath.basename(MUTEX_PATH) + flags = ( + os.O_RDWR + | os.O_CREAT + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + fd = -1 + try: + fd = os.open(name, flags, 0o600, dir_fd=parent_fd) + actual = os.fstat(fd) + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(actual.st_mode) + or actual.st_nlink != 1 + or not _same_inode(actual, current) + or actual.st_uid != identity.root_uid + or actual.st_gid != identity.root_gid + or stat.S_IMODE(actual.st_mode) != 0o600 + or actual.st_size > MAX_MUTEX_BYTES + ): + raise GuardError( + "unsafe-mutation-mutex", + MUTEX_PATH, + "mutation mutex must be a private root-owned regular file", + ) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o600) + os.fsync(parent_fd) + return parent_fd, fd + except Exception: + if fd >= 0: + os.close(fd) + os.close(parent_fd) + raise + + +def _mutex_owner_detail(fd: int) -> str: + try: + raw = _read_fd_bounded(fd, MAX_MUTEX_BYTES, MUTEX_PATH) + owner = json.loads(raw.decode("utf-8")) if raw else {} + except (GuardError, UnicodeDecodeError, json.JSONDecodeError): + return "another guard process owns the mutation mutex" + pid = owner.get("pid") if isinstance(owner, dict) else None + action = owner.get("action") if isinstance(owner, dict) else None + if isinstance(pid, int) and isinstance(action, str): + return f"guard pid {pid} is still running action {action}" + return "another guard process owns the mutation mutex" + + +def _acquire_mutation_mutex( + action: Action, identity: Identity, *, exclusive: bool +) -> MutationMutex: + parent_fd, fd = _open_mutex_file(identity) + operation = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH + try: + try: + fcntl.flock(fd, operation | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise GuardError( + "mutation-in-progress", MUTEX_PATH, _mutex_owner_detail(fd) + ) from exc + token = secrets.token_hex(32) if exclusive else "" + if exclusive: + owner = { + "version": 1, + "token": token, + "action": action, + "pid": os.getpid(), + "pidStartTime": _process_start_time(os.getpid()), + } + payload = ( + json.dumps(owner, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + os.ftruncate(fd, 0) + os.lseek(fd, 0, os.SEEK_SET) + _write_all(fd, payload) + os.fsync(fd) + return MutationMutex( + fd=fd, + parent_fd=parent_fd, + token=token, + exclusive=exclusive, + ) + except Exception: + os.close(fd) + os.close(parent_fd) + raise + + +def _release_mutation_mutex(mutex: MutationMutex) -> None: + try: + if mutex.exclusive: + raw = _read_fd_bounded(mutex.fd, MAX_MUTEX_BYTES, MUTEX_PATH) + try: + owner = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise GuardError( + "unsafe-mutation-mutex", + MUTEX_PATH, + "mutation mutex owner record is corrupt", + ) from exc + recorded = owner.get("token") if isinstance(owner, dict) else None + if not isinstance(recorded, str) or not secrets.compare_digest( + recorded, mutex.token + ): + raise GuardError( + "mutation-mutex-token-mismatch", + MUTEX_PATH, + "mutation mutex owner token changed before release", + ) + os.ftruncate(mutex.fd, 0) + os.fsync(mutex.fd) + fcntl.flock(mutex.fd, fcntl.LOCK_UN) + finally: + mutex.close() + + +def _cmdline_is_nemoclaw_start(raw: bytes) -> bool: + return any(argument in NEMOCLAW_START_ARGV for argument in raw.split(b"\0")) + + +def _cmdline_is_openshell_supervisor(raw: bytes) -> bool: + arguments = raw.split(b"\0") + return bool(arguments and arguments[0] == OPENSHELL_SUPERVISOR_ARGV0) + + +def _parse_process_parent_pid(raw: bytes) -> int | None: + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + return None + closing_paren = text.rfind(")") + if closing_paren < 0: + return None + fields_after_comm = text[closing_paren + 2 :].split() + if len(fields_after_comm) <= 1: + return None + try: + parent_pid = int(fields_after_comm[1], 10) + except ValueError: + return None + return parent_pid if parent_pid >= 0 else None + + +def _process_status_identity(raw: bytes) -> tuple[int, tuple[int, ...]] | None: + try: + lines = raw.decode("ascii").splitlines() + except UnicodeDecodeError: + return None + uid_fields: list[str] | None = None + namespace_pids: tuple[int, ...] | None = None + for line in lines: + if line.startswith("Uid:"): + uid_fields = line.removeprefix("Uid:").split() + elif line.startswith("NSpid:"): + try: + namespace_pids = tuple( + int(value, 10) for value in line.removeprefix("NSpid:").split() + ) + except ValueError: + return None + if uid_fields is None or len(uid_fields) != 4 or not namespace_pids: + return None + try: + effective_uid = int(uid_fields[1], 10) + except ValueError: + return None + if effective_uid < 0 or any(pid <= 0 for pid in namespace_pids): + return None + return effective_uid, namespace_pids + + +def _pid1_is_nemoclaw_start() -> bool: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, 1) + raw = _read_proc_pid_file(proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline") + except (OSError, GuardError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + return _cmdline_is_nemoclaw_start(raw) + + +def _pinned_process_matches_startup_identity( + proc_root_fd: int, + pid: str, + expected_start_time: str, + expected_namespace_inode: int, + expected_effective_uid: int, +) -> bool: + proc_pid_fd = -1 + try: + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + pinned_before = os.fstat(proc_pid_fd) + first_start_time = _parse_process_start_time( + _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + ) + if first_start_time is None or not secrets.compare_digest( + first_start_time, expected_start_time + ): + return False + first_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + if ( + first_status is None + or first_status[0] != expected_effective_uid + or first_status[1][-1] != 1 + ): + return False + cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + if not _cmdline_is_nemoclaw_start(cmdline): + return False + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + if first_namespace_inode != expected_namespace_inode: + return False + second_start_time = _parse_process_start_time( + _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + ) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + second_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + return bool( + second_start_time is not None + and secrets.compare_digest(second_start_time, expected_start_time) + and second_status is not None + and second_status[0] == expected_effective_uid + and second_status[1][-1] == 1 + and _cmdline_is_nemoclaw_start(second_cmdline) + and second_namespace_inode == expected_namespace_inode + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ) + except (OSError, GuardError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + + +def _startup_process_identity_is_live( + expected_start_time: str, + expected_namespace_inode: int, + expected_effective_uid: int = 0, +) -> bool: + if ( + not re.fullmatch(r"[0-9]+", expected_start_time) + or expected_namespace_inode <= 0 + ): + return False + proc_root_fd = -1 + try: + proc_root_fd = _open_proc_root() + observed = 0 + matches = 0 + with os.scandir(proc_root_fd) as entries: + for entry in entries: + if not entry.name.isascii() or not entry.name.isdigit(): + continue + observed += 1 + if observed > MAX_PROC_ENTRIES: + return False + if _pinned_process_matches_startup_identity( + proc_root_fd, + entry.name, + expected_start_time, + expected_namespace_inode, + expected_effective_uid, + ): + matches += 1 + if matches > 1: + return False + return matches == 1 + except OSError: + return False + finally: + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _openshell_supervisor_identity( + expected_effective_uid: int, +) -> tuple[str, int | None] | None: + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, 1) + pinned_before = os.fstat(proc_pid_fd) + first_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline" + ) + first_status = _process_status_identity( + _read_proc_pid_file(proc_pid_fd, "status", f"{PROC_ROOT}/1/status") + ) + first_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/1/stat" + ) + first_start_time = _parse_process_start_time(first_stat) + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/1/cmdline" + ) + second_status = _process_status_identity( + _read_proc_pid_file(proc_pid_fd, "status", f"{PROC_ROOT}/1/status") + ) + second_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/1/stat" + ) + second_start_time = _parse_process_start_time(second_stat) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + if not ( + _cmdline_is_openshell_supervisor(first_cmdline) + and _cmdline_is_openshell_supervisor(second_cmdline) + and first_status is not None + and second_status is not None + and first_status[0] == expected_effective_uid + and second_status[0] == expected_effective_uid + and first_status[1][-1] == 1 + and second_status[1][-1] == 1 + and _parse_process_parent_pid(first_stat) == 0 + and _parse_process_parent_pid(second_stat) == 0 + and first_start_time is not None + and second_start_time is not None + and secrets.compare_digest(first_start_time, second_start_time) + and ( + (first_namespace_inode is None and second_namespace_inode is None) + or ( + first_namespace_inode is not None + and first_namespace_inode == second_namespace_inode + ) + ) + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ): + return None + return first_start_time, first_namespace_inode + except (OSError, GuardError): + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _pinned_process_matches_supervised_nonroot_start( + proc_root_fd: int, + pid: str, + supervisor_identity: tuple[str, int | None], + expected_effective_uid: int, +) -> bool: + proc_pid_fd = -1 + try: + numeric_pid = int(pid, 10) + if numeric_pid <= 1: + return False + proc_pid_fd = _open_proc_pid(proc_root_fd, pid) + pinned_before = os.fstat(proc_pid_fd) + first_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + first_start_time = _parse_process_start_time(first_stat) + first_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + first_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + first_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + second_stat = _read_proc_pid_file( + proc_pid_fd, "stat", f"{PROC_ROOT}/{pid}/stat" + ) + second_start_time = _parse_process_start_time(second_stat) + second_status = _process_status_identity( + _read_proc_pid_file( + proc_pid_fd, "status", f"{PROC_ROOT}/{pid}/status" + ) + ) + second_cmdline = _read_proc_pid_file( + proc_pid_fd, "cmdline", f"{PROC_ROOT}/{pid}/cmdline" + ) + second_namespace_inode = _proc_pid_namespace_inode(proc_pid_fd) + pinned_after = os.fstat(proc_pid_fd) + expected_namespace_inode = supervisor_identity[1] + namespace_matches = ( + expected_namespace_inode is None + and first_namespace_inode == second_namespace_inode + ) or ( + expected_namespace_inode is not None + and first_namespace_inode == expected_namespace_inode + and second_namespace_inode == expected_namespace_inode + ) + return bool( + first_start_time is not None + and second_start_time is not None + and secrets.compare_digest(first_start_time, second_start_time) + and _parse_process_parent_pid(first_stat) == 1 + and _parse_process_parent_pid(second_stat) == 1 + and first_status is not None + and second_status is not None + and first_status[0] == expected_effective_uid + and second_status[0] == expected_effective_uid + and first_status[1][-1] == numeric_pid + and second_status[1][-1] == numeric_pid + and _cmdline_is_nemoclaw_start(first_cmdline) + and _cmdline_is_nemoclaw_start(second_cmdline) + and namespace_matches + and pinned_before.st_dev == pinned_after.st_dev + and pinned_before.st_ino == pinned_after.st_ino + ) + except (OSError, GuardError, ValueError): + return False + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + + +def _openshell_supervised_nonroot_start_is_live( + expected_root_uid: int, + expected_sandbox_uid: int, + required_pid: int | None = None, +) -> bool: + supervisor_identity = _openshell_supervisor_identity(expected_root_uid) + if supervisor_identity is None: + return False + proc_root_fd = -1 + try: + proc_root_fd = _open_proc_root() + observed = 0 + matches = 0 + matched_pid: int | None = None + with os.scandir(proc_root_fd) as entries: + for entry in entries: + if not entry.name.isascii() or not entry.name.isdigit(): + continue + observed += 1 + if observed > MAX_PROC_ENTRIES: + return False + if _pinned_process_matches_supervised_nonroot_start( + proc_root_fd, + entry.name, + supervisor_identity, + expected_sandbox_uid, + ): + matches += 1 + matched_pid = int(entry.name, 10) + if matches > 1: + return False + return bool( + matches == 1 + and (required_pid is None or matched_pid == required_pid) + and _openshell_supervisor_identity(expected_root_uid) + == supervisor_identity + ) + except OSError: + return False + finally: + if proc_root_fd >= 0: + os.close(proc_root_fd) + + +def _pid1_effective_uid() -> int | None: + """Read PID 1's effective UID from a pinned procfs descriptor.""" + + proc_root_fd = -1 + proc_pid_fd = -1 + try: + proc_root_fd = _open_proc_root() + proc_pid_fd = _open_proc_pid(proc_root_fd, 1) + raw = _read_proc_pid_file(proc_pid_fd, "status", f"{PROC_ROOT}/1/status") + except (OSError, GuardError): + return None + finally: + if proc_pid_fd >= 0: + os.close(proc_pid_fd) + if proc_root_fd >= 0: + os.close(proc_root_fd) + for line in raw.splitlines(): + if not line.startswith(b"Uid:"): + continue + fields = line.removeprefix(b"Uid:").split() + if len(fields) != 4: + return None + try: + return int(fields[1], 10) + except ValueError: + return None + return None + + +def _read_pid1_marker_identity( + path: str, identity: Identity +) -> StartupIdentity | None: + parent_fd = _open_private_state_dir(posixpath.dirname(path), identity, False) + if parent_fd is None: + return None + fd = -1 + try: + try: + fd = os.open( + posixpath.basename(path), + _file_flags(), + dir_fd=parent_fd, + ) + except FileNotFoundError: + return None + before = os.fstat(fd) + current = os.stat( + posixpath.basename(path), + dir_fd=parent_fd, + follow_symlinks=False, + ) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or not _same_inode(before, current) + or before.st_uid != identity.root_uid + or before.st_gid != identity.root_gid + or stat.S_IMODE(before.st_mode) != 0o600 + or before.st_size > MAX_READY_BYTES + ): + return None + raw = _read_fd_bounded(fd, MAX_READY_BYTES, path) + after = os.fstat(fd) + if not _stable_metadata(before, after): + return None + try: + marker = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + return None + if not isinstance(marker, dict): + return None + version = marker.get("version") + marker_pid = marker.get("pid") + if ( + not isinstance(version, int) + or isinstance(version, bool) + or not isinstance(marker_pid, int) + or isinstance(marker_pid, bool) + or marker_pid != 1 + or not isinstance(marker.get("pidStartTime"), str) + ): + return None + marker_start_time = marker["pidStartTime"] + if version == 1: + # Version 1 predates OpenShell's outer supervisor PID namespace. + # Preserve it only when the helper still sees the entrypoint as its + # own PID 1; accepting it after a namespace remap would authenticate + # a starttime without the namespace identity needed for uniqueness. + current_start_time = _process_start_time(1) + namespace_inode = _process_namespace_inode(1) + if ( + current_start_time is not None + and namespace_inode is not None + and _pid1_is_nemoclaw_start() + and secrets.compare_digest(marker_start_time, current_start_time) + ): + return (1, marker_start_time, namespace_inode) + return None + namespace_inode = marker.get("pidNamespaceInode") + if ( + version == 2 + and isinstance(namespace_inode, int) + and not isinstance(namespace_inode, bool) + and namespace_inode > 0 + and re.fullmatch(r"[0-9]+", marker_start_time) + ): + return (2, marker_start_time, namespace_inode) + return None + finally: + if fd >= 0: + os.close(fd) + os.close(parent_fd) + + +def _startup_identity_is_live( + startup_identity: StartupIdentity, identity: Identity +) -> bool: + version, start_time, namespace_inode = startup_identity + if version == 1: + current_start_time = _process_start_time(1) + return bool( + current_start_time is not None + and _process_namespace_inode(1) == namespace_inode + and _pid1_is_nemoclaw_start() + and secrets.compare_digest(start_time, current_start_time) + ) + return _startup_process_identity_is_live( + start_time, namespace_inode, identity.root_uid + ) + + +def _pid1_marker_matches(path: str, identity: Identity) -> bool: + startup_identity = _read_pid1_marker_identity(path, identity) + return bool( + startup_identity is not None + and _startup_identity_is_live(startup_identity, identity) + ) + + +def _startup_lease_state(identity: Identity) -> tuple[bool, bool]: + capability_identity = _read_pid1_marker_identity( + STARTUP_CAPABILITY_PATH, identity + ) + ready_identity = _read_pid1_marker_identity(STARTUP_READY_PATH, identity) + identities_match = bool( + capability_identity is not None + and ready_identity is not None + and ready_identity == capability_identity + ) + protocol_active = bool( + capability_identity is not None + and _startup_identity_is_live(capability_identity, identity) + ) + capability_after = _read_pid1_marker_identity( + STARTUP_CAPABILITY_PATH, identity + ) + ready_after = _read_pid1_marker_identity(STARTUP_READY_PATH, identity) + markers_stable = ( + capability_after == capability_identity and ready_after == ready_identity + ) + protocol_active = protocol_active and markers_stable + startup_ready = protocol_active and identities_match + return protocol_active, startup_ready + + +def _startup_ready(identity: Identity) -> bool: + return _startup_lease_state(identity)[1] + + +def _startup_protocol_active(identity: Identity) -> bool: + return _pid1_marker_matches(STARTUP_CAPABILITY_PATH, identity) + + +def _startup_markers_absent(identity: Identity) -> bool: + parent_fd = _open_private_state_dir( + posixpath.dirname(STARTUP_READY_PATH), identity, False + ) + if parent_fd is None: + return True + try: + for path in (STARTUP_CAPABILITY_PATH, STARTUP_READY_PATH): + try: + os.stat( + posixpath.basename(path), + dir_fd=parent_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + continue + return False + return True + finally: + os.close(parent_fd) + + +def _write_pid1_marker(path: str, identity: Identity) -> None: + start_time = _process_start_time(1) + namespace_inode = _process_namespace_inode(1) + if start_time is None or namespace_inode is None: + raise GuardError( + "startup-owner-unknown", + path, + "cannot identify PID 1 startup identity", + ) + payload = ( + json.dumps( + { + "version": 2, + "pid": 1, + "pidStartTime": start_time, + "pidNamespaceInode": namespace_inode, + }, + sort_keys=True, + separators=(",", ":"), + ) + + "\n" + ).encode("utf-8") + parent_fd = _open_private_state_dir(posixpath.dirname(path), identity, True) + if parent_fd is None: + raise GuardError( + "startup-ready-failed", + path, + "startup readiness directory is missing", + ) + name = posixpath.basename(path) + temp = f".{name}.{secrets.token_hex(16)}.tmp" + fd = -1 + try: + fd = os.open( + temp, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + 0o600, + dir_fd=parent_fd, + ) + _write_all(fd, payload) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o600) + os.fsync(fd) + os.replace(temp, name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + temp = "" + os.fsync(parent_fd) + finally: + if fd >= 0: + os.close(fd) + if temp: + try: + os.unlink(temp, dir_fd=parent_fd) + except FileNotFoundError: + # The atomic rename or an earlier cleanup already consumed it. + pass + os.close(parent_fd) + + +def _write_startup_ready(identity: Identity) -> None: + if not _startup_protocol_active(identity): + raise GuardError( + "startup-capability-missing", + STARTUP_CAPABILITY_PATH, + "revoke-startup-ready must begin the PID 1 startup transaction", + ) + _write_pid1_marker(STARTUP_READY_PATH, identity) + + +def _revoke_startup_ready(identity: Identity) -> None: + # Publishing the capability sentinel opts this PID 1 instance into the + # readiness protocol before the ready marker is removed. Old images with + # the same nemoclaw-start cmdline never create it and retain compatibility. + _write_pid1_marker(STARTUP_CAPABILITY_PATH, identity) + parent_fd = _open_private_state_dir( + posixpath.dirname(STARTUP_READY_PATH), identity, True + ) + if parent_fd is None: + return + try: + try: + os.unlink(posixpath.basename(STARTUP_READY_PATH), dir_fd=parent_fd) + except FileNotFoundError: + return + except IsADirectoryError as exc: + raise GuardError( + "unsafe-startup-ready", + STARTUP_READY_PATH, + "startup readiness path is an unexpected directory", + ) from exc + os.fsync(parent_fd) + finally: + os.close(parent_fd) + + +def _validate_action_readiness( + action: Action, startup_owner: bool, identity: Identity +) -> None: + startup_action = action in {"revoke-startup-ready", "publish-startup-ready"} + if startup_action: + if not _pid1_is_nemoclaw_start() or not startup_owner or os.getppid() != 1: + raise GuardError( + "startup-owner-required", + STARTUP_READY_PATH, + f"{action} is restricted to the PID 1 startup transaction", + ) + return + installed_current = os.path.realpath(__file__) == os.path.realpath( + INSTALLED_HELPER_PATH + ) + pid1_is_nemoclaw_start = _pid1_is_nemoclaw_start() + if not pid1_is_nemoclaw_start and not installed_current: + # A source helper injected into an older image, and the local unit + # harness, retain their explicit compatibility path. Current images + # use the installed helper and authenticate a namespace remap below. + return + protocol_active, startup_ready = _startup_lease_state(identity) + if not pid1_is_nemoclaw_start and not protocol_active: + if ( + installed_current + and _startup_markers_absent(identity) + and _openshell_supervised_nonroot_start_is_live( + identity.root_uid, identity.sandbox_uid + ) + ): + # OpenShell is the container PID 1 and launches the configured + # image command as one non-root child in the same PID namespace. + # That degraded topology cannot publish root-owned readiness + # markers, so authenticate the stable supervisor/child pair while + # refusing any stale or malformed marker left by a strict startup. + return + if installed_current: + raise GuardError( + "startup-not-ready", + STARTUP_READY_PATH, + "installed config guard requires NemoClaw PID 1", + ) + return + # Source injected into an older image retains compatibility until that + # image explicitly opts in. The trusted installed helper requires the + # protocol from its very first exec, closing the pre-revoke boot race. + if not installed_current and not protocol_active: + return + if installed_current and not protocol_active: + # The supported --user sandbox entrypoint cannot create a root-owned + # readiness capability. It also explicitly disables gateway privilege + # separation and privileged PID 1 control. Preserve host shields/config + # compatibility only for that degraded mode. Root PID 1 never falls + # through when the capability is missing or malformed, and any valid + # capability opts even a non-root PID 1 into the strict lease below. + pid1_euid = _pid1_effective_uid() + if pid1_euid is not None and pid1_euid != identity.root_uid: + return + early_recover = action == "recover" and not startup_ready + if early_recover: + if not startup_owner or os.getppid() != 1: + raise GuardError( + "startup-owner-required", + STARTUP_READY_PATH, + f"{action} is restricted to the PID 1 startup transaction", + ) + return + if action in { + "lock", + "unlock", + "write-config", + "seal-restart", + "unseal-restart", + } and not startup_ready: + raise GuardError( + "startup-not-ready", + STARTUP_READY_PATH, + "OpenClaw startup is not ready for host config mutations", + ) + + +def _write_secondary_journal(record: dict[str, object], identity: Identity) -> None: + payload = json.dumps(record, sort_keys=True, separators=(",", ":")).encode("utf-8") + if len(payload) > MAX_JOURNAL_BYTES: + raise GuardError( + "journal-too-large", JOURNAL_PATH, "transaction journal is too large" + ) + journal_fd = _open_journal_dir(identity, True) + if journal_fd is None: + raise GuardError( + "journal-write-failed", JOURNAL_PATH, "journal directory is missing" + ) + journal_name = posixpath.basename(JOURNAL_PATH) + temp_name = f".{journal_name}.{secrets.token_hex(16)}.tmp" + fd = -1 + try: + fd = os.open( + temp_name, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + 0o600, + dir_fd=journal_fd, + ) + _write_all(fd, payload) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o600) + os.fsync(fd) + os.replace( + temp_name, journal_name, src_dir_fd=journal_fd, dst_dir_fd=journal_fd + ) + temp_name = "" + os.fsync(journal_fd) + finally: + if fd >= 0: + os.close(fd) + if temp_name: + try: + os.unlink(temp_name, dir_fd=journal_fd) + except FileNotFoundError: + # The atomic rename or an earlier cleanup already consumed it. + pass + os.close(journal_fd) + + +def _read_secondary_journal(identity: Identity) -> dict[str, object] | None: + journal_fd = _open_journal_dir(identity, False) + if journal_fd is None: + return None + journal_name = posixpath.basename(JOURNAL_PATH) + fd = -1 + try: + try: + fd = os.open(journal_name, _file_flags(), dir_fd=journal_fd) + except FileNotFoundError: + return None + before = os.fstat(fd) + current = os.stat(journal_name, dir_fd=journal_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or not _same_inode(before, current) + or before.st_uid != identity.root_uid + or before.st_gid != identity.root_gid + or stat.S_IMODE(before.st_mode) & 0o077 + or before.st_size > MAX_JOURNAL_BYTES + ): + raise GuardError( + "unsafe-journal", JOURNAL_PATH, "journal metadata is not trusted" + ) + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, COPY_BUFFER_BYTES) + if not chunk: + break + total += len(chunk) + if total > MAX_JOURNAL_BYTES: + raise GuardError( + "journal-too-large", JOURNAL_PATH, "journal exceeds size cap" + ) + chunks.append(chunk) + after = os.fstat(fd) + if not _stable_metadata(before, after): + raise GuardError( + "entry-raced", JOURNAL_PATH, "journal changed while reading" + ) + try: + value = json.loads(b"".join(chunks).decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "journal JSON is invalid" + ) from exc + if not isinstance(value, dict): + raise GuardError( + "invalid-journal", JOURNAL_PATH, "journal is not an object" + ) + return value + finally: + if fd >= 0: + os.close(fd) + os.close(journal_fd) + + +def _clear_secondary_journal(identity: Identity) -> None: + journal_fd = _open_journal_dir(identity, False) + if journal_fd is None: + return + try: + try: + os.unlink(posixpath.basename(JOURNAL_PATH), dir_fd=journal_fd) + except FileNotFoundError: + return + os.fsync(journal_fd) + finally: + os.close(journal_fd) + + +def _open_config(config_path: str) -> OpenConfig: + normalized = posixpath.normpath(config_path) + parent_path = posixpath.dirname(normalized) + config_name = posixpath.basename(normalized) + if config_name != ".openclaw" or not parent_path: + raise GuardError( + "invalid-config-path", + config_path, + "config directory must be an absolute path ending in .openclaw", + ) + parent_fd = _open_absolute_dir(parent_path) + try: + parent_stat = os.fstat(parent_fd) + before = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + if not stat.S_ISDIR(before.st_mode): + raise GuardError( + "unsafe-config-entry", + normalized, + f"config entry is a {_kind(before)}, expected directory", + ) + config_fd = os.open(config_name, _directory_flags(), dir_fd=parent_fd) + config_stat = os.fstat(config_fd) + after = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_inode(before, config_stat) or not _same_inode(config_stat, after): + os.close(config_fd) + raise GuardError( + "entry-raced", normalized, "config directory changed while opening" + ) + if config_stat.st_dev != parent_stat.st_dev: + os.close(config_fd) + raise GuardError( + "cross-device-entry", + normalized, + "config directory is on another filesystem", + ) + return OpenConfig( + config_path=normalized, + parent_path=parent_path, + config_name=config_name, + parent_fd=parent_fd, + config_fd=config_fd, + parent_stat=parent_stat, + config_stat=config_stat, + ) + except Exception: + os.close(parent_fd) + raise + + +def _open_config_for_lock(config_path: str, identity: Identity) -> OpenConfig: + """Pin /sandbox before resolving an attacker-controlled .openclaw name.""" + + normalized = posixpath.normpath(config_path) + parent_path = posixpath.dirname(normalized) + config_name = posixpath.basename(normalized) + if config_name != ".openclaw" or not parent_path: + raise GuardError( + "invalid-config-path", + config_path, + "config directory must be an absolute path ending in .openclaw", + ) + parent_fd = _open_absolute_dir(parent_path) + created = False + try: + original_parent = os.fstat(parent_fd) + try: + before = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + before = None + already_protected = bool( + original_parent.st_uid == identity.root_uid + and original_parent.st_gid == identity.sandbox_gid + and stat.S_IMODE(original_parent.st_mode) == 0o1775 + and before is not None + and stat.S_ISDIR(before.st_mode) + and before.st_uid == identity.root_uid + and before.st_gid == identity.root_gid + and stat.S_IMODE(before.st_mode) in {0o500, 0o755} + ) + if ( + before is not None + and stat.S_ISDIR(before.st_mode) + and before.st_dev != original_parent.st_dev + ): + if not already_protected: + os.fchown(parent_fd, identity.root_uid, identity.sandbox_gid) + os.fchmod(parent_fd, 0o755) + os.fsync(parent_fd) + raise GuardError( + "cross-device-entry", + normalized, + "refusing to mutate a cross-device .openclaw mount", + ) + # This root-ownership transition is the fail-closed outer namespace + # boundary. No later error returns /sandbox rename authority. + if not already_protected: + os.fchown(parent_fd, identity.root_uid, identity.sandbox_gid) + os.fchmod(parent_fd, 0o755) + os.fsync(parent_fd) + try: + before = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + before = None + if ( + before is not None + and stat.S_ISDIR(before.st_mode) + and before.st_dev != original_parent.st_dev + ): + raise GuardError( + "cross-device-entry", + normalized, + "refusing to mutate a cross-device .openclaw mount", + ) + if before is not None and not stat.S_ISDIR(before.st_mode): + os.rename( + config_name, + f".nemoclaw-rejected-openclaw-{secrets.token_hex(16)}", + src_dir_fd=parent_fd, + dst_dir_fd=parent_fd, + ) + os.fsync(parent_fd) + before = None + if before is None: + os.mkdir(config_name, 0o700, dir_fd=parent_fd) + os.fsync(parent_fd) + before = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + created = True + config_fd = os.open(config_name, _directory_flags(), dir_fd=parent_fd) + config_stat = os.fstat(config_fd) + current = os.stat(config_name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_inode(before, config_stat) or not _same_inode( + config_stat, current + ): + os.close(config_fd) + raise GuardError( + "entry-raced", normalized, "config directory changed while locking" + ) + opened = OpenConfig( + config_path=normalized, + parent_path=parent_path, + config_name=config_name, + parent_fd=parent_fd, + config_fd=config_fd, + parent_stat=original_parent, + config_stat=config_stat, + ) + if created: + placeholder = b"{}\n" + digest = hashlib.sha256(placeholder).hexdigest() + _force_replace_bytes(opened, "openclaw.json", placeholder, identity) + _force_replace_bytes( + opened, + ".config-hash", + f"{digest} openclaw.json\n".encode("ascii"), + identity, + ) + _commit_locked_dirs(opened, identity) + return opened + except Exception: + os.close(parent_fd) + raise + + +def _journal_payload(record: dict[str, object]) -> bytes: + payload = json.dumps(record, sort_keys=True, separators=(",", ":")).encode("utf-8") + if len(payload) > MAX_JOURNAL_BYTES: + raise GuardError( + "journal-too-large", JOURNAL_PATH, "transaction journal is too large" + ) + return payload + + +def _write_persistent_journal( + opened: OpenConfig, record: dict[str, object], identity: Identity +) -> None: + payload = _journal_payload(record) + temp_name = f".{PERSISTENT_JOURNAL_NAME}.{secrets.token_hex(16)}.tmp" + fd = -1 + try: + fd = os.open( + temp_name, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + 0o600, + dir_fd=opened.config_fd, + ) + _write_all(fd, payload) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o600) + os.fsync(fd) + try: + existing = os.stat( + PERSISTENT_JOURNAL_NAME, + dir_fd=opened.config_fd, + follow_symlinks=False, + ) + if stat.S_ISDIR(existing.st_mode): + _quarantine_untrusted_persistent_journal(opened, identity) + except FileNotFoundError: + # No planted persistent journal exists to quarantine before replace. + pass + os.replace( + temp_name, + PERSISTENT_JOURNAL_NAME, + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + temp_name = "" + os.fsync(opened.config_fd) + finally: + if fd >= 0: + os.close(fd) + if temp_name: + try: + os.unlink(temp_name, dir_fd=opened.config_fd) + except FileNotFoundError: + # The atomic rename or an earlier cleanup already consumed it. + pass + + +def _read_persistent_journal( + opened: OpenConfig, identity: Identity +) -> dict[str, object] | None: + display = posixpath.join(opened.config_path, PERSISTENT_JOURNAL_NAME) + fd = -1 + try: + try: + before = os.stat( + PERSISTENT_JOURNAL_NAME, + dir_fd=opened.config_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + return None + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or before.st_uid != identity.root_uid + or before.st_gid != identity.root_gid + or stat.S_IMODE(before.st_mode) & 0o077 + or before.st_size > MAX_JOURNAL_BYTES + ): + raise GuardError( + "unsafe-journal", + display, + "persistent journal metadata is not trusted", + ) + fd = os.open(PERSISTENT_JOURNAL_NAME, _file_flags(), dir_fd=opened.config_fd) + actual = os.fstat(fd) + if not _same_inode(before, actual): + raise GuardError( + "entry-raced", + display, + "persistent journal changed while opening", + ) + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, COPY_BUFFER_BYTES) + if not chunk: + break + total += len(chunk) + if total > MAX_JOURNAL_BYTES: + raise GuardError( + "journal-too-large", + display, + "persistent journal exceeds size cap", + ) + chunks.append(chunk) + after = os.fstat(fd) + if not _stable_metadata(before, after): + raise GuardError( + "entry-raced", display, "persistent journal changed while reading" + ) + try: + value = json.loads(b"".join(chunks).decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise GuardError( + "invalid-journal", display, "persistent journal JSON is invalid" + ) from exc + if not isinstance(value, dict): + raise GuardError( + "invalid-journal", display, "persistent journal is not an object" + ) + return value + finally: + if fd >= 0: + os.close(fd) + + +def _write_journal( + record: dict[str, object], identity: Identity, opened: OpenConfig | None = None +) -> None: + _write_secondary_journal(record, identity) + if opened is not None: + _write_persistent_journal(opened, record, identity) + + +def _read_journal( + identity: Identity, opened: OpenConfig | None = None +) -> dict[str, object] | None: + secondary = _read_secondary_journal(identity) + if opened is not None: + try: + persistent = _read_persistent_journal(opened, identity) + except GuardError: + if secondary is not None and ( + _is_mutable_dir_posture(opened, identity) + or _is_partial_frozen_mutable_posture(opened, identity) + ): + return secondary + raise + if persistent is not None: + if _is_mutable_dir_posture( + opened, identity + ) or _is_partial_frozen_mutable_posture(opened, identity): + display = posixpath.join(opened.config_path, PERSISTENT_JOURNAL_NAME) + if secondary is None: + raise GuardError( + "persistent-journal-without-secondary", + display, + "persistent journal is replayable after mutable handoff", + ) + if _journal_payload(persistent) != _journal_payload(secondary): + # The sandbox can replay a retained persistent inode after + # handoff; private rootfs state wins in mutable posture. + return secondary + return persistent + return secondary + + +def _clear_persistent_journal(opened: OpenConfig) -> None: + try: + current = os.stat( + PERSISTENT_JOURNAL_NAME, + dir_fd=opened.config_fd, + follow_symlinks=False, + ) + if stat.S_ISDIR(current.st_mode): + os.rename( + PERSISTENT_JOURNAL_NAME, + f".nemoclaw-untrusted-journal-{secrets.token_hex(16)}", + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + else: + os.unlink(PERSISTENT_JOURNAL_NAME, dir_fd=opened.config_fd) + os.fsync(opened.config_fd) + except FileNotFoundError: + # Clearing an already-absent journal is intentionally idempotent. + pass + + +def _clear_journal(identity: Identity, opened: OpenConfig | None = None) -> None: + if opened is not None: + _clear_persistent_journal(opened) + _clear_secondary_journal(identity) + + +def _commit_mutable_and_retire_journal(opened: OpenConfig, identity: Identity) -> None: + # The persistent record must disappear while config is still root-owned; + # otherwise sandbox can retain and replay its inode after handoff. The + # private rootfs record remains authoritative until handoff completes. + _clear_persistent_journal(opened) + _commit_mutable_dirs(opened, identity) + try: + _clear_secondary_journal(identity) + except (OSError, GuardError): + # Visible mutable handoff is already durable; recovery can retire the + # root-only secondary record idempotently on the next invocation. + pass + + +def _quarantine_untrusted_persistent_journal( + opened: OpenConfig, identity: Identity +) -> None: + """Remove a sandbox-planted reserved entry only after the tree is frozen.""" + + try: + current = os.stat( + PERSISTENT_JOURNAL_NAME, + dir_fd=opened.config_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + return + sandbox_owned = ( + current.st_uid == identity.sandbox_uid + and current.st_gid == identity.sandbox_gid + ) + root_owned = ( + current.st_uid == identity.root_uid and current.st_gid == identity.root_gid + ) + if not sandbox_owned and not root_owned: + raise GuardError( + "unsafe-journal", + posixpath.join(opened.config_path, PERSISTENT_JOURNAL_NAME), + "refusing to quarantine a reserved entry not owned by sandbox", + ) + quarantine = f".nemoclaw-untrusted-journal-{secrets.token_hex(16)}" + if stat.S_ISDIR(current.st_mode): + fd = os.open( + PERSISTENT_JOURNAL_NAME, _directory_flags(), dir_fd=opened.config_fd + ) + try: + actual = os.fstat(fd) + if not _same_inode(current, actual): + raise GuardError( + "entry-raced", + posixpath.join(opened.config_path, PERSISTENT_JOURNAL_NAME), + "reserved journal directory changed before quarantine", + ) + finally: + os.close(fd) + os.rename( + PERSISTENT_JOURNAL_NAME, + quarantine, + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + else: + os.rename( + PERSISTENT_JOURNAL_NAME, + quarantine, + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + os.unlink(quarantine, dir_fd=opened.config_fd) + os.fsync(opened.config_fd) + + +def _mutable_reserved_entry_is_nonauthoritative( + opened: OpenConfig, identity: Identity +) -> bool: + if not _is_mutable_dir_posture(opened, identity): + return False + current_pair = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current_pair, identity) + try: + entry = os.stat( + PERSISTENT_JOURNAL_NAME, + dir_fd=opened.config_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + return False + sandbox_owned = ( + entry.st_uid == identity.sandbox_uid and entry.st_gid == identity.sandbox_gid + ) + retained_root_directory = stat.S_ISDIR(entry.st_mode) and ( + entry.st_uid == identity.root_uid and entry.st_gid == identity.root_gid + ) + return sandbox_owned or retained_root_directory + + +def _assert_config_binding(opened: OpenConfig) -> None: + current = os.stat( + opened.config_name, dir_fd=opened.parent_fd, follow_symlinks=False + ) + actual = os.fstat(opened.config_fd) + if not stat.S_ISDIR(current.st_mode) or not _same_inode(current, actual): + raise GuardError( + "entry-raced", opened.config_path, "config directory binding changed" + ) + + +def _open_checked_file(opened: OpenConfig, name: str) -> tuple[int, os.stat_result]: + display = posixpath.join(opened.config_path, name) + try: + before = os.stat(name, dir_fd=opened.config_fd, follow_symlinks=False) + except OSError as exc: + raise GuardError("stat-failed", display, f"stat failed: {exc}") from exc + if not stat.S_ISREG(before.st_mode): + raise GuardError( + "unsafe-config-file", + display, + f"entry is a {_kind(before)}, expected regular file", + ) + if before.st_nlink != 1: + raise GuardError( + "hardlinked-config-file", + display, + f"link count is {before.st_nlink}, expected 1", + ) + max_bytes = MAX_FILE_BYTES[name] + if before.st_size > max_bytes: + raise GuardError( + "config-file-too-large", + display, + f"file is {before.st_size} bytes, maximum is {max_bytes}", + ) + if before.st_dev != opened.config_stat.st_dev: + raise GuardError( + "cross-device-entry", display, "config file is on another filesystem" + ) + try: + fd = os.open(name, _file_flags(), dir_fd=opened.config_fd) + except OSError as exc: + raise GuardError("open-failed", display, f"open failed: {exc}") from exc + actual = os.fstat(fd) + after = os.stat(name, dir_fd=opened.config_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(actual.st_mode) + or actual.st_nlink != 1 + or not _same_inode(before, actual) + or not _same_inode(actual, after) + or not _stable_metadata(before, actual) + or not _stable_metadata(actual, after) + ): + os.close(fd) + raise GuardError( + "entry-raced", display, "config file changed while it was being opened" + ) + return fd, actual + + +def _read_xattrs(fd: int) -> tuple[tuple[str, bytes], ...]: + listxattr = getattr(os, "listxattr", None) + getxattr = getattr(os, "getxattr", None) + if listxattr is None or getxattr is None: + return () + try: + return tuple((name, getxattr(fd, name)) for name in sorted(listxattr(fd))) + except OSError as exc: + if exc.errno in {errno.ENOTSUP, errno.ENOSYS}: + return () + raise + + +def _get_inode_flags(fd: int) -> int | None: + if not sys.platform.startswith("linux"): + return None + buffer = bytearray(struct.pack("I", 0)) + try: + fcntl.ioctl(fd, FS_IOC_GETFLAGS, buffer, True) + except OSError as exc: + if exc.errno in {errno.ENOTTY, errno.ENOTSUP, errno.EOPNOTSUPP, errno.EINVAL}: + return None + raise + return struct.unpack("I", buffer)[0] + + +def _set_inode_flags(fd: int, flags: int | None) -> None: + if flags is not None and sys.platform.startswith("linux"): + fcntl.ioctl(fd, FS_IOC_SETFLAGS, struct.pack("I", flags)) + + +def _snapshot_file(opened: OpenConfig, name: str) -> FileSnapshot: + display = posixpath.join(opened.config_path, name) + max_bytes = MAX_FILE_BYTES[name] + for _attempt in range(STABLE_READ_ATTEMPTS): + fd, before = _open_checked_file(opened, name) + try: + if before.st_size > max_bytes: + raise GuardError( + "config-file-too-large", + display, + f"file is {before.st_size} bytes, maximum is {max_bytes}", + ) + chunks: list[bytes] = [] + bytes_read = 0 + while True: + chunk = os.read(fd, COPY_BUFFER_BYTES) + if not chunk: + break + bytes_read += len(chunk) + if bytes_read > max_bytes: + raise GuardError( + "config-file-too-large", + display, + f"file grew beyond the {max_bytes}-byte maximum while reading", + ) + chunks.append(chunk) + xattrs = _read_xattrs(fd) + inode_flags = _get_inode_flags(fd) + after = os.fstat(fd) + current = os.stat(name, dir_fd=opened.config_fd, follow_symlinks=False) + if _stable_metadata(before, after) and _same_inode(after, current): + data = b"".join(chunks) + if len(data) != before.st_size: + continue + return FileSnapshot( + name=name, + dev=before.st_dev, + ino=before.st_ino, + uid=before.st_uid, + gid=before.st_gid, + mode=stat.S_IMODE(before.st_mode), + atime_ns=before.st_atime_ns, + mtime_ns=before.st_mtime_ns, + ctime_ns=before.st_ctime_ns, + size=before.st_size, + data=data, + xattrs=xattrs, + inode_flags=inode_flags, + ) + finally: + os.close(fd) + raise GuardError( + "unstable-config-file", + display, + f"file did not remain stable across {STABLE_READ_ATTEMPTS} reads", + ) + + +def _snapshot_is_current(opened: OpenConfig, snapshot: FileSnapshot) -> bool: + try: + current = os.stat(snapshot.name, dir_fd=opened.config_fd, follow_symlinks=False) + except OSError: + return False + return ( + stat.S_ISREG(current.st_mode) + and current.st_nlink == 1 + and current.st_dev == snapshot.dev + and current.st_ino == snapshot.ino + and current.st_size == snapshot.size + and current.st_mtime_ns == snapshot.mtime_ns + and current.st_ctime_ns == snapshot.ctime_ns + ) + + +def _validate_hash_record( + opened: OpenConfig, config: FileSnapshot, hash_file: FileSnapshot +) -> None: + display = posixpath.join(opened.config_path, hash_file.name) + try: + record = hash_file.data.decode("ascii") + except UnicodeDecodeError as exc: + raise GuardError( + "invalid-config-hash", display, "hash record must be ASCII" + ) from exc + match = SHA256_RECORD.fullmatch(record) + if not match: + raise GuardError( + "invalid-config-hash", + display, + "expected one canonical sha256sum record", + ) + digest, _marker, recorded_path = match.groups() + allowed_paths = { + "openclaw.json", + posixpath.join(opened.config_path, "openclaw.json"), + } + if recorded_path not in allowed_paths: + raise GuardError( + "invalid-config-hash-path", + display, + f"hash record path {recorded_path!r} is not an allowed OpenClaw config path", + ) + actual = hashlib.sha256(config.data).hexdigest() + if not secrets.compare_digest(digest.lower(), actual): + raise GuardError( + "config-hash-mismatch", + display, + "hash record does not match the captured openclaw.json bytes", + ) + + +def _snapshot_pair(opened: OpenConfig) -> tuple[FileSnapshot, FileSnapshot]: + last_error: GuardError | None = None + for _attempt in range(STABLE_READ_ATTEMPTS): + try: + config = _snapshot_file(opened, "openclaw.json") + hash_file = _snapshot_file(opened, ".config-hash") + if not _snapshot_is_current(opened, config) or not _snapshot_is_current( + opened, hash_file + ): + raise GuardError( + "config-pair-raced", + opened.config_path, + "OpenClaw config/hash pair changed while it was captured", + ) + _validate_hash_record(opened, config, hash_file) + return config, hash_file + except GuardError as exc: + last_error = exc + if last_error is not None: + raise GuardError( + last_error.code, + last_error.path, + f"{last_error.detail} after {STABLE_READ_ATTEMPTS} pair attempts", + ) from last_error + raise GuardError("config-pair-raced", opened.config_path, "pair capture failed") + + +def _snapshot_raw_pair(opened: OpenConfig) -> tuple[FileSnapshot, FileSnapshot]: + last_error: GuardError | None = None + for _attempt in range(STABLE_READ_ATTEMPTS): + try: + config = _snapshot_file(opened, "openclaw.json") + hash_file = _snapshot_file(opened, ".config-hash") + if not _snapshot_is_current(opened, config) or not _snapshot_is_current( + opened, hash_file + ): + raise GuardError( + "config-pair-raced", + opened.config_path, + "OpenClaw config/hash pair changed while it was captured", + ) + return config, hash_file + except GuardError as exc: + last_error = exc + if last_error is not None: + raise GuardError( + last_error.code, + last_error.path, + f"{last_error.detail} after {STABLE_READ_ATTEMPTS} pair attempts", + ) from last_error + raise GuardError("config-pair-raced", opened.config_path, "pair capture failed") + + +def _validate_config_json(data: bytes, source: str) -> None: + if not data: + raise GuardError("invalid-config-json", source, "config is empty") + try: + decoded = data.decode("utf-8") + except UnicodeDecodeError as exc: + raise GuardError("invalid-config-json", source, "config must be UTF-8") from exc + + def reject_constant(value: str) -> None: + raise ValueError(f"non-standard JSON constant {value}") + + try: + parsed = json.loads(decoded, parse_constant=reject_constant) + except (json.JSONDecodeError, ValueError) as exc: + raise GuardError( + "invalid-config-json", + source, + "config must be strict JSON (JSON5 comments and trailing commas are unsupported)", + ) from exc + if not isinstance(parsed, dict): + raise GuardError("invalid-config-json", source, "config must be a JSON object") + + +def _validate_runtime_config_json5( + data: bytes, source: str, identity: Identity +) -> None: + """Validate captured runtime bytes with the packaged root-owned JSON5 parser.""" + + if not data: + raise GuardError("invalid-config-json5", source, "config is empty") + try: + data.decode("utf-8") + except UnicodeDecodeError as exc: + raise GuardError( + "invalid-config-json5", source, "config must be UTF-8" + ) from exc + + node_fd = -1 + parser_fd = -1 + try: + node_fd = os.open(NODE_BINARY_PATH, _file_flags()) + node_st = os.fstat(node_fd) + if ( + not stat.S_ISREG(node_st.st_mode) + or node_st.st_uid != identity.root_uid + or stat.S_IMODE(node_st.st_mode) & 0o022 + ): + raise GuardError( + "unsafe-json5-validator", + NODE_BINARY_PATH, + "Node validator must be a root-owned non-writable regular file", + ) + parser_fd = _open_absolute_dir(JSON5_MODULE_PATH) + parser_st = os.fstat(parser_fd) + if ( + parser_st.st_uid != identity.root_uid + or stat.S_IMODE(parser_st.st_mode) & 0o022 + ): + raise GuardError( + "unsafe-json5-validator", + JSON5_MODULE_PATH, + "JSON5 parser directory must be root-owned and not group/world-writable", + ) + except FileNotFoundError as exc: + raise GuardError( + "json5-validator-missing", + JSON5_MODULE_PATH, + "fixed packaged JSON5 validator is unavailable", + ) from exc + finally: + if node_fd >= 0: + os.close(node_fd) + if parser_fd >= 0: + os.close(parser_fd) + + program = ( + "const fs=require('fs');" + f"const JSON5=require({json.dumps(JSON5_MODULE_PATH)});" + "const value=JSON5.parse(fs.readFileSync(0,'utf8'));" + "if (!value || typeof value!=='object' || Array.isArray(value)) process.exit(4);" + ) + try: + result = subprocess.run( + [NODE_BINARY_PATH, "--input-type=commonjs", "-e", program], + input=data, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + cwd="/", + env={ + "PATH": "/usr/bin:/bin", + "NODE_OPTIONS": "", + "NODE_PATH": "", + }, + close_fds=True, + timeout=JSON5_VALIDATION_TIMEOUT_SECONDS, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise GuardError( + "json5-validator-failed", source, "fixed JSON5 validator failed to run" + ) from exc + if result.returncode != 0: + raise GuardError( + "invalid-config-json5", source, "config must be a JSON5 object" + ) + + +def _read_replacement_config() -> bytes: + maximum = MAX_FILE_BYTES["openclaw.json"] + data = sys.stdin.buffer.read(maximum + 1) + if len(data) > maximum: + raise GuardError( + "config-file-too-large", + "stdin", + f"replacement config exceeds the {maximum}-byte maximum", + ) + _validate_config_json(data, "stdin") + return data + + +def _verify_mutable_files( + opened: OpenConfig, + snapshots: tuple[FileSnapshot, FileSnapshot], + identity: Identity, + *, + allow_blocking_flags: bool = False, +) -> None: + for snapshot in snapshots: + if ( + snapshot.uid != identity.sandbox_uid + or snapshot.gid != identity.sandbox_gid + or snapshot.mode != 0o660 + or ( + not allow_blocking_flags + and snapshot.inode_flags is not None + and snapshot.inode_flags & (FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + ): + raise GuardError( + "config-not-mutable", + posixpath.join(opened.config_path, snapshot.name), + "write-config requires sandbox:sandbox 0660 without immutable/append flags", + ) + + +def _verify_mutable_posture( + opened: OpenConfig, snapshots: tuple[FileSnapshot, FileSnapshot], identity: Identity +) -> None: + try: + _verify_dir_posture( + opened.parent_fd, + opened.parent_path, + identity.sandbox_uid, + identity.sandbox_gid, + 0o755, + ) + _verify_dir_posture( + opened.config_fd, + opened.config_path, + identity.sandbox_uid, + identity.sandbox_gid, + 0o2770, + ) + except GuardError as exc: + raise GuardError( + "config-not-mutable", + exc.path, + "write-config requires mutable sandbox-owned parent and config directories", + ) from exc + _verify_mutable_files(opened, snapshots, identity) + + +def _verify_expected_config( + opened: OpenConfig, config: FileSnapshot, expected_sha256: str +) -> None: + actual = hashlib.sha256(config.data).hexdigest() + if not secrets.compare_digest(actual, expected_sha256.lower()): + raise GuardError( + "config-cas-mismatch", + posixpath.join(opened.config_path, config.name), + f"current config SHA-256 is {actual}, not the expected digest", + ) + + +def _replacement_records( + originals: tuple[FileSnapshot, FileSnapshot], + replacement_config: bytes, + identity: Identity, + commit_time_ns: int, +) -> tuple[list[dict[str, object]], str]: + new_digest = hashlib.sha256(replacement_config).hexdigest() + replacement_by_name = { + "openclaw.json": replacement_config, + ".config-hash": f"{new_digest} openclaw.json\n".encode("ascii"), + } + records: list[dict[str, object]] = [] + for snapshot in originals: + desired_inode_flags = ( + None + if snapshot.inode_flags is None + else snapshot.inode_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + records.append( + _stored_file( + snapshot, + data=replacement_by_name[snapshot.name], + uid=identity.sandbox_uid, + gid=identity.sandbox_gid, + mode=0o660, + mtime_ns=commit_time_ns, + inode_flags=desired_inode_flags, + ) + ) + return records, new_digest + + +def _canonical_targets( + source: tuple[FileSnapshot, FileSnapshot], + identity: Identity, + *, + locked: bool, +) -> tuple[tuple[FileSnapshot, FileSnapshot], str]: + digest = hashlib.sha256(source[0].data).hexdigest() + data_by_name = { + "openclaw.json": source[0].data, + ".config-hash": f"{digest} openclaw.json\n".encode("ascii"), + } + uid = identity.root_uid if locked else identity.sandbox_uid + gid = identity.root_gid if locked else identity.sandbox_gid + mode = 0o444 if locked else 0o660 + targets: list[FileSnapshot] = [] + for snapshot in source: + desired_flags = ( + None + if snapshot.inode_flags is None + else snapshot.inode_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + targets.append( + _decode_stored_file( + _stored_file( + snapshot, + data=data_by_name[snapshot.name], + uid=uid, + gid=gid, + mode=mode, + inode_flags=desired_flags, + ) + ) + ) + return (targets[0], targets[1]), digest + + +def _journal_record( + phase: Literal["prepared", "applying", "committed"], + originals: tuple[FileSnapshot, FileSnapshot], + replacements: list[dict[str, object]], + expected_sha256: str, + new_digest: str, +) -> dict[str, object]: + return { + "version": 1, + "action": "write-config", + "phase": phase, + "configDir": PRODUCTION_CONFIG_DIR, + "expectedConfigSha256": expected_sha256.lower(), + "newConfigSha256": new_digest, + "original": [_stored_file(snapshot) for snapshot in originals], + "replacement": replacements, + } + + +def _decode_journal( + record: dict[str, object], +) -> tuple[ + str, tuple[FileSnapshot, FileSnapshot], tuple[FileSnapshot, FileSnapshot], str +]: + if ( + record.get("version") != 1 + or record.get("action") != "write-config" + or record.get("configDir") != PRODUCTION_CONFIG_DIR + or record.get("phase") not in {"prepared", "applying", "committed"} + ): + raise GuardError("invalid-journal", JOURNAL_PATH, "journal header is invalid") + original_raw = record.get("original") + replacement_raw = record.get("replacement") + digest = record.get("newConfigSha256") + if ( + not isinstance(original_raw, list) + or not isinstance(replacement_raw, list) + or len(original_raw) != 2 + or len(replacement_raw) != 2 + or not isinstance(digest, str) + or not re.fullmatch(r"[0-9a-f]{64}", digest) + ): + raise GuardError("invalid-journal", JOURNAL_PATH, "journal payload is invalid") + originals = tuple(_decode_stored_file(value) for value in original_raw) + replacements = tuple(_decode_stored_file(value) for value in replacement_raw) + if ( + tuple(item.name for item in originals) != CONFIG_FILES + or tuple(item.name for item in replacements) != CONFIG_FILES + ): + raise GuardError("invalid-journal", JOURNAL_PATH, "journal file set is invalid") + replacement_config = replacements[0] + replacement_hash = replacements[1] + actual_digest = hashlib.sha256(replacement_config.data).hexdigest() + if not secrets.compare_digest(actual_digest, digest): + raise GuardError( + "invalid-journal", JOURNAL_PATH, "replacement digest is invalid" + ) + # Reuse the strict record parser against a minimal trusted context later; + # here the canonical bytes are deterministic and can be checked directly. + if replacement_hash.data != f"{digest} openclaw.json\n".encode("ascii"): + raise GuardError( + "invalid-journal", JOURNAL_PATH, "replacement hash record is invalid" + ) + return ( + str(record["phase"]), + (originals[0], originals[1]), + (replacements[0], replacements[1]), + digest, + ) + + +RESTART_PHASES = { + "prepared", + "applying", + "sealed", + "unsealing", + "unseal-committed", +} + + +def _restart_journal_record( + phase: str, + original_locked: bool, + originals: tuple[FileSnapshot, FileSnapshot], + digest: str, +) -> dict[str, object]: + if phase not in RESTART_PHASES: + raise GuardError("invalid-journal", JOURNAL_PATH, "restart phase is invalid") + return { + "version": 1, + "action": "restart-seal", + "phase": phase, + "configDir": PRODUCTION_CONFIG_DIR, + "originalLocked": original_locked, + "configSha256": digest, + "original": [_stored_file(item) for item in originals], + } + + +def _decode_restart_journal( + record: dict[str, object], identity: Identity +) -> tuple[ + str, + bool, + tuple[FileSnapshot, FileSnapshot], + tuple[FileSnapshot, FileSnapshot], + tuple[FileSnapshot, FileSnapshot], + str, +]: + phase = record.get("phase") + original_locked = record.get("originalLocked") + digest = record.get("configSha256") + if ( + record.get("version") != 1 + or record.get("action") != "restart-seal" + or record.get("configDir") != PRODUCTION_CONFIG_DIR + or phase not in RESTART_PHASES + or not isinstance(original_locked, bool) + or not isinstance(digest, str) + or not re.fullmatch(r"[0-9a-f]{64}", digest) + ): + raise GuardError( + "invalid-journal", JOURNAL_PATH, "restart journal header is invalid" + ) + + raw = record.get("original") + if not isinstance(raw, list) or len(raw) != 2: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "restart journal original pair is invalid" + ) + items = tuple(_decode_stored_file(value) for value in raw) + if tuple(item.name for item in items) != CONFIG_FILES: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "restart journal file set is invalid" + ) + originals = (items[0], items[1]) + if hashlib.sha256(originals[0].data).hexdigest() != digest: + raise GuardError( + "invalid-journal", JOURNAL_PATH, "restart config digest is invalid" + ) + _validate_runtime_config_json5(originals[0].data, JOURNAL_PATH, identity) + if original_locked: + for item in originals: + if ( + item.uid != identity.root_uid + or item.gid != identity.root_gid + or item.mode != 0o444 + ): + raise GuardError( + "invalid-journal", + JOURNAL_PATH, + "locked restart original metadata is invalid", + ) + else: + _validate_recovery_posture(originals, identity) + sealed, _ = _canonical_targets(originals, identity, locked=True) + mutable, _ = _canonical_targets(originals, identity, locked=False) + return ( + str(phase), + original_locked, + originals, + sealed, + mutable, + digest, + ) + + +def _write_all(fd: int, data: bytes) -> None: + view = memoryview(data) + while view: + written = os.write(fd, view) + if written <= 0: + raise OSError(errno.EIO, "short write") + view = view[written:] + + +def _replace_from_snapshot( + opened: OpenConfig, + snapshot: FileSnapshot, + uid: int, + gid: int, + mode: int, + inode_flags: int | None, + *, + replacement_data: bytes | None = None, + replacement_atime_ns: int | None = None, + replacement_mtime_ns: int | None = None, + replacement_xattrs: tuple[tuple[str, bytes], ...] | None = None, +) -> os.stat_result: + temp_name = ( + f".nemoclaw-config-{snapshot.name.lstrip('.')}-{secrets.token_hex(16)}.tmp" + ) + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + fd = -1 + source_fd = -1 + source_flags: int | None = None + replaced = False + target_data = snapshot.data if replacement_data is None else replacement_data + target_atime_ns = ( + snapshot.atime_ns if replacement_atime_ns is None else replacement_atime_ns + ) + target_mtime_ns = ( + snapshot.mtime_ns if replacement_mtime_ns is None else replacement_mtime_ns + ) + target_xattrs = ( + snapshot.xattrs if replacement_xattrs is None else replacement_xattrs + ) + try: + fd = os.open(temp_name, flags, 0o600, dir_fd=opened.config_fd) + _write_all(fd, target_data) + os.fchown(fd, uid, gid) + setxattr = getattr(os, "setxattr", None) + if setxattr is not None: + for name, value in target_xattrs: + setxattr(fd, name, value) + os.fchmod(fd, mode) + os.utime(fd, ns=(target_atime_ns, target_mtime_ns)) + os.fsync(fd) + source_fd, current = _open_checked_file(opened, snapshot.name) + if ( + current.st_dev != snapshot.dev + or current.st_ino != snapshot.ino + or current.st_nlink != 1 + or not stat.S_ISREG(current.st_mode) + or current.st_size != snapshot.size + or current.st_mtime_ns != snapshot.mtime_ns + or current.st_ctime_ns != snapshot.ctime_ns + ): + raise GuardError( + "entry-raced", + posixpath.join(opened.config_path, snapshot.name), + "config file changed before atomic replacement", + ) + source_flags = _get_inode_flags(source_fd) + if source_flags is not None: + replace_flags = source_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + if replace_flags != source_flags: + _set_inode_flags(source_fd, replace_flags) + os.replace( + temp_name, + snapshot.name, + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + replaced = True + temp_name = "" + os.fsync(opened.config_fd) + if inode_flags is not None and _get_inode_flags(fd) is not None: + _set_inode_flags(fd, inode_flags) + os.fsync(fd) + os.fsync(opened.config_fd) + installed = os.stat( + snapshot.name, dir_fd=opened.config_fd, follow_symlinks=False + ) + return installed + finally: + if source_fd >= 0: + if not replaced and source_flags is not None: + try: + _set_inode_flags(source_fd, source_flags) + except OSError: + # Preserve the primary replacement failure; callers keep + # the canonical directory frozen and fail closed. + pass + os.close(source_fd) + if fd >= 0: + os.close(fd) + if temp_name: + try: + os.unlink(temp_name, dir_fd=opened.config_fd) + except FileNotFoundError: + pass + + +def _force_replace_bytes( + opened: OpenConfig, + name: str, + data: bytes, + identity: Identity, +) -> None: + """Fresh-publish bounded bytes after freeze without trusting the old inode.""" + + if len(data) > MAX_FILE_BYTES[name]: + raise GuardError( + "config-file-too-large", + posixpath.join(opened.config_path, name), + "refusing oversized fail-closed replacement", + ) + temp = f".nemoclaw-force-{name.lstrip('.')}-{secrets.token_hex(16)}.tmp" + fd = -1 + try: + fd = os.open( + temp, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + 0o400, + dir_fd=opened.config_fd, + ) + _write_all(fd, data) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o444) + os.fsync(fd) + try: + target = os.stat(name, dir_fd=opened.config_fd, follow_symlinks=False) + if stat.S_ISDIR(target.st_mode): + os.rename( + name, + f".nemoclaw-rejected-{name.lstrip('.')}-{secrets.token_hex(16)}", + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + except FileNotFoundError: + # An absent target needs no quarantine before atomic replacement. + pass + os.replace(temp, name, src_dir_fd=opened.config_fd, dst_dir_fd=opened.config_fd) + temp = "" + os.fsync(opened.config_fd) + finally: + if fd >= 0: + os.close(fd) + if temp: + try: + os.unlink(temp, dir_fd=opened.config_fd) + except FileNotFoundError: + # The atomic rename or an earlier cleanup already consumed it. + pass + + +def _set_dir(fd: int, uid: int, gid: int, mode: int, freeze_mode: int) -> None: + os.fchmod(fd, freeze_mode) + os.fchown(fd, uid, gid) + os.fchmod(fd, mode) + os.fsync(fd) + + +def _verify_dir_posture(fd: int, path: str, uid: int, gid: int, mode: int) -> None: + current = os.fstat(fd) + if ( + not stat.S_ISDIR(current.st_mode) + or current.st_uid != uid + or current.st_gid != gid + or stat.S_IMODE(current.st_mode) != mode + ): + raise GuardError( + "verification-failed", + path, + "directory owner or mode does not match the requested posture", + ) + + +def _dir_has_posture(fd: int, uid: int, gid: int, mode: int) -> bool: + current = os.fstat(fd) + return ( + stat.S_ISDIR(current.st_mode) + and current.st_uid == uid + and current.st_gid == gid + and stat.S_IMODE(current.st_mode) == mode + ) + + +def _is_mutable_dir_posture(opened: OpenConfig, identity: Identity) -> bool: + return _dir_has_posture( + opened.parent_fd, + identity.sandbox_uid, + identity.sandbox_gid, + 0o755, + ) and _dir_has_posture( + opened.config_fd, + identity.sandbox_uid, + identity.sandbox_gid, + 0o2770, + ) + + +def _is_write_frozen_posture(opened: OpenConfig, identity: Identity) -> bool: + return _dir_has_posture( + opened.parent_fd, + identity.root_uid, + identity.sandbox_gid, + 0o755, + ) and _dir_has_posture( + opened.config_fd, + identity.root_uid, + identity.root_gid, + 0o700, + ) + + +def _has_locked_dir_posture(opened: OpenConfig, identity: Identity) -> bool: + return _dir_has_posture( + opened.parent_fd, + identity.root_uid, + identity.sandbox_gid, + 0o1775, + ) and _dir_has_posture( + opened.config_fd, + identity.root_uid, + identity.root_gid, + 0o755, + ) + + +def _has_clamped_locked_dir_posture(opened: OpenConfig, identity: Identity) -> bool: + return _dir_has_posture( + opened.parent_fd, + identity.root_uid, + identity.sandbox_gid, + 0o1775, + ) and _dir_has_posture( + opened.config_fd, + identity.root_uid, + identity.root_gid, + 0o500, + ) + + +def _verify_locked_files( + opened: OpenConfig, + snapshots: tuple[FileSnapshot, FileSnapshot], + identity: Identity, + *, + allow_blocking_flags: bool = False, +) -> None: + for snapshot in snapshots: + if ( + snapshot.uid != identity.root_uid + or snapshot.gid != identity.root_gid + or snapshot.mode != 0o444 + or ( + not allow_blocking_flags + and snapshot.inode_flags is not None + and snapshot.inode_flags & (FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + ): + raise GuardError( + "config-not-locked", + posixpath.join(opened.config_path, snapshot.name), + "restart seal requires the exact shields-locked file posture", + ) + + +def _verify_locked_posture( + opened: OpenConfig, + snapshots: tuple[FileSnapshot, FileSnapshot], + identity: Identity, + *, + allow_blocking_flags: bool = False, +) -> None: + if not _has_locked_dir_posture(opened, identity): + raise GuardError( + "config-not-locked", + opened.config_path, + "restart seal requires the exact shields-locked directory posture", + ) + _verify_locked_files( + opened, + snapshots, + identity, + allow_blocking_flags=allow_blocking_flags, + ) + + +def _is_partial_frozen_mutable_posture(opened: OpenConfig, identity: Identity) -> bool: + """Recognize only pre-replacement freeze states with a root-owned marker. + + The legacy 0555/0500 modes cover a kill inside the older chmod-first freeze. + A root-owned parent or config inode is mandatory, so an ordinary sandbox + tree cannot impersonate an orphan transaction after rootfs-local state is + lost during container recreation. + """ + + if _is_mutable_dir_posture(opened, identity): + return False + parent = os.fstat(opened.parent_fd) + config = os.fstat(opened.config_fd) + parent_mode = stat.S_IMODE(parent.st_mode) + config_mode = stat.S_IMODE(config.st_mode) + parent_known = ( + parent.st_uid == identity.root_uid + and parent.st_gid == identity.sandbox_gid + and parent_mode in {0o555, 0o755} + ) or ( + parent.st_uid == identity.sandbox_uid + and parent.st_gid == identity.sandbox_gid + and parent_mode in {0o555, 0o755} + ) + config_known = ( + config.st_uid == identity.root_uid + and config.st_gid == identity.root_gid + and config_mode in {0o000, 0o500, 0o700, 0o770} + ) or ( + config.st_uid == identity.sandbox_uid + and config.st_gid == identity.sandbox_gid + and config_mode in {0o000, 0o500, 0o770, 0o2770} + ) + has_root_marker = ( + parent.st_uid == identity.root_uid or config.st_uid == identity.root_uid + ) + return parent_known and config_known and has_root_marker + + +def _capture_orphan_frozen_mutable( + opened: OpenConfig, identity: Identity +) -> tuple[FileSnapshot, FileSnapshot] | None: + if not _is_partial_frozen_mutable_posture(opened, identity): + return None + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + return current + + +def _commit_mutable_dirs(opened: OpenConfig, identity: Identity) -> None: + # Keep the parent root-owned until after config write access is granted. + # Every pre-handoff crash therefore retains a durable root-owned orphan + # discriminator; changing parent ownership last moves atomically into the + # exact final mutable posture. + os.fchown(opened.parent_fd, identity.root_uid, identity.sandbox_gid) + os.fchmod(opened.parent_fd, 0o755) + os.fsync(opened.parent_fd) + os.fchmod(opened.config_fd, 0o000) + os.fchown(opened.config_fd, identity.sandbox_uid, identity.sandbox_gid) + # This chmod is the irreversible handoff: sandbox code can mutate paths + # through an existing parent/config descriptor as soon as it succeeds. + os.fchmod(opened.config_fd, 0o2770) + try: + os.fsync(opened.config_fd) + os.fchown(opened.parent_fd, identity.sandbox_uid, identity.sandbox_gid) + os.fchmod(opened.parent_fd, 0o755) + os.fsync(opened.parent_fd) + _assert_config_binding(opened) + _verify_dir_posture( + opened.config_fd, + opened.config_path, + identity.sandbox_uid, + identity.sandbox_gid, + 0o2770, + ) + _verify_dir_posture( + opened.parent_fd, + opened.parent_path, + identity.sandbox_uid, + identity.sandbox_gid, + 0o755, + ) + except Exception as exc: + raise MutableHandoffError( + "mutable-handoff-incomplete", + opened.config_path, + f"sandbox write access was granted before final verification: {exc}", + ) from exc + + +def _commit_locked_dirs(opened: OpenConfig, identity: Identity) -> None: + _set_dir( + opened.config_fd, + identity.root_uid, + identity.root_gid, + 0o755, + 0o500, + ) + _set_dir( + opened.parent_fd, + identity.root_uid, + identity.sandbox_gid, + 0o1775, + 0o555, + ) + _assert_config_binding(opened) + _verify_dir_posture( + opened.config_fd, + opened.config_path, + identity.root_uid, + identity.root_gid, + 0o755, + ) + _verify_dir_posture( + opened.parent_fd, + opened.parent_path, + identity.root_uid, + identity.sandbox_gid, + 0o1775, + ) + + +def _freeze_parent(opened: OpenConfig, identity: Identity) -> None: + # Ownership is the persistent orphan discriminator. Changing it first also + # revokes sandbox writes atomically: once fchown returns, mode 0755 no longer + # grants the former owner write access. This avoids an unmarked 0555 window + # if the process is killed between chmod/chown syscalls. + os.fchown(opened.parent_fd, identity.root_uid, identity.sandbox_gid) + os.fsync(opened.parent_fd) + os.fchmod(opened.parent_fd, 0o755) + os.fsync(opened.parent_fd) + + +def _freeze_config(opened: OpenConfig, identity: Identity) -> None: + # The root-owned parent now pins the .openclaw name. Root ownership of the + # config inode revokes writes through already-open directory descriptors + # before the final private mode is installed. + os.fchown(opened.config_fd, identity.root_uid, identity.root_gid) + os.fsync(opened.config_fd) + os.fchmod(opened.config_fd, 0o700) + os.fsync(opened.config_fd) + + +def _freeze( + opened: OpenConfig, + identity: Identity, + *, + quarantine_reserved: bool = False, +) -> None: + # Parent first prevents a rename-swap of .openclaw; config next prevents + # replacement of either exact top-level file. + _freeze_parent(opened, identity) + _assert_config_binding(opened) + _freeze_config(opened, identity) + _assert_config_binding(opened) + if quarantine_reserved: + _quarantine_untrusted_persistent_journal(opened, identity) + + +def _verify_file( + opened: OpenConfig, + name: str, + uid: int, + gid: int, + mode: int, + expected: FileSnapshot, +) -> None: + snapshot = _snapshot_file(opened, name) + mismatches: list[str] = [] + if snapshot.uid != uid: + mismatches.append(f"uid={snapshot.uid} expected={uid}") + if snapshot.gid != gid: + mismatches.append(f"gid={snapshot.gid} expected={gid}") + if snapshot.mode != mode: + mismatches.append(f"mode={snapshot.mode:o} expected={mode:o}") + if snapshot.data != expected.data: + mismatches.append("bytes differ") + # Reading for verification may itself advance atime on relatime filesystems. + # Publication sets the requested atime, but it is not a stable post-read check. + if snapshot.mtime_ns != expected.mtime_ns: + mismatches.append(f"mtime_ns={snapshot.mtime_ns} expected={expected.mtime_ns}") + if snapshot.xattrs != expected.xattrs: + mismatches.append("xattrs differ") + if snapshot.inode_flags is not None and snapshot.inode_flags != ( + expected.inode_flags or 0 + ): + mismatches.append( + f"inode_flags={snapshot.inode_flags} expected={expected.inode_flags or 0}" + ) + if snapshot.ino <= 0: + mismatches.append("invalid inode") + if mismatches: + raise GuardError( + "verification-failed", + posixpath.join(opened.config_path, name), + "installed config metadata or bytes do not match the requested posture: " + + "; ".join(mismatches), + ) + + +def _restore_originals( + opened: OpenConfig, + snapshots: tuple[FileSnapshot, ...], + identity: Identity, +) -> list[str]: + errors: list[str] = [] + for snapshot in snapshots: + try: + current = _snapshot_file(opened, snapshot.name) + _replace_from_snapshot( + opened, + current, + snapshot.uid, + snapshot.gid, + snapshot.mode, + snapshot.inode_flags, + replacement_data=snapshot.data, + replacement_atime_ns=snapshot.atime_ns, + replacement_mtime_ns=snapshot.mtime_ns, + replacement_xattrs=snapshot.xattrs, + ) + except Exception as exc: # Best-effort rollback; force-lock follows. + errors.append(f"{snapshot.name}: {exc}") + try: + _set_dir( + opened.config_fd, + opened.config_stat.st_uid, + opened.config_stat.st_gid, + stat.S_IMODE(opened.config_stat.st_mode), + 0o500, + ) + _set_dir( + opened.parent_fd, + opened.parent_stat.st_uid, + opened.parent_stat.st_gid, + stat.S_IMODE(opened.parent_stat.st_mode), + 0o555, + ) + except OSError as exc: + errors.append(f"directory metadata: {exc}") + if errors: + try: + for name in CONFIG_FILES: + fd, _st = _open_checked_file(opened, name) + try: + inode_flags = _get_inode_flags(fd) + if inode_flags is not None: + _set_inode_flags( + fd, inode_flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + os.fchown(fd, identity.root_uid, identity.root_gid) + os.fchmod(fd, 0o444) + os.fsync(fd) + finally: + os.close(fd) + _set_dir( + opened.config_fd, + identity.root_uid, + identity.root_gid, + 0o755, + 0o500, + ) + _set_dir( + opened.parent_fd, + identity.root_uid, + identity.sandbox_gid, + 0o1775, + 0o555, + ) + except Exception as exc: + errors.append(f"fail-closed lock: {exc}") + return errors + + +def _preflight(opened: OpenConfig) -> None: + _assert_config_binding(opened) + _snapshot_pair(opened) + _assert_config_binding(opened) + + +def _preflight_restart(opened: OpenConfig, identity: Identity) -> None: + _assert_config_binding(opened) + if _is_mutable_dir_posture(opened, identity): + config, hash_file = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, (config, hash_file), identity) + elif _has_locked_dir_posture(opened, identity): + config, hash_file = _snapshot_pair(opened) + _verify_locked_files(opened, (config, hash_file), identity) + else: + raise GuardError( + "invalid-restart-posture", + opened.config_path, + "restart preflight requires an exact mutable or shields-locked posture", + ) + _validate_runtime_config_json5( + config.data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + _assert_config_binding(opened) + + +def _force_fail_closed_lock(opened: OpenConfig, identity: Identity) -> list[str]: + errors: list[str] = [] + targets: tuple[FileSnapshot, FileSnapshot] | None = None + try: + current = _snapshot_raw_pair(opened) + targets, _digest = _canonical_targets(current, identity, locked=True) + _install_stored_pair(opened, targets) + _snapshot_pair(opened) + try: + _validate_runtime_config_json5( + targets[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + except Exception as validation_exc: + # Containment succeeds even when the captured bytes are invalid. + errors.append(f"config validation: {validation_exc}") + except Exception as exc: + errors.append(f"canonical pair: {exc}") + if targets is not None: + try: + for target in targets: + _force_replace_bytes(opened, target.name, target.data, identity) + _snapshot_pair(opened) + except Exception as force_exc: + errors.append(f"forced fresh pair: {force_exc}") + else: + # No bounded pair could be captured. Sever each canonical path + # rather than retaining an attacker-held writable inode. + for name in CONFIG_FILES: + try: + os.rename( + name, + f".nemoclaw-rejected-{name.lstrip('.')}-{secrets.token_hex(16)}", + src_dir_fd=opened.config_fd, + dst_dir_fd=opened.config_fd, + ) + except FileNotFoundError: + # A concurrently absent canonical name is already severed. + pass + except Exception as file_exc: + errors.append(f"{name}: {file_exc}") + os.fsync(opened.config_fd) + try: + _commit_locked_dirs(opened, identity) + except Exception as exc: + errors.append(f"locked directories: {exc}") + return errors + + +def _settle_pending_transaction_for_lock( + opened: OpenConfig, identity: Identity +) -> None: + """Resolve only rootfs-authenticated state while the mutable tree is frozen.""" + + try: + secondary = _read_secondary_journal(identity) + except GuardError: + secondary = None + # A persistent record without the private rootfs peer is replayable after + # mutable exposure and is therefore never authoritative for deadline lock. + if secondary is not None: + try: + journal_action = secondary.get("action") + if journal_action == "write-config": + phase, originals, replacements, _digest = _decode_journal(secondary) + if phase != "prepared": + targets = replacements if phase == "committed" else originals + _install_stored_pair(opened, targets) + elif journal_action == "restart-seal": + phase, original_locked, _originals, _sealed, mutable, _digest = ( + _decode_restart_journal(secondary, identity) + ) + if not original_locked and phase != "prepared": + _install_stored_pair(opened, mutable) + except Exception: + # Containment remains deterministic even if transaction recovery is + # impossible: the current bounded config bytes are sealed below. + pass + try: + _clear_journal(identity, opened) + except (OSError, GuardError): + # A path may be a sandbox-planted nonregular entry. Quarantine it under + # the already-frozen descriptor and retry secondary cleanup. + try: + _quarantine_untrusted_persistent_journal(opened, identity) + except (OSError, GuardError): + # The directory is already frozen; sealing the bounded current + # pair below remains the fail-closed containment authority. + pass + try: + _clear_secondary_journal(identity) + except (OSError, GuardError): + # A stale root-only secondary record cannot weaken the frozen tree + # and can be retired by a later idempotent recovery. + pass + + +def _transition( + action: Literal["lock", "unlock"], + opened: OpenConfig, + identity: Identity, + *, + quarantine_untrusted: bool = False, +) -> None: + if action == "lock": + if _has_clamped_locked_dir_posture(opened, identity): + pair = _snapshot_pair(opened) + _verify_locked_files(opened, pair, identity) + return + if _has_locked_dir_posture(opened, identity): + # A restart journal may still need rootfs-authenticated cleanup. + _settle_pending_transaction_for_lock(opened, identity) + pair = _snapshot_pair(opened) + _verify_locked_files(opened, pair, identity) + return + freeze_started = False + try: + freeze_started = True + _freeze(opened, identity) + _settle_pending_transaction_for_lock(opened, identity) + source = _snapshot_raw_pair(opened) + targets, _digest = _canonical_targets(source, identity, locked=True) + _install_stored_pair(opened, targets) + pair = _snapshot_pair(opened) + _verify_locked_files(opened, pair, identity) + _commit_locked_dirs(opened, identity) + return + except Exception as exc: + fail_closed_errors = ( + _force_fail_closed_lock(opened, identity) if freeze_started else [] + ) + detail = str(exc) + if fail_closed_errors: + detail += "; fail-closed issues: " + "; ".join(fail_closed_errors) + if isinstance(exc, GuardError): + raise GuardError(exc.code, exc.path, detail) from exc + raise GuardError("transition-failed", opened.config_path, detail) from exc + + pair = _snapshot_pair(opened) + _verify_locked_posture(opened, pair, identity, allow_blocking_flags=True) + snapshots: list[FileSnapshot] = [] + try: + _freeze(opened, identity) + snapshots.extend(_snapshot_pair(opened)) + targets, _digest = _canonical_targets( + (snapshots[0], snapshots[1]), identity, locked=False + ) + _install_stored_pair(opened, targets) + _snapshot_pair(opened) + _commit_mutable_dirs(opened, identity) + except Exception as exc: + rollback_errors = ( + [] + if isinstance(exc, MutableHandoffError) + else _restore_originals(opened, tuple(snapshots), identity) + ) + detail = str(exc) + if rollback_errors: + detail += "; rollback issues: " + "; ".join(rollback_errors) + if isinstance(exc, GuardError): + raise GuardError(exc.code, exc.path, detail) from exc + raise GuardError("transition-failed", opened.config_path, detail) from exc + + +def _install_stored_pair( + opened: OpenConfig, targets: tuple[FileSnapshot, FileSnapshot] +) -> None: + current_pair = _snapshot_raw_pair(opened) + normalized_targets: list[FileSnapshot] = [] + for current, target in zip(current_pair, targets, strict=True): + installed = _replace_from_snapshot( + opened, + current, + target.uid, + target.gid, + target.mode, + target.inode_flags, + replacement_data=target.data, + replacement_atime_ns=target.atime_ns, + replacement_mtime_ns=target.mtime_ns, + replacement_xattrs=target.xattrs, + ) + if installed.st_ino == current.ino: + raise GuardError( + "replacement-failed", + posixpath.join(opened.config_path, current.name), + "journal recovery did not fresh-replace the target", + ) + normalized_targets.append( + FileSnapshot( + **{ + **target.__dict__, + "atime_ns": installed.st_atime_ns, + "mtime_ns": installed.st_mtime_ns, + } + ) + ) + for target in normalized_targets: + _verify_file( + opened, + target.name, + target.uid, + target.gid, + target.mode, + target, + ) + + +def _validate_recovery_posture( + files: tuple[FileSnapshot, FileSnapshot], identity: Identity +) -> None: + for stored in files: + if ( + stored.uid != identity.sandbox_uid + or stored.gid != identity.sandbox_gid + or stored.mode != 0o660 + or ( + stored.inode_flags is not None + and stored.inode_flags & (FS_IMMUTABLE_FL | FS_APPEND_FL) + ) + ): + raise GuardError( + "invalid-journal", + JOURNAL_PATH, + "journal files do not describe the mutable OpenClaw posture", + ) + + +def _seal_restart( + opened: OpenConfig, + identity: Identity, + *, + quarantine_untrusted: bool = False, +) -> bool: + if _has_locked_dir_posture(opened, identity): + original = _snapshot_pair(opened) + _verify_locked_files(opened, original, identity) + _sealed, digest = _canonical_targets(original, identity, locked=True) + record = _restart_journal_record("sealed", True, original, digest) + # Recording the original posture does not alter either protected file + # or any host-shields directory metadata. + _write_journal(record, identity, opened) + return True + + if not _is_mutable_dir_posture(opened, identity): + raise GuardError( + "invalid-restart-posture", + opened.config_path, + "restart seal requires exact mutable or shields-locked posture", + ) + initial = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, initial, identity) + _validate_runtime_config_json5( + initial[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + _initial_sealed, initial_digest = _canonical_targets(initial, identity, locked=True) + _write_journal( + _restart_journal_record( + "prepared", + False, + initial, + initial_digest, + ), + identity, + ) + + _freeze(opened, identity, quarantine_reserved=True) + frozen = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, frozen, identity) + _validate_runtime_config_json5( + frozen[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + sealed, digest = _canonical_targets(frozen, identity, locked=True) + applying = _restart_journal_record("applying", False, frozen, digest) + # No replacement begins until this record is durable both in rootfs state + # and in the persistent /sandbox tree. + _write_journal(applying, identity, opened) + _install_stored_pair(opened, sealed) + installed = _snapshot_pair(opened) + _verify_locked_files(opened, installed, identity) + sealed_record = _restart_journal_record("sealed", False, frozen, digest) + _write_journal(sealed_record, identity, opened) + _commit_locked_dirs(opened, identity) + return False + + +def _unseal_restart( + opened: OpenConfig, + identity: Identity, + record: dict[str, object] | None, +) -> bool: + if record is None: + if _has_locked_dir_posture(opened, identity): + current = _snapshot_pair(opened) + _verify_locked_files(opened, current, identity) + return True + if _is_mutable_dir_posture(opened, identity): + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + _validate_runtime_config_json5( + current[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + return False + raise GuardError( + "recovery-required", + opened.config_path, + "restart seal posture is incomplete and must be recovered", + ) + + ( + _phase, + original_locked, + originals, + _sealed, + mutable, + digest, + ) = _decode_restart_journal(record, identity) + if original_locked: + current = _snapshot_pair(opened) + _verify_locked_posture(opened, current, identity) + try: + _clear_journal(identity, opened) + except (OSError, GuardError): + # The root-owned record remains an idempotent cleanup request. + pass + return True + + _freeze(opened, identity) + unsealing = _restart_journal_record("unsealing", False, originals, digest) + _write_journal(unsealing, identity, opened) + _install_stored_pair(opened, mutable) + installed = _snapshot_pair(opened) + _verify_mutable_files(opened, installed, identity) + committed = _restart_journal_record("unseal-committed", False, originals, digest) + _write_journal(committed, identity, opened) + _commit_mutable_and_retire_journal(opened, identity) + return False + + +def _recover_restart( + opened: OpenConfig, + identity: Identity, + record: dict[str, object], +) -> tuple[str, str | None, bool]: + phase, original_locked, _originals, _sealed, mutable, digest = ( + _decode_restart_journal(record, identity) + ) + if original_locked: + current = _snapshot_pair(opened) + _verify_locked_posture(opened, current, identity) + try: + _clear_journal(identity, opened) + except (OSError, GuardError): + # Locked posture is already verified; later recovery can retire an + # idempotent stale journal without reopening mutation authority. + pass + return "restart-locked-preserved", digest, True + + if phase == "prepared": + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + _validate_runtime_config_json5( + current[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + if not _is_mutable_dir_posture(opened, identity): + if not _is_partial_frozen_mutable_posture(opened, identity): + raise GuardError( + "invalid-recovery-posture", + opened.config_path, + "prepared restart journal has an unexpected directory posture", + ) + _commit_mutable_and_retire_journal(opened, identity) + visible_digest = hashlib.sha256(current[0].data).hexdigest() + try: + _clear_journal(identity, opened) + except (OSError, GuardError): + # Mutable posture is already verified and committed; journal + # retirement can be retried without changing visible bytes. + pass + return "restart-prepared-preserved", visible_digest, False + + if phase == "unseal-committed" and _is_mutable_dir_posture(opened, identity): + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + _validate_runtime_config_json5( + current[0].data, + posixpath.join(opened.config_path, "openclaw.json"), + identity, + ) + visible_digest = hashlib.sha256(current[0].data).hexdigest() + try: + _clear_journal(identity, opened) + except (OSError, GuardError): + # Mutable posture is already verified and committed; journal + # retirement can be retried without changing visible bytes. + pass + return "restart-unseal-visible", visible_digest, False + + _freeze(opened, identity) + _install_stored_pair(opened, mutable) + installed = _snapshot_pair(opened) + _verify_mutable_files(opened, installed, identity) + _commit_mutable_and_retire_journal(opened, identity) + return "restart-restored-mutable", digest, False + + +def _recover_write_config( + opened: OpenConfig, identity: Identity +) -> tuple[str, str | None]: + try: + record = _read_journal(identity, opened) + except GuardError as exc: + if exc.code != "unsafe-journal" or not _is_partial_frozen_mutable_posture( + opened, identity + ): + raise + record = None + if record is None: + current = _capture_orphan_frozen_mutable(opened, identity) + if current is None: + return "none", None + # Root ownership is the durable discriminator for any kill between the + # parent/config freeze steps and persistent applying-journal publish. + # No replacement begins before that publish. + _commit_mutable_dirs(opened, identity) + return "prepared-preserved", hashlib.sha256(current[0].data).hexdigest() + phase, originals, replacements, new_digest = _decode_journal(record) + _validate_recovery_posture(originals, identity) + _validate_recovery_posture(replacements, identity) + + if phase == "committed" and _is_mutable_dir_posture(opened, identity): + # The committed pair was already exposed. The gateway may have made a + # later legitimate config+hash update before journal cleanup, so retain + # the current coherent pair rather than reinstalling older bytes. + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + visible_digest = hashlib.sha256(current[0].data).hexdigest() + _clear_journal(identity, opened) + return "committed-visible", visible_digest + + # Journal presence proves write-config owned this transition. Freeze before + # inspecting partial paths. A prepared journal precedes all replacements, + # so preserve the current coherent pair (including legitimate gateway writes + # after journal publication). Applying rolls back; committed finishes. + _freeze(opened, identity) + if phase == "prepared": + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + recovery = "prepared-preserved" + recovered_digest = hashlib.sha256(current[0].data).hexdigest() + else: + targets = replacements if phase == "committed" else originals + _install_stored_pair(opened, targets) + recovery = "committed" if phase == "committed" else "rolled-back" + recovered_digest = new_digest if phase == "committed" else None + if phase == "committed": + _snapshot_pair(opened) + _commit_mutable_and_retire_journal(opened, identity) + return recovery, recovered_digest + + +def _rollback_write_config_frozen( + opened: OpenConfig, + identity: Identity, + originals: tuple[FileSnapshot, FileSnapshot], +) -> None: + """Restore a failed write without exposing an applying-journal replay gap.""" + + # Finish revocation if the original exception interrupted either freeze + # step. No persistent journal is retired until both files are restored and + # verified under root-owned directories. + _freeze(opened, identity) + _install_stored_pair(opened, originals) + restored = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, restored, identity) + for actual, expected in zip(restored, originals, strict=True): + if actual.data != expected.data: + raise GuardError( + "rollback-verification-failed", + posixpath.join(opened.config_path, actual.name), + "restored rollback bytes do not match the frozen originals", + ) + + digest = hashlib.sha256(restored[0].data).hexdigest() + preserve_records, _ = _replacement_records( + restored, restored[0].data, identity, time.time_ns() + ) + preserve = _journal_record( + "prepared", + restored, + preserve_records, + digest, + digest, + ) + # Prepared recovery preserves whatever stable raw pair is visible. Publish + # that intent durably before retiring the applying/committed record. + _write_journal(preserve, identity, opened) + _commit_mutable_and_retire_journal(opened, identity) + + +def _write_config( + opened: OpenConfig, + identity: Identity, + expected_sha256: str, + replacement_config: bytes, +) -> str: + initial = _snapshot_raw_pair(opened) + _verify_mutable_posture(opened, initial, identity) + _verify_expected_config(opened, initial[0], expected_sha256) + + commit_time_ns = time.time_ns() + prepared_replacements, new_digest = _replacement_records( + initial, replacement_config, identity, commit_time_ns + ) + _write_journal( + _journal_record( + "prepared", + initial, + prepared_replacements, + expected_sha256, + new_digest, + ), + identity, + ) + + snapshots: list[FileSnapshot] = [] + try: + _freeze(opened, identity, quarantine_reserved=True) + frozen = _snapshot_raw_pair(opened) + snapshots.extend(frozen) + _verify_mutable_files(opened, frozen, identity) + _verify_expected_config(opened, frozen[0], expected_sha256) + + replacement_records, new_digest = _replacement_records( + frozen, replacement_config, identity, commit_time_ns + ) + applying_record = _journal_record( + "applying", frozen, replacement_records, expected_sha256, new_digest + ) + _write_journal(applying_record, identity, opened) + expected_installed = tuple( + _decode_stored_file(value) for value in replacement_records + ) + normalized_installed: list[FileSnapshot] = [] + for snapshot, expected in zip(frozen, expected_installed, strict=True): + installed = _replace_from_snapshot( + opened, + snapshot, + expected.uid, + expected.gid, + expected.mode, + expected.inode_flags, + replacement_data=expected.data, + replacement_atime_ns=expected.atime_ns, + replacement_mtime_ns=expected.mtime_ns, + replacement_xattrs=expected.xattrs, + ) + if installed.st_ino == snapshot.ino: + raise GuardError( + "replacement-failed", + posixpath.join(opened.config_path, snapshot.name), + "fresh inode replacement did not change the inode", + ) + normalized_installed.append( + FileSnapshot( + **{ + **expected.__dict__, + "atime_ns": installed.st_atime_ns, + "mtime_ns": installed.st_mtime_ns, + } + ) + ) + + for expected in normalized_installed: + _verify_file( + opened, + expected.name, + identity.sandbox_uid, + identity.sandbox_gid, + 0o660, + expected, + ) + # Validate the exact pair that will become visible before returning + # directory ownership to the sandbox. + installed_pair = _snapshot_pair(opened) + if installed_pair[0].data != replacement_config: + raise GuardError( + "verification-failed", + posixpath.join(opened.config_path, "openclaw.json"), + "installed config bytes changed before mutable commit", + ) + committed_record = { + **applying_record, + "phase": "committed", + "replacement": [_stored_file(item) for item in normalized_installed], + } + _write_journal(committed_record, identity, opened) + _commit_mutable_and_retire_journal(opened, identity) + return new_digest + except Exception as exc: + rollback_allowed = not isinstance(exc, MutableHandoffError) + rollback_errors: list[str] = [] + if rollback_allowed: + rollback_targets = ( + (snapshots[0], snapshots[1]) if len(snapshots) == 2 else initial + ) + try: + _rollback_write_config_frozen(opened, identity, rollback_targets) + except Exception as rollback_exc: + rollback_errors.append(str(rollback_exc)) + rollback_errors.extend(_force_fail_closed_lock(opened, identity)) + detail = str(exc) + if rollback_errors: + detail += "; rollback issues: " + "; ".join(rollback_errors) + if isinstance(exc, GuardError): + raise GuardError(exc.code, exc.path, detail) from exc + raise GuardError("write-config-failed", opened.config_path, detail) from exc + + +def _recover_any_transaction( + opened: OpenConfig, + identity: Identity, + pending: dict[str, object] | None, +) -> tuple[str, str | None, bool | None]: + if pending is None: + if _has_clamped_locked_dir_posture(opened, identity): + current = _snapshot_pair(opened) + _verify_locked_files(opened, current, identity) + return ( + "clamped-lock-preserved", + hashlib.sha256(current[0].data).hexdigest(), + True, + ) + if _is_partial_frozen_mutable_posture(opened, identity): + partial = _snapshot_raw_pair(opened) + mutable_files = all( + item.uid == identity.sandbox_uid + and item.gid == identity.sandbox_gid + and item.mode == 0o660 + for item in partial + ) + if mutable_files: + _commit_mutable_dirs(opened, identity) + return ( + "orphan-freeze-restored", + hashlib.sha256(partial[0].data).hexdigest(), + False, + ) + targets, digest = _canonical_targets(partial, identity, locked=True) + _install_stored_pair(opened, targets) + _commit_locked_dirs(opened, identity) + return "orphan-lock-completed", digest, True + if _has_locked_dir_posture(opened, identity): + current = _snapshot_pair(opened) + _verify_locked_files(opened, current, identity) + return "none", hashlib.sha256(current[0].data).hexdigest(), True + return "none", None, False + journal_action = pending.get("action") + if journal_action == "restart-seal": + return _recover_restart(opened, identity, pending) + if journal_action == "write-config": + recovery, digest = _recover_write_config(opened, identity) + return recovery, digest, False + raise GuardError( + "invalid-journal", JOURNAL_PATH, "journal action is not recognized" + ) + + +def _clear_untrusted_mutable_reserved_entry( + opened: OpenConfig, identity: Identity +) -> tuple[str, str]: + _freeze(opened, identity) + _quarantine_untrusted_persistent_journal(opened, identity) + current = _snapshot_raw_pair(opened) + _verify_mutable_files(opened, current, identity) + _commit_mutable_dirs(opened, identity) + return "untrusted-journal-cleared", hashlib.sha256(current[0].data).hexdigest() + + +def _contain_partial_replay(opened: OpenConfig, identity: Identity) -> tuple[str, str]: + _freeze(opened, identity) + _quarantine_untrusted_persistent_journal(opened, identity) + _force_fail_closed_lock(opened, identity) + if not _has_locked_dir_posture(opened, identity): + raise GuardError( + "fail-closed-incomplete", + opened.config_path, + "could not contain ambiguous persistent journal replay", + ) + current = _snapshot_pair(opened) + return "ambiguous-replay-locked", hashlib.sha256(current[0].data).hexdigest() + + +def _production_identity() -> Identity: + try: + sandbox_user = pwd.getpwnam("sandbox") + sandbox_group = grp.getgrnam("sandbox") + except KeyError as exc: + raise GuardError( + "identity-missing", "", "sandbox user and group must exist" + ) from exc + return Identity( + root_uid=0, + root_gid=0, + sandbox_uid=sandbox_user.pw_uid, + sandbox_gid=sandbox_group.gr_gid, + ) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", + choices=( + "preflight", + "preflight-restart", + "lock", + "unlock", + "seal-restart", + "unseal-restart", + "revoke-startup-ready", + "publish-startup-ready", + "write-config", + "recover", + ), + ) + parser.add_argument("--config-dir", default=PRODUCTION_CONFIG_DIR) + parser.add_argument("--expected-config-sha256", default="") + parser.add_argument("--startup-owner", action="store_true") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = _parser().parse_args(argv) + action: Action = args.action + if os.geteuid() != 0: + error = GuardError("root-required", args.config_dir, "helper must run as root") + print(json.dumps(error.as_json(), sort_keys=True)) + print( + json.dumps( + {"type": "result", "action": action, "status": "failed"}, + sort_keys=True, + ) + ) + return 1 + + opened: OpenConfig | None = None + mutex: MutationMutex | None = None + try: + normalized_config = posixpath.normpath(args.config_dir) + if normalized_config != PRODUCTION_CONFIG_DIR: + raise GuardError( + "invalid-config-path", + args.config_dir, + f"helper is restricted to {PRODUCTION_CONFIG_DIR}", + ) + identity = _production_identity() + _validate_action_readiness(action, args.startup_owner, identity) + read_only = action in {"preflight", "preflight-restart"} + mutex = _acquire_mutation_mutex(action, identity, exclusive=not read_only) + + if action in {"revoke-startup-ready", "publish-startup-ready"}: + if action == "revoke-startup-ready": + _revoke_startup_ready(identity) + else: + _write_startup_ready(identity) + print( + json.dumps( + { + "type": "result", + "action": action, + "status": "ok", + "configDir": normalized_config, + }, + sort_keys=True, + ) + ) + return 0 + + replacement_config: bytes | None = None + if action == "write-config": + if not re.fullmatch(r"[0-9a-fA-F]{64}", args.expected_config_sha256): + raise GuardError( + "invalid-expected-sha256", + "--expected-config-sha256", + "write-config requires exactly 64 hexadecimal characters", + ) + replacement_config = _read_replacement_config() + + opened = ( + _open_config_for_lock(args.config_dir, identity) + if action == "lock" + else _open_config(args.config_dir) + ) + untrusted_reserved_entry = False + if action == "lock": + # Lock freezes both namespace levels before journal inspection so + # a last-moment sandbox swap cannot veto containment. + pending_journal = None + else: + try: + pending_journal = _read_journal(identity, opened) + except GuardError as exc: + persistent_display = posixpath.join( + opened.config_path, PERSISTENT_JOURNAL_NAME + ) + # Never reinterpret a bad /etc journal. Only an unsafe persistent + # entry in the exact mutable tree, with no trusted secondary, is a + # sandbox-planted nonauthority. + if exc.path != persistent_display: + raise + secondary = _read_secondary_journal(identity) + replay_without_secondary = ( + exc.code == "persistent-journal-without-secondary" + and secondary is None + and ( + _is_mutable_dir_posture(opened, identity) + or _is_partial_frozen_mutable_posture(opened, identity) + ) + ) + if secondary is not None or not ( + replay_without_secondary + or _mutable_reserved_entry_is_nonauthoritative(opened, identity) + ): + raise + pending_journal = None + untrusted_reserved_entry = True + + if action == "lock" and pending_journal is not None: + # Deadline/manual relock cannot be vetoed by an interrupted config + # write or restart seal. Recover under this same mutex, then seal. + _recover_any_transaction(opened, identity, pending_journal) + pending_journal = None + elif ( + action not in {"recover", "unseal-restart"} and pending_journal is not None + ): + raise GuardError( + "recovery-required", + JOURNAL_PATH, + "an interrupted config transaction must be recovered first", + ) + + if read_only and _is_partial_frozen_mutable_posture(opened, identity): + raise GuardError( + "recovery-required", + opened.config_path, + "a partially frozen config transaction must be recovered first", + ) + + recovery: str | None = None + original_locked: bool | None = None + if action == "preflight": + _preflight(opened) + new_digest = None + elif action == "preflight-restart": + _preflight_restart(opened, identity) + new_digest = None + elif action == "seal-restart": + original_locked = _seal_restart( + opened, + identity, + quarantine_untrusted=untrusted_reserved_entry, + ) + new_digest = hashlib.sha256( + _snapshot_file(opened, "openclaw.json").data + ).hexdigest() + elif action == "unseal-restart": + if ( + pending_journal is not None + and pending_journal.get("action") != "restart-seal" + ): + raise GuardError( + "recovery-required", + JOURNAL_PATH, + "non-restart transaction must be recovered before unseal", + ) + original_locked = _unseal_restart(opened, identity, pending_journal) + new_digest = hashlib.sha256( + _snapshot_file(opened, "openclaw.json").data + ).hexdigest() + elif action == "write-config": + if replacement_config is None: # Narrow the optional type. + raise GuardError( + "invalid-config-json", "stdin", "replacement config is missing" + ) + new_digest = _write_config( + opened, + identity, + args.expected_config_sha256, + replacement_config, + ) + recovery = None + elif action == "recover": + if untrusted_reserved_entry: + if _is_partial_frozen_mutable_posture(opened, identity): + recovery, new_digest = _contain_partial_replay(opened, identity) + original_locked = True + else: + recovery, new_digest = _clear_untrusted_mutable_reserved_entry( + opened, identity + ) + original_locked = False + else: + recovery, new_digest, original_locked = _recover_any_transaction( + opened, identity, pending_journal + ) + else: + _transition( + action, + opened, + identity, + quarantine_untrusted=untrusted_reserved_entry, + ) + new_digest = None + recovery = None + if action in {"preflight", "preflight-restart"}: + recovery = None + print( + json.dumps( + { + "type": "result", + "action": action, + "status": "ok", + "configDir": opened.config_path, + "files": list(CONFIG_FILES), + "chattrApplied": False, + **({"configSha256": new_digest} if new_digest is not None else {}), + **({"recovery": recovery} if recovery is not None else {}), + **( + {"originalLocked": original_locked} + if original_locked is not None + else {} + ), + }, + sort_keys=True, + ) + ) + return 0 + except GuardError as exc: + print(json.dumps(exc.as_json(), sort_keys=True)) + print( + json.dumps( + {"type": "result", "action": action, "status": "failed"}, + sort_keys=True, + ) + ) + return 1 + except OSError as exc: + error = GuardError("operation-failed", args.config_dir, str(exc)) + print(json.dumps(error.as_json(), sort_keys=True)) + print( + json.dumps( + {"type": "result", "action": action, "status": "failed"}, + sort_keys=True, + ) + ) + return 1 + finally: + if opened is not None: + opened.close() + if mutex is not None: + try: + _release_mutation_mutex(mutex) + except (OSError, GuardError): + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/state-dir-guard.py b/scripts/state-dir-guard.py new file mode 100755 index 00000000000..48c2fe31069 --- /dev/null +++ b/scripts/state-dir-guard.py @@ -0,0 +1,1915 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Descriptor-safe recursive state-directory shields transitions. + +The host invokes this helper as root inside an agent sandbox. It deliberately +does not use ``chown -R``/``chmod -R``: every traversal is rooted at an already +opened directory descriptor and every descent uses ``O_NOFOLLOW``. Locking +also replaces regular files with fresh inodes so a sandbox process cannot keep +mutating the visible file through a writable descriptor opened before shields +went up. Extended attributes (including ACL storage) are copied when the +container Python exposes the descriptor-based xattr API; the shipped Linux +images do. The final chmod clamps any copied ACL mask to the shields mode. +""" + +from __future__ import annotations + +import argparse +import errno +import fcntl +import grp +import json +import os +import posixpath +import pwd +import secrets +import stat +import struct +import sys +import time +from dataclasses import dataclass, field +from typing import Literal + + +HIGH_RISK_STATE_DIRS = frozenset( + { + "skills", + "agent", + "hooks", + "cron", + "agents", + "extensions", + "plugins", + "workspace", + "memory", + "devices", + "canvas", + "telegram", + "wechat", + "whatsapp", + "platforms", + "weixin", + "profiles", + "skins", + } +) +CONFIDENTIALITY_STATE_DIRS = frozenset({"credentials", "identity", "pairing"}) +MAX_SYMLINK_EXPANSIONS = 40 +MAX_TRAVERSAL_DEPTH = 256 +STABLE_COPY_ATTEMPTS = 3 +COPY_BUFFER_BYTES = 1024 * 1024 +MAX_ENTRIES_PER_PASS = 100_000 +MAX_LOGICAL_BYTES_PER_PASS = 16 * 1024 * 1024 * 1024 +MAX_ALLOCATED_BYTES_PER_PASS = 8 * 1024 * 1024 * 1024 +MAX_COPIED_BYTES_PER_PASS = 8 * 1024 * 1024 * 1024 +MAX_GUARD_SECONDS = 10 * 60 +PRODUCTION_FAIL_CLOSED_CONFIG_DIRS = frozenset( + {"/sandbox/.openclaw", "/sandbox/.hermes"} +) +OPENCLAW_MUTATION_MUTEX_PATH = "/run/nemoclaw/openclaw-config-mutation.lock" +FS_IMMUTABLE_FL = 0x00000010 +FS_APPEND_FL = 0x00000020 +FS_IOC_GETFLAGS = 0x80086601 +FS_IOC_SETFLAGS = 0x40086602 + +Action = Literal["preflight", "lock", "unlock"] +Policy = Literal["high-risk", "confidentiality"] + + +@dataclass(frozen=True) +class Identity: + root_uid: int + root_gid: int + sandbox_uid: int + sandbox_gid: int + + +@dataclass(frozen=True) +class Issue: + code: str + path: str + detail: str + + def as_json(self) -> dict[str, str]: + return { + "type": "issue", + "code": self.code, + "path": self.path, + "detail": self.detail, + } + + +@dataclass(frozen=True) +class RootSpec: + name: str + policy: Policy + dev: int + ino: int + + +@dataclass +class GuardResult: + action: Action + issues: list[Issue] = field(default_factory=list) + roots: int = 0 + directories: int = 0 + files: int = 0 + symlinks: int = 0 + removed_entries: int = 0 + + @property + def ok(self) -> bool: + return not self.issues + + def summary_json(self) -> dict[str, object]: + return { + "type": "result", + "action": self.action, + "status": "ok" if self.ok else "failed", + "roots": self.roots, + "directories": self.directories, + "files": self.files, + "symlinks": self.symlinks, + "removedEntries": self.removed_entries, + "issueCount": len(self.issues), + } + + +class GuardOperationError(RuntimeError): + def __init__(self, issue: Issue): + super().__init__(issue.detail) + self.issue = issue + + +@dataclass +class WorkBudget: + deadline: float + entries: int = 0 + logical_bytes: int = 0 + allocated_bytes: int = 0 + copied_bytes: int = 0 + + def check_time(self, path: str) -> None: + if time.monotonic() > self.deadline: + raise GuardOperationError( + Issue( + "work-time-limit", + path, + f"state-dir guard exceeded {MAX_GUARD_SECONDS} seconds", + ) + ) + + def observe_entry(self, path: str, entry: os.stat_result) -> None: + self.check_time(path) + self.entries += 1 + if self.entries > MAX_ENTRIES_PER_PASS: + raise GuardOperationError( + Issue( + "work-entry-limit", + path, + f"state tree exceeds {MAX_ENTRIES_PER_PASS} entries in one pass", + ) + ) + if not stat.S_ISREG(entry.st_mode): + return + self.logical_bytes += max(0, entry.st_size) + self.allocated_bytes += max(0, getattr(entry, "st_blocks", 0) * 512) + if self.logical_bytes > MAX_LOGICAL_BYTES_PER_PASS: + raise GuardOperationError( + Issue( + "work-logical-byte-limit", + path, + f"state tree exceeds {MAX_LOGICAL_BYTES_PER_PASS} logical bytes", + ) + ) + if self.allocated_bytes > MAX_ALLOCATED_BYTES_PER_PASS: + raise GuardOperationError( + Issue( + "work-allocated-byte-limit", + path, + f"state tree exceeds {MAX_ALLOCATED_BYTES_PER_PASS} allocated bytes", + ) + ) + + def account_copy(self, path: str, size: int) -> None: + self.check_time(path) + self.copied_bytes += size + if self.copied_bytes > MAX_COPIED_BYTES_PER_PASS: + raise GuardOperationError( + Issue( + "work-copy-byte-limit", + path, + f"state lock exceeds {MAX_COPIED_BYTES_PER_PASS} copied data bytes", + ) + ) + + +def _is_runtime_carveout(relative_path: str) -> bool: + """Return whether this is OpenClaw's intentional writable sessions root.""" + + parts = relative_path.split("/") + return ( + len(parts) == 3 + and parts[0] == "agents" + and parts[1] not in {"", ".", ".."} + and parts[2] == "sessions" + ) + + +def _is_under_runtime_carveout(relative_path: str) -> bool: + parts = relative_path.split("/") + return ( + len(parts) >= 3 + and parts[0] == "agents" + and parts[1] not in {"", ".", ".."} + and parts[2] == "sessions" + ) + + +def _no_follow_flag() -> int: + flag = getattr(os, "O_NOFOLLOW", 0) + if not flag: + raise GuardOperationError( + Issue("unsupported-platform", "", "O_NOFOLLOW is unavailable") + ) + return flag + + +def _directory_flags() -> int: + flag = getattr(os, "O_DIRECTORY", 0) + if not flag: + raise GuardOperationError( + Issue("unsupported-platform", "", "O_DIRECTORY is unavailable") + ) + return os.O_RDONLY | flag | _no_follow_flag() | getattr(os, "O_CLOEXEC", 0) + + +def _file_flags() -> int: + return os.O_RDONLY | _no_follow_flag() | getattr(os, "O_CLOEXEC", 0) + + +def _get_inode_flags(fd: int) -> int | None: + try: + raw = fcntl.ioctl(fd, FS_IOC_GETFLAGS, struct.pack("I", 0)) + return int(struct.unpack("I", raw)[0]) + except OSError as exc: + if exc.errno in {errno.ENOTTY, errno.EOPNOTSUPP, errno.ENOSYS, errno.EINVAL}: + return None + raise + + +def _set_inode_flags(fd: int, flags: int | None) -> None: + if flags is None: + return + try: + fcntl.ioctl(fd, FS_IOC_SETFLAGS, struct.pack("I", flags)) + except OSError as exc: + if exc.errno in {errno.ENOTTY, errno.EOPNOTSUPP, errno.ENOSYS, errno.EINVAL}: + return + raise + + +def _clear_mutation_flags(fd: int) -> int | None: + original = _get_inode_flags(fd) + if original is not None and original & (FS_IMMUTABLE_FL | FS_APPEND_FL): + _set_inode_flags(fd, original & ~(FS_IMMUTABLE_FL | FS_APPEND_FL)) + return original + + +def _display_path(config_path: str, relative_path: str) -> str: + if not relative_path: + return config_path + return posixpath.join(config_path, relative_path) + + +def _os_issue(code: str, path: str, operation: str, exc: OSError) -> Issue: + return Issue(code, path, f"{operation} failed: {exc.strerror or exc}") + + +def _same_entry(first: os.stat_result, second: os.stat_result) -> bool: + return first.st_dev == second.st_dev and first.st_ino == second.st_ino + + +def _bounded_directory_names( + dir_fd: int, + path: str, + budget: WorkBudget | None = None, +) -> list[str]: + names: list[str] = [] + with os.scandir(dir_fd) as entries: + for entry in entries: + if budget is not None: + budget.check_time(path) + names.append(entry.name) + if len(names) > MAX_ENTRIES_PER_PASS: + raise GuardOperationError( + Issue( + "work-entry-limit", + path, + f"directory exceeds {MAX_ENTRIES_PER_PASS} entries", + ) + ) + names.sort() + return names + + +def _open_absolute_dir_nofollow(path: str) -> int: + if not posixpath.isabs(path): + raise GuardOperationError( + Issue("invalid-config-path", path, "config directory must be absolute") + ) + normalized = posixpath.normpath(path) + fd = os.open("/", _directory_flags()) + try: + for component in normalized.split("/"): + if not component: + continue + next_fd = os.open(component, _directory_flags(), dir_fd=fd) + os.close(fd) + fd = next_fd + return fd + except Exception: + os.close(fd) + raise + + +def _open_child_dir(parent_fd: int, name: str, expected: os.stat_result) -> int: + child_fd = os.open(name, _directory_flags(), dir_fd=parent_fd) + actual = os.fstat(child_fd) + if not _same_entry(expected, actual): + os.close(child_fd) + raise GuardOperationError( + Issue("entry-raced", name, "directory changed while it was being opened") + ) + return child_fd + + +def _entry_kind(st: os.stat_result) -> str: + mode = st.st_mode + if stat.S_ISDIR(mode): + return "directory" + if stat.S_ISREG(mode): + return "regular file" + if stat.S_ISLNK(mode): + return "symlink" + if stat.S_ISFIFO(mode): + return "FIFO" + if stat.S_ISSOCK(mode): + return "socket" + if stat.S_ISCHR(mode): + return "character device" + if stat.S_ISBLK(mode): + return "block device" + return "unknown entry" + + +def _policy_for_root(name: str) -> Policy | None: + if name in CONFIDENTIALITY_STATE_DIRS: + return "confidentiality" + if name in HIGH_RISK_STATE_DIRS or name.startswith("workspace-"): + return "high-risk" + return None + + +def _select_roots( + config_fd: int, config_path: str, config_dev: int +) -> tuple[list[RootSpec], list[Issue]]: + issues: list[Issue] = [] + try: + present_names = set(_bounded_directory_names(config_fd, config_path)) + except OSError as exc: + return [], [_os_issue("list-failed", config_path, "list config directory", exc)] + + selected_names = sorted( + name for name in present_names if _policy_for_root(name) is not None + ) + roots: list[RootSpec] = [] + for name in selected_names: + path = _display_path(config_path, name) + try: + st = os.stat(name, dir_fd=config_fd, follow_symlinks=False) + except OSError as exc: + issues.append(_os_issue("stat-failed", path, "stat state-dir root", exc)) + continue + if st.st_dev != config_dev: + issues.append( + Issue( + "cross-device-entry", + path, + "state-dir root is on a different filesystem", + ) + ) + continue + if stat.S_ISLNK(st.st_mode): + issues.append( + Issue( + "state-root-symlink", path, "state-dir roots must not be symlinks" + ) + ) + continue + if not stat.S_ISDIR(st.st_mode): + issues.append( + Issue( + "state-root-not-directory", + path, + f"state-dir root is a {_entry_kind(st)}, not a directory", + ) + ) + continue + policy = _policy_for_root(name) + if policy is None: # The name came from the same predicate above. + continue + roots.append(RootSpec(name=name, policy=policy, dev=st.st_dev, ino=st.st_ino)) + return roots, issues + + +def _remove_unsupported_root_entries_for_lock( + config_fd: int, config_path: str, config_dev: int +) -> int: + """Remove attacker-created protected-root names that cannot be traversed. + + The caller has already frozen the top-level config directory. Removing a + symlink/FIFO/file at a name whose shields contract requires a directory is + therefore descriptor-relative and cannot follow or affect its target. A + hard failure (including a cross-device mount) remains fail-closed. + """ + + removed = 0 + for name in _bounded_directory_names(config_fd, config_path): + if _policy_for_root(name) is None: + continue + path = _display_path(config_path, name) + st = os.stat(name, dir_fd=config_fd, follow_symlinks=False) + if st.st_dev != config_dev: + raise GuardOperationError( + Issue( + "cross-device-entry", + path, + "state-dir root is on a different filesystem", + ) + ) + if stat.S_ISDIR(st.st_mode): + continue + current = os.stat(name, dir_fd=config_fd, follow_symlinks=False) + if not _same_entry(st, current): + raise GuardOperationError( + Issue( + "entry-raced", + path, + "unsupported state-dir root changed before removal", + ) + ) + try: + os.unlink(name, dir_fd=config_fd) + os.fsync(config_fd) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "unsafe-entry-remove-failed", + path, + "remove unsupported state-dir root", + exc, + ) + ) from exc + removed += 1 + return removed + + +@dataclass +class TraversalContext: + config_fd: int + config_path: str + config_dev: int + protected_roots: tuple[str, ...] + budget: WorkBudget + + def display(self, relative_path: str) -> str: + return _display_path(self.config_path, relative_path) + + def is_protected(self, relative_path: str) -> bool: + return any( + relative_path == root or relative_path.startswith(f"{root}/") + for root in self.protected_roots + ) + + +def _normalize_link_target( + context: TraversalContext, + link_parent: str, + target: str, +) -> str: + if posixpath.isabs(target): + normalized_absolute = posixpath.normpath(target) + try: + within_config = ( + posixpath.commonpath([context.config_path, normalized_absolute]) + == context.config_path + ) + except ValueError: + within_config = False + if not within_config: + raise GuardOperationError( + Issue( + "symlink-outside-protected-root", + normalized_absolute, + "absolute symlink target is outside the config directory", + ) + ) + relative = posixpath.relpath(normalized_absolute, context.config_path) + else: + relative = posixpath.normpath(posixpath.join(link_parent, target)) + + if relative in {"", "."} or relative == ".." or relative.startswith("../"): + raise GuardOperationError( + Issue( + "symlink-outside-protected-root", + target, + "symlink target escapes the config directory", + ) + ) + if not context.is_protected(relative): + raise GuardOperationError( + Issue( + "symlink-outside-protected-root", + target, + "symlink target is not inside a protected state-dir root", + ) + ) + return relative + + +def _resolve_internal_symlink( + context: TraversalContext, + link_relative_path: str, + target: str, +) -> None: + """Resolve a link without ever asking the kernel to follow a symlink.""" + + relative = _normalize_link_target( + context, posixpath.dirname(link_relative_path), target + ) + if _is_under_runtime_carveout(link_relative_path) or _is_under_runtime_carveout( + relative + ): + raise GuardOperationError( + Issue( + "symlink-crosses-runtime-carveout", + context.display(link_relative_path), + "symlinks may not enter or originate in the writable sessions carveout", + ) + ) + seen: set[str] = set() + expansions = 0 + + while True: + if relative in seen: + raise GuardOperationError( + Issue( + "symlink-cycle", + context.display(link_relative_path), + "internal symlink chain contains a cycle", + ) + ) + seen.add(relative) + components = relative.split("/") + current_fd = os.dup(context.config_fd) + resolved_parts: list[str] = [] + restart = False + try: + for index, component in enumerate(components): + current_relative = "/".join([*resolved_parts, component]) + current_path = context.display(current_relative) + try: + st = os.stat(component, dir_fd=current_fd, follow_symlinks=False) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "symlink-target-unavailable", + current_path, + "stat symlink target", + exc, + ) + ) from exc + if st.st_dev != context.config_dev: + raise GuardOperationError( + Issue( + "cross-device-entry", + current_path, + "symlink target crosses to a different filesystem", + ) + ) + remaining = components[index + 1 :] + if stat.S_ISLNK(st.st_mode): + if st.st_nlink != 1: + raise GuardOperationError( + Issue( + "hardlinked-entry", + current_path, + f"symlink has link count {st.st_nlink}, expected 1", + ) + ) + expansions += 1 + if expansions > MAX_SYMLINK_EXPANSIONS: + raise GuardOperationError( + Issue( + "too-many-symlinks", + context.display(link_relative_path), + "internal symlink chain is too deep", + ) + ) + nested_target = os.readlink(component, dir_fd=current_fd) + expanded = _normalize_link_target( + context, "/".join(resolved_parts), nested_target + ) + relative = posixpath.normpath(posixpath.join(expanded, *remaining)) + if not context.is_protected(relative): + raise GuardOperationError( + Issue( + "symlink-outside-protected-root", + context.display(link_relative_path), + "expanded symlink target leaves protected roots", + ) + ) + if _is_under_runtime_carveout(relative): + raise GuardOperationError( + Issue( + "symlink-crosses-runtime-carveout", + context.display(link_relative_path), + "symlink chain enters the writable sessions carveout", + ) + ) + restart = True + break + if remaining: + if not stat.S_ISDIR(st.st_mode): + raise GuardOperationError( + Issue( + "symlink-target-invalid", + current_path, + "non-directory occurs before the end of a symlink target", + ) + ) + next_fd = _open_child_dir(current_fd, component, st) + os.close(current_fd) + current_fd = next_fd + resolved_parts.append(component) + continue + if not (stat.S_ISDIR(st.st_mode) or stat.S_ISREG(st.st_mode)): + raise GuardOperationError( + Issue( + "special-entry", + current_path, + f"symlink resolves to a {_entry_kind(st)}", + ) + ) + if stat.S_ISREG(st.st_mode) and st.st_nlink != 1: + raise GuardOperationError( + Issue( + "hardlinked-entry", + current_path, + f"regular file has link count {st.st_nlink}, expected 1", + ) + ) + finally: + os.close(current_fd) + if restart: + continue + return + + +def _validate_symlink( + context: TraversalContext, + parent_fd: int, + name: str, + relative_path: str, + st: os.stat_result, +) -> Issue | None: + path = context.display(relative_path) + if st.st_dev != context.config_dev: + return Issue("cross-device-entry", path, "symlink is on a different filesystem") + if st.st_nlink != 1: + return Issue( + "hardlinked-entry", + path, + f"symlink has link count {st.st_nlink}, expected 1", + ) + try: + target = os.readlink(name, dir_fd=parent_fd) + _resolve_internal_symlink(context, relative_path, target) + except GuardOperationError as exc: + return Issue(exc.issue.code, path, exc.issue.detail) + except OSError as exc: + return _os_issue("readlink-failed", path, "read symlink", exc) + return None + + +def _scan_dir( + context: TraversalContext, + dir_fd: int, + relative_dir: str, + issues: list[Issue], + depth: int, + action: Action, +) -> None: + if depth > MAX_TRAVERSAL_DEPTH: + issues.append( + Issue( + "tree-too-deep", + context.display(relative_dir), + f"state tree exceeds {MAX_TRAVERSAL_DEPTH} directory levels", + ) + ) + return + try: + names = _bounded_directory_names( + dir_fd, context.display(relative_dir), context.budget + ) + except OSError as exc: + issues.append( + _os_issue( + "list-failed", context.display(relative_dir), "list directory", exc + ) + ) + return + + for name in names: + relative_path = posixpath.join(relative_dir, name) + path = context.display(relative_path) + try: + st = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) + except OSError as exc: + issues.append(_os_issue("stat-failed", path, "stat entry", exc)) + continue + context.budget.observe_entry(path, st) + if st.st_dev != context.config_dev: + issues.append( + Issue("cross-device-entry", path, "entry is on a different filesystem") + ) + continue + if stat.S_ISDIR(st.st_mode): + # Session contents are intentionally outside the shields integrity + # boundary and remain live while shields are up. Validate that the + # carve-out itself is a real in-tree directory, but do not traverse + # a subtree the gateway may be appending to concurrently. + if _is_runtime_carveout(relative_path): + continue + try: + child_fd = _open_child_dir(dir_fd, name, st) + except (OSError, GuardOperationError) as exc: + if isinstance(exc, GuardOperationError): + issues.append(Issue(exc.issue.code, path, exc.issue.detail)) + else: + issues.append(_os_issue("open-failed", path, "open directory", exc)) + continue + try: + _scan_dir(context, child_fd, relative_path, issues, depth + 1, action) + finally: + os.close(child_fd) + elif stat.S_ISREG(st.st_mode): + if action != "lock" and st.st_nlink != 1: + issues.append( + Issue( + "hardlinked-entry", + path, + f"regular file has link count {st.st_nlink}, expected 1", + ) + ) + elif stat.S_ISLNK(st.st_mode): + issue = _validate_symlink(context, dir_fd, name, relative_path, st) + if action != "lock" and issue is not None: + issues.append(issue) + else: + if action != "lock": + issues.append( + Issue( + "special-entry", + path, + f"state tree contains a {_entry_kind(st)}", + ) + ) + + +def _preflight( + config_fd: int, + config_path: str, + config_dev: int, + deadline: float, + action: Action, +) -> tuple[list[RootSpec], list[Issue]]: + roots, issues = _select_roots(config_fd, config_path, config_dev) + protected_roots = tuple(root.name for root in roots) + context = TraversalContext( + config_fd, + config_path, + config_dev, + protected_roots, + WorkBudget(deadline), + ) + for root in roots: + path = context.display(root.name) + try: + root_lstat = os.stat(root.name, dir_fd=config_fd, follow_symlinks=False) + context.budget.observe_entry(path, root_lstat) + root_fd = _open_child_dir(config_fd, root.name, root_lstat) + except (OSError, GuardOperationError) as exc: + if isinstance(exc, GuardOperationError): + issues.append(Issue(exc.issue.code, path, exc.issue.detail)) + else: + issues.append( + _os_issue("open-failed", path, "open state-dir root", exc) + ) + continue + try: + _scan_dir(context, root_fd, root.name, issues, 1, action) + finally: + os.close(root_fd) + return roots, issues + + +def _expected_ids( + policy: Policy, action: Action, identity: Identity +) -> tuple[int, int]: + if action == "unlock": + return identity.sandbox_uid, identity.sandbox_gid + if policy == "confidentiality": + return identity.root_uid, identity.root_gid + return identity.root_uid, identity.sandbox_gid + + +def _expected_dir_mode(policy: Policy, action: Action) -> int: + if action == "unlock": + return 0o2770 + return 0o700 if policy == "confidentiality" else 0o755 + + +def _expected_file_mode(policy: Policy, action: Action, old_mode: int) -> int: + old_mode &= 0o777 + if action == "unlock": + # chmod g+rwX,o-rwx: preserve owner bits; group gets rw and gets x only + # when the file was executable by somebody before the transition. + return (old_mode & 0o700) | 0o060 | (0o010 if old_mode & 0o111 else 0) + if policy == "confidentiality": + return old_mode & 0o700 + return old_mode & ~0o022 + + +def _freeze_dir_for_lock(dir_fd: int) -> None: + current = stat.S_IMODE(os.fstat(dir_fd).st_mode) + os.fchmod(dir_fd, current & 0o555) + + +def _set_dir_metadata( + dir_fd: int, + policy: Policy, + action: Action, + identity: Identity, +) -> None: + uid, gid = _expected_ids(policy, action, identity) + os.fchown(dir_fd, uid, gid) + os.fchmod(dir_fd, _expected_dir_mode(policy, action)) + + +def _copy_extent( + source_fd: int, + temp_fd: int, + length: int, + context: TraversalContext, + path: str, +) -> None: + remaining = length + while remaining > 0: + context.budget.check_time(path) + chunk = os.read(source_fd, min(COPY_BUFFER_BYTES, remaining)) + if not chunk: + raise OSError(errno.EIO, "unexpected EOF while copying state file") + context.budget.account_copy(path, len(chunk)) + view = memoryview(chunk) + while view: + written = os.write(temp_fd, view) + if written <= 0: + raise OSError(errno.EIO, "short write while copying state file") + view = view[written:] + remaining -= len(chunk) + + +def _copy_file_sparse_aware( + source_fd: int, + temp_fd: int, + size: int, + context: TraversalContext, + path: str, +) -> None: + seek_data = getattr(os, "SEEK_DATA", None) + seek_hole = getattr(os, "SEEK_HOLE", None) + if seek_data is not None and seek_hole is not None: + try: + os.ftruncate(temp_fd, size) + offset = 0 + while offset < size: + context.budget.check_time(path) + try: + data_offset = os.lseek(source_fd, offset, seek_data) + except OSError as exc: + if exc.errno == errno.ENXIO: + return + raise + hole_offset = min(size, os.lseek(source_fd, data_offset, seek_hole)) + os.lseek(source_fd, data_offset, os.SEEK_SET) + os.lseek(temp_fd, data_offset, os.SEEK_SET) + _copy_extent( + source_fd, + temp_fd, + hole_offset - data_offset, + context, + path, + ) + offset = hole_offset + return + except OSError as exc: + if exc.errno not in {errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP}: + raise + # Filesystem does not implement SEEK_DATA/SEEK_HOLE. Reset the + # partially staged file before the bounded dense fallback. + os.ftruncate(temp_fd, 0) + os.lseek(source_fd, 0, os.SEEK_SET) + os.lseek(temp_fd, 0, os.SEEK_SET) + + _copy_extent(source_fd, temp_fd, size, context, path) + + +def _copy_stable_file_to_temp( + parent_fd: int, + name: str, + relative_path: str, + context: TraversalContext, + policy: Policy, + identity: Identity, +) -> int: + path = context.display(relative_path) + for attempt in range(STABLE_COPY_ATTEMPTS): + source_fd = -1 + temp_fd = -1 + source_flags: int | None = None + replaced = False + temp_name = f".nemoclaw-state-dir-{secrets.token_hex(12)}.tmp" + try: + source_fd = os.open(name, _file_flags(), dir_fd=parent_fd) + before = os.fstat(source_fd) + if not stat.S_ISREG(before.st_mode): + raise GuardOperationError( + Issue("entry-raced", path, "file changed type while being opened") + ) + if before.st_dev != context.config_dev: + raise GuardOperationError( + Issue( + "cross-device-entry", path, "file is on a different filesystem" + ) + ) + # A hardlink is severed by the fresh-inode replacement below. Do + # not clear immutable/append flags on a multiply-linked source: + # those flags belong to every link, potentially including a path + # outside this state tree. + source_flags = _get_inode_flags(source_fd) + if before.st_nlink == 1: + source_flags = _clear_mutation_flags(source_fd) + temp_fd = os.open( + temp_name, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | _no_follow_flag() + | getattr(os, "O_CLOEXEC", 0), + 0o600, + dir_fd=parent_fd, + ) + try: + _copy_file_sparse_aware( + source_fd, + temp_fd, + before.st_size, + context, + path, + ) + except OSError as exc: + # At the containment deadline a writer holding an old FD must + # not veto fresh-inode publication forever. On the final + # attempt, a concurrent shrink can yield EIO after a bounded + # partial copy; publish those captured bytes and report any + # application-level damage after the stale FD is detached. + if attempt + 1 < STABLE_COPY_ATTEMPTS or exc.errno != errno.EIO: + raise + after = os.fstat(source_fd) + stable = ( + _same_entry(before, after) + and before.st_size == after.st_size + and before.st_mtime_ns == after.st_mtime_ns + and before.st_ctime_ns == after.st_ctime_ns + ) + if not stable and attempt + 1 < STABLE_COPY_ATTEMPTS: + os.close(temp_fd) + temp_fd = -1 + os.unlink(temp_name, dir_fd=parent_fd) + continue + + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_entry(before, current): + raise GuardOperationError( + Issue("entry-raced", path, "file changed before atomic replacement") + ) + uid, gid = _expected_ids(policy, "lock", identity) + os.fchown(temp_fd, uid, gid) + # Preserve application metadata on the fresh inode. Applying the + # final mode after copying xattrs also clamps any POSIX ACL mask to + # the shields mode instead of re-opening write access. + listxattr = getattr(os, "listxattr", None) + getxattr = getattr(os, "getxattr", None) + setxattr = getattr(os, "setxattr", None) + try: + attributes = ( + listxattr(source_fd) + if listxattr is not None + and getxattr is not None + and setxattr is not None + else () + ) + for attribute in attributes: + setxattr( + temp_fd, + attribute, + getxattr(source_fd, attribute), + ) + except OSError as exc: + if exc.errno not in {errno.ENOTSUP, errno.ENOSYS}: + raise + os.fchmod( + temp_fd, + _expected_file_mode(policy, "lock", stat.S_IMODE(before.st_mode)), + ) + os.utime( + temp_fd, + ns=(before.st_atime_ns, before.st_mtime_ns), + ) + final_source = os.fstat(source_fd) + final_stable = ( + _same_entry(before, final_source) + and before.st_size == final_source.st_size + and before.st_mtime_ns == final_source.st_mtime_ns + and before.st_ctime_ns == final_source.st_ctime_ns + ) + if not final_stable and attempt + 1 < STABLE_COPY_ATTEMPTS: + os.close(temp_fd) + temp_fd = -1 + os.unlink(temp_name, dir_fd=parent_fd) + continue + os.fsync(temp_fd) + os.replace(temp_name, name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + replaced = True + temp_name = "" + _set_inode_flags(temp_fd, source_flags) + os.fsync(temp_fd) + os.fsync(parent_fd) + return before.st_ino + except GuardOperationError: + raise + except OSError as exc: + raise GuardOperationError( + _os_issue("file-replace-failed", path, "atomically replace file", exc) + ) from exc + finally: + if source_fd >= 0: + if not replaced: + try: + _set_inode_flags(source_fd, source_flags) + except OSError: + # Best effort: preserve the original operation failure. + pass + os.close(source_fd) + if temp_fd >= 0: + os.close(temp_fd) + if temp_name: + try: + os.unlink(temp_name, dir_fd=parent_fd) + except FileNotFoundError: + # Replacement or concurrent cleanup already removed it. + pass + raise GuardOperationError( + Issue( + "unstable-file", + path, + f"file did not remain stable across {STABLE_COPY_ATTEMPTS} copy attempts", + ) + ) + + +def _unlock_file( + parent_fd: int, + name: str, + relative_path: str, + context: TraversalContext, + policy: Policy, + identity: Identity, +) -> None: + path = context.display(relative_path) + try: + file_fd = os.open(name, _file_flags(), dir_fd=parent_fd) + except OSError as exc: + raise GuardOperationError( + _os_issue("open-failed", path, "open file", exc) + ) from exc + try: + _clear_mutation_flags(file_fd) + st = os.fstat(file_fd) + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_entry(st, current) or not stat.S_ISREG(st.st_mode): + raise GuardOperationError( + Issue("entry-raced", path, "file changed while it was being opened") + ) + if st.st_dev != context.config_dev: + raise GuardOperationError( + Issue("cross-device-entry", path, "file is on a different filesystem") + ) + if st.st_nlink != 1: + raise GuardOperationError( + Issue( + "hardlinked-entry", + path, + f"regular file has link count {st.st_nlink}, expected 1", + ) + ) + uid, gid = _expected_ids(policy, "unlock", identity) + os.fchown(file_fd, uid, gid) + os.fchmod( + file_fd, + _expected_file_mode(policy, "unlock", stat.S_IMODE(st.st_mode)), + ) + except OSError as exc: + raise GuardOperationError( + _os_issue("metadata-update-failed", path, "update file metadata", exc) + ) from exc + finally: + os.close(file_fd) + + +def _chown_symlink( + parent_fd: int, + name: str, + relative_path: str, + context: TraversalContext, + policy: Policy, + action: Action, + identity: Identity, +) -> None: + path = context.display(relative_path) + before = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + issue = _validate_symlink(context, parent_fd, name, relative_path, before) + if issue is not None: + raise GuardOperationError(issue) + uid, gid = _expected_ids(policy, action, identity) + try: + os.chown(name, uid, gid, dir_fd=parent_fd, follow_symlinks=False) + except OSError as exc: + raise GuardOperationError( + _os_issue("metadata-update-failed", path, "update symlink ownership", exc) + ) from exc + after = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_entry(before, after): + raise GuardOperationError( + Issue("entry-raced", path, "symlink changed while ownership was updated") + ) + + +def _mutate_dir( + context: TraversalContext, + dir_fd: int, + relative_dir: str, + policy: Policy, + action: Action, + identity: Identity, + result: GuardResult, + replaced_inodes: dict[str, int], + depth: int, + is_root: bool = False, +) -> None: + if depth > MAX_TRAVERSAL_DEPTH: + raise GuardOperationError( + Issue( + "tree-too-deep", + context.display(relative_dir), + f"state tree exceeds {MAX_TRAVERSAL_DEPTH} directory levels", + ) + ) + try: + original_dir_flags = _clear_mutation_flags(dir_fd) + if action == "lock": + # Remove every write bit before changing ownership. This revokes + # mutation through directory descriptors opened by the sandbox + # before shields-up, and it happens before visiting descendants. + _freeze_dir_for_lock(dir_fd) + _set_dir_metadata(dir_fd, policy, action, identity) + elif is_root: + # Keep the subtree inaccessible while descendants are restored. + os.fchmod(dir_fd, 0o700) + os.fchown(dir_fd, identity.root_uid, identity.root_gid) + os.fchmod(dir_fd, 0o700) + names = _bounded_directory_names( + dir_fd, context.display(relative_dir), context.budget + ) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "metadata-update-failed", + context.display(relative_dir), + "prepare directory", + exc, + ) + ) from exc + + result.directories += 1 + for name in names: + relative_path = posixpath.join(relative_dir, name) + path = context.display(relative_path) + try: + entry_st = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) + except OSError as exc: + raise GuardOperationError( + _os_issue("stat-failed", path, "stat entry during mutation", exc) + ) from exc + context.budget.observe_entry(path, entry_st) + if entry_st.st_dev != context.config_dev: + raise GuardOperationError( + Issue("cross-device-entry", path, "entry is on a different filesystem") + ) + if stat.S_ISDIR(entry_st.st_mode): + try: + child_fd = _open_child_dir(dir_fd, name, entry_st) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "open-failed", path, "open directory during mutation", exc + ) + ) from exc + try: + if _is_runtime_carveout(relative_path): + # Only the carve-out root has a shields contract. Its + # contents remain runtime-owned and may change while this + # helper runs, so never chmod/chown/copy descendants. + _clear_mutation_flags(child_fd) + _set_dir_metadata(child_fd, policy, "unlock", identity) + result.directories += 1 + else: + _mutate_dir( + context, + child_fd, + relative_path, + policy, + action, + identity, + result, + replaced_inodes, + depth + 1, + ) + finally: + os.close(child_fd) + elif stat.S_ISREG(entry_st.st_mode): + if action == "lock": + replaced_inodes[relative_path] = _copy_stable_file_to_temp( + dir_fd, + name, + relative_path, + context, + policy, + identity, + ) + else: + _unlock_file( + dir_fd, + name, + relative_path, + context, + policy, + identity, + ) + result.files += 1 + elif stat.S_ISLNK(entry_st.st_mode): + issue = _validate_symlink(context, dir_fd, name, relative_path, entry_st) + if action == "lock" and issue is not None: + current = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) + if not _same_entry(entry_st, current): + raise GuardOperationError( + Issue( + "entry-raced", path, "unsafe symlink changed before removal" + ) + ) + try: + os.unlink(name, dir_fd=dir_fd) + os.fsync(dir_fd) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "unsafe-entry-remove-failed", + path, + "remove unsafe symlink", + exc, + ) + ) from exc + result.removed_entries += 1 + else: + _chown_symlink( + dir_fd, + name, + relative_path, + context, + policy, + action, + identity, + ) + result.symlinks += 1 + else: + if action != "lock": + raise GuardOperationError( + Issue( + "special-entry", + path, + f"state tree contains a {_entry_kind(entry_st)}", + ) + ) + current = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) + if not _same_entry(entry_st, current): + raise GuardOperationError( + Issue("entry-raced", path, "special entry changed before removal") + ) + try: + os.unlink(name, dir_fd=dir_fd) + os.fsync(dir_fd) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "unsafe-entry-remove-failed", path, "remove special entry", exc + ) + ) from exc + result.removed_entries += 1 + + if action == "unlock": + try: + _set_dir_metadata(dir_fd, policy, action, identity) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "metadata-update-failed", + context.display(relative_dir), + "restore directory metadata", + exc, + ) + ) from exc + else: + try: + _set_inode_flags(dir_fd, original_dir_flags) + except OSError as exc: + raise GuardOperationError( + _os_issue( + "metadata-update-failed", + context.display(relative_dir), + "restore directory inode flags", + exc, + ) + ) from exc + + +def _verify_metadata( + path: str, + st: os.stat_result, + entry_type: Literal["directory", "file", "symlink"], + policy: Policy, + action: Action, + identity: Identity, +) -> Issue | None: + expected_uid, expected_gid = _expected_ids(policy, action, identity) + if st.st_uid != expected_uid or st.st_gid != expected_gid: + return Issue( + "verification-owner-mismatch", + path, + f"owner is {st.st_uid}:{st.st_gid}, expected {expected_uid}:{expected_gid}", + ) + if entry_type == "symlink": + return None + mode = stat.S_IMODE(st.st_mode) + if entry_type == "directory": + expected_mode = _expected_dir_mode(policy, action) + if mode != expected_mode: + return Issue( + "verification-mode-mismatch", + path, + f"directory mode is {mode:04o}, expected {expected_mode:04o}", + ) + return None + if mode & 0o7000: + return Issue( + "verification-mode-mismatch", + path, + f"file retains special mode bits: {mode:04o}", + ) + if action == "unlock": + if mode & 0o007 or mode & 0o060 != 0o060: + return Issue( + "verification-mode-mismatch", + path, + f"mutable file mode does not satisfy g+rwX,o-rwx: {mode:04o}", + ) + elif policy == "confidentiality": + if mode & 0o077: + return Issue( + "verification-mode-mismatch", + path, + f"confidential file exposes group/world permissions: {mode:04o}", + ) + elif mode & 0o022: + return Issue( + "verification-mode-mismatch", + path, + f"high-risk file is group/world writable: {mode:04o}", + ) + return None + + +def _verify_dir( + context: TraversalContext, + dir_fd: int, + relative_dir: str, + policy: Policy, + action: Action, + identity: Identity, + replaced_inodes: dict[str, int], + issues: list[Issue], + depth: int, +) -> None: + if depth > MAX_TRAVERSAL_DEPTH: + issues.append( + Issue( + "tree-too-deep", + context.display(relative_dir), + f"state tree exceeds {MAX_TRAVERSAL_DEPTH} directory levels", + ) + ) + return + dir_issue = _verify_metadata( + context.display(relative_dir), + os.fstat(dir_fd), + "directory", + policy, + action, + identity, + ) + if dir_issue is not None: + issues.append(dir_issue) + try: + names = _bounded_directory_names( + dir_fd, context.display(relative_dir), context.budget + ) + except OSError as exc: + issues.append( + _os_issue( + "verification-list-failed", context.display(relative_dir), "list", exc + ) + ) + return + for name in names: + relative_path = posixpath.join(relative_dir, name) + path = context.display(relative_path) + try: + st = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) + except OSError as exc: + issues.append(_os_issue("verification-stat-failed", path, "stat", exc)) + continue + try: + context.budget.observe_entry(path, st) + except GuardOperationError as exc: + issues.append(exc.issue) + return + if st.st_dev != context.config_dev: + issues.append( + Issue("cross-device-entry", path, "entry is on a different filesystem") + ) + continue + if stat.S_ISDIR(st.st_mode): + try: + child_fd = _open_child_dir(dir_fd, name, st) + except (OSError, GuardOperationError) as exc: + if isinstance(exc, GuardOperationError): + issues.append(Issue(exc.issue.code, path, exc.issue.detail)) + else: + issues.append( + _os_issue("verification-open-failed", path, "open", exc) + ) + continue + try: + if _is_runtime_carveout(relative_path): + carveout_issue = _verify_metadata( + path, + os.fstat(child_fd), + "directory", + policy, + "unlock", + identity, + ) + if carveout_issue is not None: + issues.append(carveout_issue) + else: + _verify_dir( + context, + child_fd, + relative_path, + policy, + action, + identity, + replaced_inodes, + issues, + depth + 1, + ) + finally: + os.close(child_fd) + elif stat.S_ISREG(st.st_mode): + if st.st_nlink != 1: + issues.append( + Issue( + "hardlinked-entry", + path, + f"regular file has link count {st.st_nlink}, expected 1", + ) + ) + metadata_issue = _verify_metadata( + path, st, "file", policy, action, identity + ) + if metadata_issue is not None: + issues.append(metadata_issue) + old_inode = replaced_inodes.get(relative_path) + if action == "lock" and old_inode is not None and st.st_ino == old_inode: + issues.append( + Issue( + "verification-inode-not-replaced", + path, + "locked file still uses its pre-lock inode", + ) + ) + elif stat.S_ISLNK(st.st_mode): + metadata_issue = _verify_metadata( + path, st, "symlink", policy, action, identity + ) + if metadata_issue is not None: + issues.append(metadata_issue) + symlink_issue = _validate_symlink(context, dir_fd, name, relative_path, st) + if symlink_issue is not None: + issues.append(symlink_issue) + else: + issues.append( + Issue( + "special-entry", + path, + f"state tree contains a {_entry_kind(st)}", + ) + ) + + +def _run_guard_unserialized( + action: Action, + config_dir: str, + identity: Identity, +) -> GuardResult: + """Run one guard action. ``identity`` is explicit for focused tests.""" + + result = GuardResult(action=action) + deadline = time.monotonic() + MAX_GUARD_SECONDS + normalized_config = posixpath.normpath(config_dir) + fail_closed_config_root = action == "lock" and ( + normalized_config in PRODUCTION_FAIL_CLOSED_CONFIG_DIRS + or os.environ.get("NEMOCLAW_TEST_OPENCLAW_FAIL_CLOSED") == "1" + or os.environ.get("NEMOCLAW_TEST_HERMES_FAIL_CLOSED") == "1" + ) + config_fd = -1 + try: + config_fd = _open_absolute_dir_nofollow(normalized_config) + config_st = os.fstat(config_fd) + if not stat.S_ISDIR(config_st.st_mode): + result.issues.append( + Issue( + "invalid-config-path", + normalized_config, + "config path is not a directory", + ) + ) + return result + + if fail_closed_config_root: + # The agent top-config guard has already pinned the config root + # under a root-owned outer parent. Clamp traversal before any + # attacker-sized listing. On every later error the directory stays + # 0500, so no gateway/sandbox identity can consume partially + # hardened code or state through the canonical namespace. + _clear_mutation_flags(config_fd) + os.fchmod(config_fd, 0o500) + os.fchown(config_fd, identity.root_uid, identity.root_gid) + os.fchmod(config_fd, 0o500) + os.fsync(config_fd) + + if action == "lock": + result.removed_entries += _remove_unsupported_root_entries_for_lock( + config_fd, normalized_config, config_st.st_dev + ) + + roots, issues = _preflight( + config_fd, + normalized_config, + config_st.st_dev, + deadline, + action, + ) + result.roots = len(roots) + result.issues.extend(issues) + if action == "preflight" or issues: + return result + + # Detect root swaps/creations between preflight and mutation before + # changing any metadata. Each root inode is checked again when opened. + current_roots, selection_issues = _select_roots( + config_fd, normalized_config, config_st.st_dev + ) + result.issues.extend(selection_issues) + expected_root_set = {(root.name, root.dev, root.ino) for root in roots} + current_root_set = {(root.name, root.dev, root.ino) for root in current_roots} + if expected_root_set != current_root_set: + result.issues.append( + Issue( + "root-set-changed", + normalized_config, + "protected state-dir roots changed after preflight", + ) + ) + return result + + context = TraversalContext( + config_fd, + normalized_config, + config_st.st_dev, + tuple(root.name for root in roots), + WorkBudget(deadline), + ) + replaced_inodes: dict[str, int] = {} + for root in roots: + path = context.display(root.name) + try: + root_lstat = os.stat(root.name, dir_fd=config_fd, follow_symlinks=False) + context.budget.observe_entry(path, root_lstat) + if root_lstat.st_dev != root.dev or root_lstat.st_ino != root.ino: + raise GuardOperationError( + Issue( + "entry-raced", + path, + "state-dir root changed after preflight", + ) + ) + root_fd = _open_child_dir(config_fd, root.name, root_lstat) + try: + _mutate_dir( + context, + root_fd, + root.name, + root.policy, + action, + identity, + result, + replaced_inodes, + 1, + is_root=True, + ) + finally: + os.close(root_fd) + except GuardOperationError as exc: + result.issues.append(exc.issue) + return result + except OSError as exc: + result.issues.append( + _os_issue("mutation-failed", path, "mutate state-dir root", exc) + ) + return result + + # A second independent descriptor traversal verifies the recursive + # result and catches entries changed by a concurrent pre-open FD. + verify_roots, selection_issues = _select_roots( + config_fd, normalized_config, config_st.st_dev + ) + result.issues.extend(selection_issues) + verify_root_set = {(root.name, root.dev, root.ino) for root in verify_roots} + if verify_root_set != current_root_set: + result.issues.append( + Issue( + "verification-root-set-changed", + normalized_config, + "protected state-dir roots changed during mutation", + ) + ) + return result + context.budget = WorkBudget(deadline) + for root in verify_roots: + path = context.display(root.name) + try: + root_lstat = os.stat(root.name, dir_fd=config_fd, follow_symlinks=False) + context.budget.observe_entry(path, root_lstat) + root_fd = _open_child_dir(config_fd, root.name, root_lstat) + except (OSError, GuardOperationError) as exc: + if isinstance(exc, GuardOperationError): + result.issues.append(Issue(exc.issue.code, path, exc.issue.detail)) + else: + result.issues.append( + _os_issue("verification-open-failed", path, "open root", exc) + ) + continue + try: + _verify_dir( + context, + root_fd, + root.name, + root.policy, + action, + identity, + replaced_inodes, + result.issues, + 1, + ) + finally: + os.close(root_fd) + if fail_closed_config_root and not result.issues: + os.fchmod(config_fd, 0o755) + os.fsync(config_fd) + return result + except GuardOperationError as exc: + result.issues.append(exc.issue) + return result + except OSError as exc: + result.issues.append( + _os_issue( + "config-open-failed", normalized_config, "open config directory", exc + ) + ) + return result + finally: + if config_fd >= 0: + os.close(config_fd) + + +def _transition_lock_path(config_dir: str) -> str | None: + if config_dir == "/sandbox/.openclaw": + return OPENCLAW_MUTATION_MUTEX_PATH + if os.environ.get("NEMOCLAW_TEST_OPENCLAW_TRANSACTION_LOCK") == "1": + return posixpath.join( + posixpath.dirname(config_dir), ".openclaw-config-mutation.lock" + ) + return None + + +def _acquire_transition_lock(path: str, identity: Identity) -> int: + parent_fd = _open_absolute_dir_nofollow(posixpath.dirname(path)) + name = posixpath.basename(path) + fd = -1 + try: + fd = os.open( + name, + os.O_RDWR + | os.O_CREAT + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0), + 0o600, + dir_fd=parent_fd, + ) + opened = os.fstat(fd) + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if ( + not stat.S_ISREG(opened.st_mode) + or opened.st_nlink != 1 + or not _same_entry(opened, current) + or opened.st_uid != identity.root_uid + or opened.st_gid != identity.root_gid + or stat.S_IMODE(opened.st_mode) != 0o600 + ): + raise GuardOperationError( + Issue( + "unsafe-transition-lock", + path, + "transition mutex must be a private root-owned regular file", + ) + ) + fcntl.flock(fd, fcntl.LOCK_EX) + after = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_entry(opened, after): + raise GuardOperationError( + Issue( + "transition-lock-raced", + path, + "transition mutex changed while waiting", + ) + ) + return fd + except Exception: + if fd >= 0: + os.close(fd) + raise + finally: + os.close(parent_fd) + + +def run_guard( + action: Action, + config_dir: str, + identity: Identity, +) -> GuardResult: + """Serialize production OpenClaw recursive transitions with its top guard.""" + + normalized_config = posixpath.normpath(config_dir) + lock_path = _transition_lock_path(normalized_config) + if lock_path is None: + return _run_guard_unserialized(action, normalized_config, identity) + + lock_fd = -1 + try: + lock_fd = _acquire_transition_lock(lock_path, identity) + if normalized_config != "/sandbox/.openclaw": + ready_path = os.environ.get("NEMOCLAW_TEST_TRANSACTION_LOCK_READY") + if ready_path: + with open(ready_path, "w", encoding="utf-8") as stream: + stream.write("ready\n") + hold_ms = int(os.environ.get("NEMOCLAW_TEST_TRANSACTION_LOCK_HOLD_MS", "0")) + if hold_ms > 0: + time.sleep(hold_ms / 1000) + return _run_guard_unserialized(action, normalized_config, identity) + except GuardOperationError as exc: + result = GuardResult(action=action) + result.issues.append(exc.issue) + return result + except (OSError, ValueError) as exc: + result = GuardResult(action=action) + result.issues.append( + _os_issue( + "transition-lock-failed", lock_path, "acquire transition mutex", exc + ) + if isinstance(exc, OSError) + else Issue("transition-lock-failed", lock_path, str(exc)) + ) + return result + finally: + if lock_fd >= 0: + try: + fcntl.flock(lock_fd, fcntl.LOCK_UN) + finally: + os.close(lock_fd) + + +def _production_identity() -> Identity: + sandbox_user = pwd.getpwnam("sandbox") + sandbox_group = grp.getgrnam("sandbox") + return Identity( + root_uid=0, + root_gid=0, + sandbox_uid=sandbox_user.pw_uid, + sandbox_gid=sandbox_group.gr_gid, + ) + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Safely preflight, lock, or unlock recursive agent state directories" + ) + parser.add_argument("action", choices=("preflight", "lock", "unlock")) + parser.add_argument("--config-dir", required=True) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = _parse_args(sys.argv[1:] if argv is None else argv) + if os.geteuid() != 0: + result = GuardResult(action=args.action) + result.issues.append( + Issue("root-required", args.config_dir, "state-dir guard must run as root") + ) + else: + try: + identity = _production_identity() + except KeyError as exc: + result = GuardResult(action=args.action) + result.issues.append( + Issue( + "identity-unavailable", + args.config_dir, + f"required sandbox account is unavailable: {exc}", + ) + ) + else: + result = run_guard(args.action, args.config_dir, identity) + + for issue in result.issues: + print(json.dumps(issue.as_json(), sort_keys=True, separators=(",", ":"))) + print(json.dumps(result.summary_json(), sort_keys=True, separators=(",", ":"))) + return 0 if result.ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/commands/sandbox/config/set.ts b/src/commands/sandbox/config/set.ts index ca4a6cdabb4..37e0b5ecc9f 100644 --- a/src/commands/sandbox/config/set.ts +++ b/src/commands/sandbox/config/set.ts @@ -32,7 +32,7 @@ export default class SandboxConfigSetCommand extends NemoClawCommand { required: true, }), restart: Flags.boolean({ - description: "Signal the sandbox agent process to reload after writing", + description: "Restart a supported OpenClaw or Hermes gateway after writing", }), "config-accept-new-path": Flags.boolean({ description: "Allow creating a config key that does not already exist", diff --git a/src/commands/sandbox/gateway/restart.ts b/src/commands/sandbox/gateway/restart.ts new file mode 100644 index 00000000000..44e3c895134 --- /dev/null +++ b/src/commands/sandbox/gateway/restart.ts @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Args } from "@oclif/core"; + +import { restartSandboxGateway } from "../../../lib/actions/sandbox/process-recovery"; +import { quietFlag } from "../../../lib/cli/common-flags"; +import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; + +export default class GatewayRestartCliCommand extends NemoClawCommand { + static id = "sandbox:gateway:restart"; + static strict = true; + static summary = "Restart the sandbox agent gateway"; + static description = + "Restart the sandbox agent gateway through its privileged lifecycle controller, wait for health, and check or recover host forwards."; + static usage = [" [--quiet|-q]"]; + static examples = [ + "<%= config.bin %> sandbox gateway restart alpha", + "<%= config.bin %> sandbox gateway restart alpha --quiet", + ]; + static args = { + sandboxName: Args.string({ + name: "sandbox", + description: "Sandbox name", + required: true, + }), + }; + static flags = { + quiet: quietFlag("Suppress progress output"), + }; + + public async run(): Promise { + const { args, flags } = await this.parse(GatewayRestartCliCommand); + const result = restartSandboxGateway(args.sandboxName, { quiet: flags.quiet === true }); + if (!result.ok) { + this.setExitCode(1); + } + } +} diff --git a/src/commands/sandbox/oclif-command-adapters.test.ts b/src/commands/sandbox/oclif-command-adapters.test.ts index 6e357aca90e..71887f011ed 100644 --- a/src/commands/sandbox/oclif-command-adapters.test.ts +++ b/src/commands/sandbox/oclif-command-adapters.test.ts @@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => { listSandboxChannels: vi.fn(), listSandboxPolicies: vi.fn(), rebuildSandbox: vi.fn().mockResolvedValue(undefined), + restartSandboxGateway: vi.fn().mockReturnValue({ ok: true }), runSandboxDoctor: vi.fn().mockResolvedValue(undefined), shieldsDown: vi.fn(), shieldsStatus: vi.fn(), @@ -48,6 +49,10 @@ vi.mock("../../lib/actions/sandbox/rebuild", () => ({ rebuildSandbox: mocks.rebuildSandbox, })); +vi.mock("../../lib/actions/sandbox/process-recovery", () => ({ + restartSandboxGateway: mocks.restartSandboxGateway, +})); + vi.mock("../../lib/actions/sandbox/status", () => ({ showSandboxStatus: mocks.showSandboxStatus, })); @@ -82,21 +87,23 @@ vi.mock("../../lib/shields", () => ({ shieldsUp: mocks.shieldsUp, })); -import ConnectCliCommand from "./connect"; +import SandboxChannelsListCommand from "./channels/list"; import SandboxConfigGetCommand from "./config/get"; +import ConnectCliCommand from "./connect"; import DestroyCliCommand from "./destroy"; import SandboxDoctorCliCommand from "./doctor"; -import SandboxChannelsListCommand from "./channels/list"; +import GatewayRestartCliCommand from "./gateway/restart"; import HostsAddCommand from "./hosts/add"; import HostsListCommand from "./hosts/list"; import HostsRemoveCommand from "./hosts/remove"; import SandboxLogsCommand from "./logs"; import SandboxPolicyListCommand from "./policy/list"; import RebuildCliCommand from "./rebuild"; -import SandboxStatusCommand from "./status"; +import RecoverCliCommand from "./recover"; import ShieldsDownCommand from "./shields/down"; import ShieldsStatusCommand from "./shields/status"; import ShieldsUpCommand from "./shields/up"; +import SandboxStatusCommand from "./status"; const rootDir = process.cwd(); @@ -112,6 +119,7 @@ describe("sandbox oclif command adapters", () => { await ConnectCliCommand.run(["alpha", "--probe-only"], rootDir); await DestroyCliCommand.run(["alpha", "--yes"], rootDir); await RebuildCliCommand.run(["alpha", "--force", "--verbose"], rootDir); + await GatewayRestartCliCommand.run(["alpha", "--quiet"], rootDir); expect(mocks.connectSandbox).toHaveBeenCalledWith("alpha", { probeOnly: true }); expect(mocks.destroySandbox).toHaveBeenCalledWith("alpha", { force: false, yes: true }); @@ -120,6 +128,7 @@ describe("sandbox oclif command adapters", () => { verbose: true, yes: false, }); + expect(mocks.restartSandboxGateway).toHaveBeenCalledWith("alpha", { quiet: true }); } finally { if (originalCleanupGatewayEnv === undefined) { delete process.env.NEMOCLAW_CLEANUP_GATEWAY; @@ -187,12 +196,19 @@ describe("sandbox oclif command adapters", () => { expect(usage(SandboxLogsCommand)).toContain("[--tail |-n ]"); expect(DestroyCliCommand.id).toBe("sandbox:destroy"); expect(usage(DestroyCliCommand)).toContain("[--yes|-y|--force]"); + expect(RecoverCliCommand.id).toBe("sandbox:recover"); + expect(RecoverCliCommand.summary).toMatch(/Repair a stopped sandbox gateway/); + expect(RecoverCliCommand.description).toContain("A healthy gateway is not restarted"); + expect(RecoverCliCommand.description).toContain("gateway restart"); + expect(RecoverCliCommand.summary).not.toMatch(/^Restart\b/); expect(RebuildCliCommand.id).toBe("sandbox:rebuild"); expect(usage(RebuildCliCommand)).toContain("[--yes|-y|--force]"); expect(SandboxPolicyListCommand.id).toBe("sandbox:policy:list"); expect(SandboxChannelsListCommand.id).toBe("sandbox:channels:list"); expect(SandboxConfigGetCommand.id).toBe("sandbox:config:get"); expect(usage(SandboxConfigGetCommand)).toContain("[--format json|yaml]"); + expect(GatewayRestartCliCommand.id).toBe("sandbox:gateway:restart"); + expect(usage(GatewayRestartCliCommand)).toContain(" [--quiet|-q]"); expect(HostsAddCommand.id).toBe("sandbox:hosts:add"); expect(usage(HostsAddCommand)).toContain(" [--dry-run]"); expect(HostsListCommand.id).toBe("sandbox:hosts:list"); diff --git a/src/commands/sandbox/recover.ts b/src/commands/sandbox/recover.ts index 9cec27fa88e..2dcfa11c6d3 100644 --- a/src/commands/sandbox/recover.ts +++ b/src/commands/sandbox/recover.ts @@ -9,9 +9,9 @@ import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; export default class RecoverCliCommand extends NemoClawCommand { static id = "sandbox:recover"; static strict = true; - static summary = "Restart the sandbox gateway and dashboard port-forward"; + static summary = "Repair a stopped sandbox gateway and host forwards"; static description = - "Re-run the sandbox-side gateway recovery and re-establish the host-side dashboard port-forward without opening an SSH session. Equivalent to `connect --probe-only`; safe to re-run."; + "Probe sandbox gateway health and repair stopped gateways or host forwards without opening an SSH session. A healthy gateway is not restarted; use `gateway restart` when you need a forced runtime reload."; static usage = [""]; static examples = ["<%= config.bin %> sandbox recover alpha"]; static args = { diff --git a/src/lib/actions/inference-set-endpoint-security.test.ts b/src/lib/actions/inference-set-endpoint-security.test.ts new file mode 100644 index 00000000000..5efa78f6739 --- /dev/null +++ b/src/lib/actions/inference-set-endpoint-security.test.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { rewriteConfigUrlsWithDnsPinning } from "../sandbox/config"; +import { normalizeCustomEndpointUrl } from "./inference-set"; + +describe("custom inference endpoint DNS pinning", () => { + it.each([ + 1024, 65535, + ])("allows the exact OpenShell bridge exemption at port %i without DNS rewriting", async (port) => { + const rewriteUrl = vi.fn(async () => { + throw new Error("bridge exemption unexpectedly reached DNS validation"); + }); + + await expect( + normalizeCustomEndpointUrl(`http://host.openshell.internal:${port}/v1/`, rewriteUrl), + ).resolves.toBe(`http://host.openshell.internal:${port}/v1`); + expect(rewriteUrl).not.toHaveBeenCalled(); + }); + + it.each([ + ["no explicit port", "http://host.openshell.internal/v1"], + ["privileged port", "http://host.openshell.internal:1023/v1"], + ["HTTPS bridge", "https://host.openshell.internal:1234/v1"], + ["localhost", "http://localhost:1234/v1"], + ["loopback", "http://127.0.0.1:1234/v1"], + ["RFC1918", "http://10.0.0.1:1234/v1"], + ["non-allowlisted internal DNS", "http://other.internal:1234/v1"], + ])("rejects the adjacent %s bypass shape", async (_kind, endpointUrl) => { + const lookup = vi.fn(async () => [{ address: "10.0.0.8", family: 4 }]); + + await expect( + normalizeCustomEndpointUrl(endpointUrl, (value) => + rewriteConfigUrlsWithDnsPinning(value, lookup), + ), + ).rejects.toThrow(/endpoint-url is not allowed:.*private\/internal address/i); + }); + + it("pins validated public HTTP endpoints before they become durable metadata", async () => { + const lookup = vi.fn(async () => [{ address: "93.184.216.34", family: 4 }]); + + await expect( + normalizeCustomEndpointUrl("http://public-endpoint.example/v1/", (value) => + rewriteConfigUrlsWithDnsPinning(value, lookup), + ), + ).resolves.toBe("http://93.184.216.34/v1"); + expect(lookup).toHaveBeenCalledWith("public-endpoint.example", { all: true }); + }); + + it("preserves a validated HTTPS hostname for certificate verification", async () => { + const lookup = vi.fn(async () => [{ address: "93.184.216.34", family: 4 }]); + + await expect( + normalizeCustomEndpointUrl("https://public-endpoint.example/v1/", (value) => + rewriteConfigUrlsWithDnsPinning(value, lookup), + ), + ).resolves.toBe("https://public-endpoint.example/v1"); + }); +}); diff --git a/src/lib/actions/inference-set.test.ts b/src/lib/actions/inference-set.test.ts index 3b03c1922a3..06c8bd07995 100644 --- a/src/lib/actions/inference-set.test.ts +++ b/src/lib/actions/inference-set.test.ts @@ -4,11 +4,12 @@ import { describe, expect, it, vi } from "vitest"; import { HERMES_PROXY_API_KEY_PLACEHOLDER } from "../hermes-proxy-api-key"; import type { AgentConfigTarget } from "../sandbox/config"; -import type { ConfigObject } from "../security/credential-filter"; +import type { ConfigObject, ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry"; vi.mock("../adapters/openshell/runtime", () => ({ + getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: vi.fn(), })); @@ -29,6 +30,7 @@ vi.mock("../sandbox/config", () => ({ readSandboxConfig: vi.fn(), recomputeSandboxConfigHash: vi.fn(), resolveAgentConfig: vi.fn(), + rewriteConfigUrlsWithDnsPinning: vi.fn(async (value: ConfigValue) => value), writeSandboxConfig: vi.fn(), })); @@ -117,6 +119,9 @@ function createDeps(options: { localValidation?: ValidationResult; localReachable?: boolean; contextWindow?: number | null; + shieldsMutable?: boolean; + prepareRunOpenshell?: () => void; + rewriteConfigUrlsWithDnsPinning?: (value: ConfigValue) => Promise; }): InferenceSetDeps & { calls: { runOpenshell: ReturnType; @@ -130,6 +135,8 @@ function createDeps(options: { validateLocalProvider: ReturnType; ensureLocalProviderReachable: ReturnType; resolveContextWindowForModel: ReturnType; + prepareRunOpenshell: ReturnType; + rewriteConfigUrlsWithDnsPinning: ReturnType; }; getSession: () => Session | null; } { @@ -159,6 +166,10 @@ function createDeps(options: { resolveContextWindowForModel: vi.fn((_provider: string, _model: string) => options.contextWindow === undefined ? null : options.contextWindow, ), + prepareRunOpenshell: vi.fn(options.prepareRunOpenshell ?? (() => undefined)), + rewriteConfigUrlsWithDnsPinning: vi.fn( + options.rewriteConfigUrlsWithDnsPinning ?? (async (value: ConfigValue) => value), + ), }; return { getDefaultSandbox: () => defaultSandbox, @@ -172,6 +183,7 @@ function createDeps(options: { readSandboxConfig: calls.readSandboxConfig, writeSandboxConfig: calls.writeSandboxConfig, recomputeSandboxConfigHash: calls.recomputeSandboxConfigHash, + prepareRunOpenshell: calls.prepareRunOpenshell, runOpenshell: calls.runOpenshell, appendAuditEntry: calls.appendAuditEntry, log: calls.log, @@ -180,6 +192,8 @@ function createDeps(options: { validateLocalProvider: calls.validateLocalProvider, ensureLocalProviderReachable: calls.ensureLocalProviderReachable, resolveContextWindowForModel: calls.resolveContextWindowForModel, + isSandboxConfigMutable: () => options.shieldsMutable ?? true, + rewriteConfigUrlsWithDnsPinning: calls.rewriteConfigUrlsWithDnsPinning, calls, getSession: () => session, }; @@ -418,6 +432,34 @@ describe("patchHermesInferenceConfig", () => { }); describe("runInferenceSet", () => { + it("resolves the OpenShell runner before entering the async mutation lock", async () => { + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } } }, + prepareRunOpenshell: () => { + throw new Error("openshell CLI not found"); + }, + }); + + await expect( + runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b" }, + deps, + ), + ).rejects.toThrow("openshell CLI not found"); + expect(deps.calls.prepareRunOpenshell).toHaveBeenCalledOnce(); + expect(deps.calls.runOpenshell).not.toHaveBeenCalled(); + + // A failed preflight cannot leave a transition lock behind: retrying with + // a valid runner proceeds immediately in the same process. + deps.calls.prepareRunOpenshell.mockImplementation(() => undefined); + await expect( + runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b" }, + deps, + ), + ).resolves.toMatchObject({ sandboxName: "alpha" }); + }); + it("updates OpenShell, OpenClaw config, registry, and the matching onboard session", async () => { const config: ConfigObject = { agents: { defaults: { model: { primary: "inference/moonshotai/kimi-k2.6" } } }, @@ -597,6 +639,58 @@ describe("runInferenceSet", () => { }); }); + it("refuses a Hermes switch while shields are up before changing route or registry state", async () => { + const deps = createDeps({ + config: { model: { default: "moonshotai/kimi-k2.6" } }, + entry: { + name: "hermes", + agent: "hermes", + provider: "hermes-provider", + model: "moonshotai/kimi-k2.6", + }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + shieldsMutable: false, + }); + + await expect( + runInferenceSet( + { + provider: "hermes-provider", + model: "openai/gpt-5.4-mini", + sandboxName: "hermes", + }, + deps, + ), + ).rejects.toThrow("shields are up"); + expect(deps.calls.runOpenshell).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + }); + + it("refuses an OpenClaw switch while shields are up before changing route or registry state", async () => { + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/moonshotai/kimi-k2.6" } } }, + }, + shieldsMutable: false, + }); + + await expect( + runInferenceSet( + { + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + sandboxName: "alpha", + }, + deps, + ), + ).rejects.toThrow(/OpenClaw inference changes.*shields are up/); + expect(deps.calls.runOpenshell).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + }); + it("syncs OpenClaw compatible Anthropic switches to Anthropic Messages when changing provider families", async () => { const config: ConfigObject = { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } }, @@ -848,8 +942,56 @@ describe("runInferenceSet", () => { preferredInferenceApi: "anthropic-messages", nimContainer: null, }); + expect(deps.calls.rewriteConfigUrlsWithDnsPinning).not.toHaveBeenCalled(); }); + for (const provider of ["compatible-endpoint", "compatible-anthropic-endpoint"]) { + it.each([ + ["loopback", "http://127.0.0.1:8000/v1", "93.184.216.34"], + ["localhost", "http://localhost:8000/v1", "93.184.216.34"], + ["link-local", "http://169.254.169.254/latest", "93.184.216.34"], + ["RFC1918", "http://10.0.0.1:8000/v1", "93.184.216.34"], + ["non-allowlisted internal", "http://evil.host.openshell.internal:18767/v1", "93.184.216.34"], + ["HTTPS bridge", "https://host.openshell.internal:18767/v1", "93.184.216.34"], + ["privileged-port bridge", "http://host.openshell.internal:80/v1", "93.184.216.34"], + ["DNS-private", "https://private-resolution.example/v1", "10.0.0.8"], + ])(`rejects %s endpoint metadata for ${provider}`, async (_kind, endpointUrl, resolvedAddress) => { + const actualConfig = + await vi.importActual("../sandbox/config"); + const lookup = vi.fn(async () => [{ address: resolvedAddress, family: 4 }]); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/model-a", + }, + rewriteConfigUrlsWithDnsPinning: (value) => + actualConfig.rewriteConfigUrlsWithDnsPinning(value, lookup), + }); + + await expect( + runInferenceSet( + { + provider, + model: "mock-model", + noVerify: true, + endpointUrl, + credentialEnv: + provider === "compatible-endpoint" + ? "COMPATIBLE_API_KEY" + : "COMPATIBLE_ANTHROPIC_API_KEY", + }, + deps, + ), + ).rejects.toThrow(/endpoint-url is not allowed:.*private\/internal address/i); + + expect(deps.calls.runOpenshell).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + } + it("preserves same-provider Bedrock Runtime adapter routing for OpenClaw switches", async () => { const config: ConfigObject = { agents: { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index b258fd99222..3718999daa5 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -3,7 +3,7 @@ import type { SpawnSyncReturns } from "node:child_process"; -import { runOpenshell } from "../adapters/openshell/runtime"; +import { getOpenshellBinary, runOpenshell } from "../adapters/openshell/runtime"; import { CLI_NAME } from "../cli/branding"; import { HERMES_PROXY_API_KEY_PLACEHOLDER } from "../hermes-proxy-api-key"; import { @@ -12,19 +12,21 @@ import { type SandboxInferenceConfig, } from "../inference/config"; import { resolveContextWindowForModel } from "../inference/context-window"; -import { inferenceSelectionRegistryFields } from "../inference/selection"; import { type ValidationResult, validateLocalProvider } from "../inference/local"; +import { inferenceSelectionRegistryFields } from "../inference/selection"; import { ensureLocalProviderReachable } from "../onboard/local-inference-topology"; import { type AgentConfigTarget, readSandboxConfig, recomputeSandboxConfigHash, resolveAgentConfig, + rewriteConfigUrlsWithDnsPinning, writeSandboxConfig, } from "../sandbox/config"; import type { ConfigObject, ConfigValue } from "../security/credential-filter"; import { isConfigObject, isConfigValue } from "../security/credential-filter"; import { appendAuditEntry } from "../shields/audit"; +import { withTimerBoundShieldsMutationLockAsync } from "../shields/timer-bound-lock"; import * as onboardSession from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry"; import * as registry from "../state/registry"; @@ -72,6 +74,7 @@ export interface InferenceSetDeps { config: ConfigObject, ) => void; recomputeSandboxConfigHash: (sandboxName: string, target: AgentConfigTarget) => void; + prepareRunOpenshell: () => void; runOpenshell: (args: string[], opts?: { ignoreError?: boolean }) => OpenshellRunResult; appendAuditEntry: typeof appendAuditEntry; log: (message: string) => void; @@ -79,6 +82,8 @@ export interface InferenceSetDeps { validateLocalProvider: (provider: string) => ValidationResult; ensureLocalProviderReachable: (provider: string) => boolean; resolveContextWindowForModel: (provider: string, model: string) => number | null; + isSandboxConfigMutable: (sandboxName: string) => boolean; + rewriteConfigUrlsWithDnsPinning: (value: ConfigValue) => Promise; } export class InferenceSetError extends Error { @@ -118,6 +123,9 @@ function defaultDeps(): InferenceSetDeps { readSandboxConfig, writeSandboxConfig, recomputeSandboxConfigHash, + prepareRunOpenshell: () => { + getOpenshellBinary(); + }, runOpenshell: (args, opts) => runOpenshell(args, opts), appendAuditEntry, log: console.log, @@ -126,6 +134,11 @@ function defaultDeps(): InferenceSetDeps { validateLocalProvider, ensureLocalProviderReachable, resolveContextWindowForModel, + rewriteConfigUrlsWithDnsPinning, + isSandboxConfigMutable: (sandboxName) => { + const { isShieldsDown }: typeof import("../shields") = require("../shields"); + return isShieldsDown(sandboxName, true); + }, }; } @@ -392,26 +405,70 @@ function hasExplicitCustomMetadata(options: InferenceSetOptions): boolean { return Boolean(options.endpointUrl || options.credentialEnv || options.inferenceApi); } -function normalizeCustomEndpointUrl(value: string | null | undefined): string { +// TRUST BOUNDARY: host.openshell.internal is the single sandbox-to-host bridge +// hostname provisioned by OpenShell. It resolves to the Docker host gateway +// only inside the sandbox network namespace. This exemption is intentionally +// limited below to HTTP, an explicit unprivileged port, and the exact hostname; +// do not extend it to HTTPS, wildcard subdomains, localhost, RFC1918 literals, +// or other internal DNS names. +const ALLOWED_PRIVATE_CUSTOM_ENDPOINT_HOSTS = new Set(["host.openshell.internal"]); + +function normalizeEndpointUrlShape(value: string): { url: URL; normalized: string } { + const url = new URL(value); + if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) { + throw new Error("unsupported URL shape"); + } + url.search = ""; + url.hash = ""; + const pathname = url.pathname.replace(/\/+$/, ""); + url.pathname = pathname || "/"; + return { + url, + normalized: url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`, + }; +} + +export async function normalizeCustomEndpointUrl( + value: string | null | undefined, + rewriteUrlWithDnsPinning: InferenceSetDeps["rewriteConfigUrlsWithDnsPinning"], +): Promise { const raw = typeof value === "string" ? value.trim() : ""; if (!raw) throw new InferenceSetError("endpoint-url is required for custom-compatible metadata.", 2); + let shaped: { url: URL; normalized: string }; try { - const url = new URL(raw); - if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) { - throw new Error("unsupported URL shape"); - } - url.search = ""; - url.hash = ""; - const pathname = url.pathname.replace(/\/+$/, ""); - url.pathname = pathname || "/"; - return url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`; + shaped = normalizeEndpointUrlShape(raw); } catch { throw new InferenceSetError( "endpoint-url must be a valid http(s) URL without embedded credentials.", 2, ); } + + const hostname = shaped.url.hostname.replace(/\.$/, "").toLowerCase(); + const port = Number(shaped.url.port); + if ( + ALLOWED_PRIVATE_CUSTOM_ENDPOINT_HOSTS.has(hostname) && + shaped.url.protocol === "http:" && + Number.isInteger(port) && + port >= 1024 + ) { + // This is the single sandbox-to-host bridge name that NemoClaw itself + // provisions for local inference. Its supported routes are explicit + // unprivileged HTTP listeners; do not generalize this exemption to HTTPS, + // default/privileged ports, localhost, RFC1918 addresses, or arbitrary + // internal DNS names. + return shaped.normalized; + } + + try { + const validated = await rewriteUrlWithDnsPinning(shaped.normalized); + if (typeof validated !== "string") throw new Error("URL validator returned a non-string value"); + return normalizeEndpointUrlShape(validated).normalized; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new InferenceSetError(`endpoint-url is not allowed: ${message}`, 2); + } } function normalizeExplicitCredentialEnv( @@ -451,10 +508,11 @@ function normalizeExplicitInferenceApi( return normalized; } -function explicitCustomProviderMetadata( +async function explicitCustomProviderMetadata( provider: string, options: InferenceSetOptions, -): RegistryInferenceMetadata | null { + rewriteUrlWithDnsPinning: InferenceSetDeps["rewriteConfigUrlsWithDnsPinning"], +): Promise { if (!hasExplicitCustomMetadata(options)) return null; if (!isCustomCompatibleProvider(provider)) { throw new InferenceSetError( @@ -469,7 +527,7 @@ function explicitCustomProviderMetadata( // for this switch, after URL and credential-env validation, instead of // borrowing from an unrelated onboard session or global OpenShell provider. return { - endpointUrl: normalizeCustomEndpointUrl(options.endpointUrl), + endpointUrl: await normalizeCustomEndpointUrl(options.endpointUrl, rewriteUrlWithDnsPinning), credentialEnv: normalizeExplicitCredentialEnv(provider, options.credentialEnv), preferredInferenceApi: normalizeExplicitInferenceApi(provider, options.inferenceApi), nimContainer: null, @@ -534,7 +592,7 @@ function registryMetadataForProviderSwitch(options: { }; } -export async function runInferenceSet( +async function runInferenceSetWithoutHostLock( options: InferenceSetOptions, deps: InferenceSetDeps = defaultDeps(), ): Promise { @@ -563,8 +621,18 @@ export async function runInferenceSet( 2, ); } + if (!deps.isSandboxConfigMutable(sandboxName)) { + throw new InferenceSetError( + `${agentName === "hermes" ? "Hermes" : "OpenClaw"} inference changes are unavailable while shields are up for '${sandboxName}'. Run '${CLI_NAME} ${sandboxName} shields down' first.`, + 2, + ); + } const session = deps.loadSession(); - const explicitMetadata = explicitCustomProviderMetadata(provider, options); + const explicitMetadata = await explicitCustomProviderMetadata( + provider, + options, + deps.rewriteConfigUrlsWithDnsPinning, + ); const explicitPreferredInferenceApi = explicitMetadata?.preferredInferenceApi ?? null; const registryMetadata = registryMetadataForProviderSwitch({ entry, @@ -756,3 +824,19 @@ export async function runInferenceSet( inSandboxConfigSynced, }; } + +export async function runInferenceSet( + options: InferenceSetOptions, + deps: InferenceSetDeps = defaultDeps(), +): Promise { + // Resolve once before acquiring so a default-sandbox change cannot make the + // protected callback mutate a different sandbox from the one whose lock we + // hold. Prime the default OpenShell runner before acquiring too: its legacy + // missing-binary path exits the process, which cannot be deferred safely by + // an async lock. The inner resolution still validates the live registry entry. + const selected = resolveTargetSandbox(options.sandboxName, deps); + deps.prepareRunOpenshell(); + return withTimerBoundShieldsMutationLockAsync(selected.sandboxName, "inference set", () => + runInferenceSetWithoutHostLock({ ...options, sandboxName: selected.sandboxName }, deps), + ); +} diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index 15151109bf1..2afd13058ec 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -287,4 +287,34 @@ describe("connectSandbox flow", () => { ); expect(exitSpy).toHaveBeenCalledWith(1); }); + it("probe-only mode exits when primary dashboard/API forward recovery fails", async () => { + const harness = createConnectHarness({ + processCheck: { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + }, + }); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( + "process.exit(1)", + ); + + expect(harness.runAutoPairSpy).not.toHaveBeenCalled(); + expect(harness.spawnSyncSpy).not.toHaveBeenCalledWith( + "openshell", + ["sandbox", "connect", "alpha"], + expect.any(Object), + ); + const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(errorOutput).toContain( + "Probe failed: OpenClaw gateway is running in 'alpha', but the dashboard/API host forward could not be restored.", + ); + expect(errorOutput).toContain("openshell forward start --background 18789 alpha"); + const logOutput = harness.logSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(logOutput).not.toContain("Probe complete"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); }); diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 659a282927e..3e7cf7b4aab 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -55,7 +55,11 @@ import { ensureLiveSandboxOrExit, printGatewayLifecycleHint } from "./gateway-st import { getSandboxTargetGatewayName } from "./gateway-target"; import { printGatewayWedgeDiagnostics } from "./gateway-wedge-diagnostics"; import type { SecretBoundaryRefusalReason } from "./hermes-secret-boundary-recovery"; -import { checkAndRecoverSandboxProcesses, executeSandboxExecCommand } from "./process-recovery"; +import { + checkAndRecoverSandboxProcesses, + executeSandboxExecCommand, + resolveSandboxDashboardPort, +} from "./process-recovery"; import { runTerminalAgentConnectProbe } from "./terminal-connect-probe"; import { applyOpenShellVmDnsMonkeypatch, shouldApplyVmDnsMonkeypatch } from "./vm-dns-monkeypatch"; @@ -229,6 +233,22 @@ function exitOnSecretBoundaryRefusal( process.exit(1); } +function exitOnForwardRecoveryFailure( + sandboxName: string, + agentName: string, + port: number, + detail?: string, +): never { + console.error(""); + console.error( + ` Probe failed: ${agentName} gateway is running in '${sandboxName}', but ${detail ?? "the dashboard/API host forward could not be restored"}.`, + ); + console.error( + ` Run \`openshell forward start --background ${port} ${sandboxName}\` manually and re-run \`nemoclaw ${sandboxName} recover\`.`, + ); + process.exit(1); +} + function runSandboxConnectProbe(sandboxName: string): void { const agent = agentRuntime.getSessionAgent(sandboxName); const agentName = agentRuntime.getAgentDisplayName(agent); @@ -253,6 +273,18 @@ function runSandboxConnectProbe(sandboxName: string): void { if ("secretBoundaryRefused" in processCheck && processCheck.secretBoundaryRefused) { exitOnSecretBoundaryRefusal(sandboxName, agentName, processCheck, "Probe"); } + if ("forwardRecoveryFailed" in processCheck && processCheck.forwardRecoveryFailed) { + const detail = + "forwardRecoveryFailureDetail" in processCheck + ? String(processCheck.forwardRecoveryFailureDetail) + : undefined; + exitOnForwardRecoveryFailure( + sandboxName, + agentName, + resolveSandboxDashboardPort(sandboxName), + detail, + ); + } if (processCheck.wasRunning) { ensureSandboxInferenceRoute(sandboxName, { quiet: true }); // Defense-in-depth scope-upgrade approval on the probe-only / `recover` diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 49eff34d19c..757fad8d5b2 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -13,6 +13,8 @@ const destroyModulePath = "./destroy.js"; type DestroyHarness = { cleanupGatewaySpy: MockInstance; destroySandbox: DestroySandbox; + events: string[]; + killTimerSpy: MockInstance; killStaleProxySpy: MockInstance; logSpy: MockInstance; removeSandboxSpy: MockInstance; @@ -20,11 +22,14 @@ type DestroyHarness = { selectGatewaySpy: MockInstance; stopNimByNameSpy: MockInstance; unloadOllamaModelsSpy: MockInstance; + shieldsUpSpy: MockInstance; }; type DestroyHarnessOptions = { + activeTimer?: boolean; deleteStatus?: number; deleteOutput?: string; + shieldsUpError?: Error; }; const sandboxEntry = { @@ -39,6 +44,7 @@ const sandboxEntry = { function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarness { delete require.cache[requireDist.resolve(destroyModulePath)]; + const events: string[] = []; const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); @@ -54,6 +60,7 @@ function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarne const onboardSession = requireDist("../../state/onboard-session.js"); const registry = requireDist("../../state/registry.js"); const sandboxSession = requireDist("../../state/sandbox-session.js"); + const shields = requireDist("../../shields/index.js"); const timerControl = requireDist("../../shields/timer-control.js"); vi.spyOn(resolve, "resolveOpenshell").mockReturnValue("/usr/bin/openshell"); @@ -67,13 +74,22 @@ function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarne vi.spyOn(onboardSession, "loadSession").mockReturnValue({ sandboxName: "alpha" }); vi.spyOn(onboardSession, "updateSession").mockImplementation((mutator: unknown) => { const session = { sandboxName: "alpha" }; - if (typeof mutator === "function") (mutator as (value: typeof session) => void)(session); + typeof mutator === "function" && (mutator as (value: typeof session) => void)(session); return session; }); const runOpenshellSpy = vi.spyOn(runtime, "runOpenshell").mockImplementation((args: unknown) => { const argv = Array.isArray(args) ? args : []; - if (argv[0] === "sandbox" && argv[1] === "delete") { - return { status: options.deleteStatus ?? 0, stdout: options.deleteOutput ?? "", stderr: "" }; + switch (`${String(argv[0])} ${String(argv[1])}`) { + case "sandbox exec": + events.push("wipe"); + break; + case "sandbox delete": + events.push("delete"); + return { + status: options.deleteStatus ?? 0, + stdout: options.deleteOutput ?? "", + stderr: "", + }; } return { status: 0, stdout: "", stderr: "" }; }); @@ -84,8 +100,9 @@ function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarne const cleanupGatewaySpy = vi .spyOn(destroyGateway, "cleanupGatewayAfterLastSandbox") .mockImplementation(() => undefined); - vi.spyOn(sandboxProviderCleanup, "runSandboxProviderPreDeleteCleanup").mockReturnValue({ - failures: [], + vi.spyOn(sandboxProviderCleanup, "runSandboxProviderPreDeleteCleanup").mockImplementation(() => { + events.push("detach"); + return { failures: [] }; }); vi.spyOn(sandboxProviderCleanup, "emitProviderDetachResidualHint").mockImplementation( () => undefined, @@ -101,13 +118,39 @@ function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarne .spyOn(ollamaProxy, "unloadOllamaModels") .mockImplementation(() => undefined); vi.spyOn(tunnelServices, "stopAll").mockImplementation(() => undefined); - vi.spyOn(timerControl, "killTimer").mockReturnValue({ warnings: [] }); + vi.spyOn(timerControl, "readTimerMarker").mockReturnValue( + options.activeTimer + ? { + pid: 4242, + sandboxName: "alpha", + snapshotPath: "/tmp/policy.yaml", + restoreAt: "2026-06-27T06:00:00.000Z", + processToken: "a".repeat(32), + } + : null, + ); + const shieldsUpSpy = vi.spyOn(shields, "shieldsUp").mockImplementation(() => { + events.push("harden"); + const shieldsUpError = options.shieldsUpError; + switch (shieldsUpError) { + case undefined: + break; + default: + throw shieldsUpError; + } + }); + const killTimerSpy = vi.spyOn(timerControl, "killTimer").mockImplementation(() => { + events.push("timer-cleanup"); + return { warnings: [] }; + }); logSpy.mockClear(); return { cleanupGatewaySpy, destroySandbox: requireDist(destroyModulePath).destroySandbox, + events, + killTimerSpy, killStaleProxySpy, logSpy, removeSandboxSpy, @@ -115,6 +158,7 @@ function createDestroyHarness(options: DestroyHarnessOptions = {}): DestroyHarne selectGatewaySpy, stopNimByNameSpy, unloadOllamaModelsSpy, + shieldsUpSpy, }; } @@ -175,4 +219,33 @@ describe("destroySandbox flow", () => { expect(harness.cleanupGatewaySpy).not.toHaveBeenCalled(); expect(exitSpy).toHaveBeenCalledWith(7); }); + + it("wipes while mutable, hardens an active timer window, then deletes and clears it", async () => { + const harness = createDestroyHarness({ activeTimer: true }); + + await expect(harness.destroySandbox("alpha", { yes: true })).resolves.toBeUndefined(); + + expect(harness.events).toEqual( + expect.arrayContaining(["wipe", "harden", "detach", "delete", "timer-cleanup"]), + ); + expect(harness.events.indexOf("wipe")).toBeLessThan(harness.events.indexOf("harden")); + expect(harness.events.indexOf("harden")).toBeLessThan(harness.events.indexOf("delete")); + expect(harness.events.indexOf("delete")).toBeLessThan(harness.events.indexOf("timer-cleanup")); + }); + + it("does not delete when active-window hardening fails after the wipe", async () => { + const harness = createDestroyHarness({ + activeTimer: true, + shieldsUpError: new Error("injected hardening failure"), + }); + + await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow( + "injected hardening failure", + ); + + expect(harness.events).toContain("wipe"); + expect(harness.events).toContain("harden"); + expect(harness.events).not.toContain("delete"); + expect(harness.killTimerSpy).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 84dce38891b..e40de33bdf2 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -25,7 +25,8 @@ import { } from "../../onboard/sandbox-provider-cleanup"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import { redact } from "../../security/redact"; -import { killTimer as defaultKillShieldsTimer } from "../../shields/timer-control"; +import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; +import { killTimer as defaultKillShieldsTimer, readTimerMarker } from "../../shields/timer-control"; import type { Session } from "../../state/onboard-session"; import * as onboardSession from "../../state/onboard-session"; import { resolveNemoclawStateDir } from "../../state/paths"; @@ -40,7 +41,7 @@ import { selectGatewayForSandboxDestroy, } from "./destroy-gateway"; import { getSandboxTargetGatewayName } from "./gateway-target"; -import { wipeSandboxState, type WipeSandboxStateDeps } from "./wipe-state"; +import { type WipeSandboxStateDeps, wipeSandboxState } from "./wipe-state"; type DockerRmi = (tag: string, opts?: { ignoreError?: boolean }) => { status: number | null }; @@ -292,10 +293,10 @@ export function cleanupShieldsDestroyArtifacts( }); } +export type { WipeSandboxStateDeps }; // Re-export so existing callers (tests, downstream code) keep working after // the wipe was extracted out of the destroy monolith (#5455 PRA-2). export { wipeSandboxState }; -export type { WipeSandboxStateDeps }; export async function destroySandbox( sandboxName: string, @@ -373,31 +374,75 @@ export async function destroySandbox( const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); - // Wipe persistent state AFTER the gateway is selected so the exec targets - // the sandbox's recorded gateway (#5455 PRA-5), but BEFORE delete because - // `sandbox delete` unmounts the PVC and `rm -rf` could no longer reach it. - // PRA-2's later ask to defer past delete is physically impossible and - // contradicts PRA-5; the wipe-state docstring covers the full source- - // boundary justification. - wipeSandboxState(sandboxName); - - const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { - runOpenshell, - redact, - }); - const deleteResult = runOpenshell(["sandbox", "delete", sandboxName], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - const { output: deleteOutput, alreadyGone } = getSandboxDeleteOutcome(deleteResult); + const destructiveResult = withTimerBoundShieldsMutationLock( + sandboxName, + "destroy sandbox", + () => { + // Wipe persistent state AFTER the gateway is selected so the exec targets + // the sandbox's recorded gateway (#5455 PRA-5), but BEFORE delete because + // `sandbox delete` unmounts the PVC and `rm -rf` could no longer reach it. + // Hold the same lock used by the auto-restore timer through wipe, provider + // detach, and delete. A timer that is already restoring finishes first; + // a waiting timer cannot mutate this sandbox or a same-name replacement. + wipeSandboxState(sandboxName); + + // The wipe needs the timed mutable posture so the sandbox user can + // remove manifest state. Convert it back to a verified locked posture + // immediately afterward and before delete. The outer owner carries the + // timer takeover token throughout, so a deadline/crash during the wipe + // can still reclaim it; after shieldsUp succeeds, delete failure or + // process death leaves a surviving sandbox hardened. + if (readTimerMarker(sandboxName)) { + const { shieldsUp: hardenShields } = + require("../../shields") as typeof import("../../shields"); + hardenShields(sandboxName, { + throwOnError: true, + allowLegacyHermesProtocol: true, + }); + } + + const lockedDetachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { + runOpenshell, + redact, + }); + const lockedDeleteResult = runOpenshell(["sandbox", "delete", sandboxName], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const { output: deleteOutput, alreadyGone: lockedAlreadyGone } = + getSandboxDeleteOutcome(lockedDeleteResult); + + if (lockedDeleteResult.status !== 0 && !lockedAlreadyGone) { + // Any active timer was cleared only after shieldsUp verified the live + // sandbox was hardened. Preserve that locked state on delete failure; + // do not remove its local shields record as if deletion had succeeded. + return { + ok: false as const, + deleteOutput, + exitCode: lockedDeleteResult.status || 1, + }; + } - if (deleteResult.status !== 0 && !alreadyGone) { - if (deleteOutput) { - console.error(` ${deleteOutput}`); + // The live sandbox is now gone while this name remains serialized. + // Revoke the timer and local shields state before releasing the lock so + // neither can target a subsequently created sandbox with the same name. + cleanupShieldsDestroyArtifacts(sandboxName); + return { + ok: true as const, + detachOutcome: lockedDetachOutcome, + deleteResult: lockedDeleteResult, + alreadyGone: lockedAlreadyGone, + }; + }, + ); + if (!destructiveResult.ok) { + if (destructiveResult.deleteOutput) { + console.error(` ${destructiveResult.deleteOutput}`); } console.error(` Failed to destroy sandbox '${sandboxName}'.`); - process.exit(deleteResult.status || 1); + process.exit(destructiveResult.exitCode); } + const { detachOutcome, deleteResult, alreadyGone } = destructiveResult; const deleteSucceededOrAlreadyGone = deleteResult.status === 0 || alreadyGone; const shouldStopHostServices = shouldStopHostServicesAfterDestroy({ @@ -409,7 +454,6 @@ export async function destroySandbox( cleanupSandboxServices(sandboxName, { stopHostServices: shouldStopHostServices, }); - cleanupShieldsDestroyArtifacts(sandboxName); // The sandbox's gateway was captured before the registry entry is removed — // post-removal lookups return null and would collapse the cleanup target // back to the default gateway. diff --git a/src/lib/actions/sandbox/forward-health.ts b/src/lib/actions/sandbox/forward-health.ts index 8bab553dea3..a4c71045543 100644 --- a/src/lib/actions/sandbox/forward-health.ts +++ b/src/lib/actions/sandbox/forward-health.ts @@ -2,27 +2,40 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; -import type { SandboxForwardHealth, SandboxForwardListEntry } from "./process-recovery"; + +export type SandboxForwardListEntry = { + sandboxName: string; + port: string; + status: string; +}; + +export type SandboxForwardHealth = boolean | "occupied" | null; + +function liveEntriesForPort( + entries: SandboxForwardListEntry[], + port: string, +): SandboxForwardListEntry[] { + return entries.filter((entry) => entry.port === port && entry.status === "running"); +} export function classifySandboxForwardHealth( entries: SandboxForwardListEntry[], sandboxName: string, port: string, ): Exclude { - const match = entries.find((entry) => entry.port === port); - if (!match) return false; - if (match.sandboxName !== sandboxName) return "occupied"; - return match.status === "running"; + const liveEntries = liveEntriesForPort(entries, port); + if (liveEntries.some((entry) => entry.sandboxName !== sandboxName)) return "occupied"; + return liveEntries.some((entry) => entry.sandboxName === sandboxName); } /** * Like {@link classifySandboxForwardHealth} but accepts a reachability * callback that probes whether the local forwarded port actually answers. - * When the entry-based classification would return `false`, the - * reachability check overrides it: a port that answers is healthy - * regardless of what `forward list` reports. The "occupied" verdict is - * preserved — we never silently take over a forward owned by another - * sandbox, even if that forward happens to be reachable. + * OpenShell's exact live owner metadata remains authoritative: reachability + * cannot prove which process owns a local listener, so it must never upgrade a + * missing or non-running entry. A target-owned running row is necessary but not + * sufficient; it must also answer the local transport probe so stale list data + * cannot make recovery report a dead forward as healthy. */ export function classifyForwardHealthWithReachability( entries: SandboxForwardListEntry[], @@ -30,15 +43,15 @@ export function classifyForwardHealthWithReachability( port: string, isReachable: () => boolean, ): Exclude { - const verdict = classifySandboxForwardHealth(entries, sandboxName, port); - if (verdict !== false) return verdict; - return isReachable() ? true : false; + const ownership = classifySandboxForwardHealth(entries, sandboxName, port); + if (ownership !== true) return ownership; + return isReachable(); } /** - * Synchronous reachability check for a local port. Used to override a - * negative `openshell forward list` verdict when the forward is actually - * still serving traffic. + * Synchronous reachability check for a local port. Reachability is transport + * evidence only; callers must pair it with authoritative OpenShell owner + * metadata and must not treat an arbitrary local listener as an owned forward. */ export function isLocalForwardReachable(port: number): boolean { const script = diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts new file mode 100644 index 00000000000..fc5713dfa9c --- /dev/null +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -0,0 +1,236 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { captureOpenshell, isCommandTimeout, runOpenshell } from "../../adapters/openshell/runtime"; +import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import * as agentRuntime from "../../agent/runtime"; +import { DASHBOARD_PORT } from "../../core/ports"; +import { waitUntil } from "../../core/wait"; +import { getActiveMessagingHostForward } from "../../messaging/host-forward"; +import type { SandboxMessagingHostForwardPlan } from "../../messaging/manifest"; +import { hydrateDerivedSandboxMessagingPlanFields } from "../../messaging/persistence"; +import { parseSandboxMessagingPlan } from "../../messaging/plan-validation"; +import * as registry from "../../state/registry"; +import { parseForwardList } from "../../state/sandbox-session"; +import { + classifyForwardHealthWithReachability, + isLocalForwardReachable, + type SandboxForwardHealth, + type SandboxForwardListEntry, +} from "./forward-health"; +import { + ensureHermesDashboardPortForwardIfEnabled as ensureHermesDashboardPortForward, + getHermesDashboardRecoveryConfig, +} from "./hermes-dashboard-recovery"; + +type SandboxPortAgent = { forwardPort?: unknown; runtime?: { kind?: unknown } } | null; + +type SandboxPortDeps = { + getSandbox?: typeof registry.getSandbox; + getSessionAgent?: (sandboxName?: string) => SandboxPortAgent; +}; + +function isValidPort(value: unknown): value is number { + return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; +} + +export function resolveSandboxDashboardPort( + sandboxName: string, + deps: SandboxPortDeps = {}, +): number { + const getSessionAgent = deps.getSessionAgent ?? agentRuntime.getSessionAgent; + const agent = getSessionAgent(sandboxName); + if (agent && agentRuntime.hasGatewayRuntime(agent) && isValidPort(agent.forwardPort)) { + return agent.forwardPort; + } + + const getSandbox = deps.getSandbox ?? registry.getSandbox; + const sandbox = getSandbox(sandboxName); + return isValidPort(sandbox?.dashboardPort) ? sandbox.dashboardPort : DASHBOARD_PORT; +} + +/** + * Re-establish the dashboard port forward to the sandbox. + * Uses the recorded dashboard port for OpenClaw sandboxes, or the agent's + * declared forward port when a non-OpenClaw agent is active. + * Returns true when `forward start` succeeded and a follow-up probe + * confirms the new entry is running, false otherwise. + */ +export function ensureSandboxPortForward(sandboxName: string): boolean { + return ensureSandboxPortForwardForPort(sandboxName, resolveSandboxDashboardPort(sandboxName)); +} + +/** + * Probe `openshell forward list` for the sandbox's dashboard forward. + * Returns true when an entry exists for the expected sandbox+port pair + * with STATUS=running, false when the entry is missing or non-running, + * "occupied" when another sandbox already owns the expected port, and + * null when openshell is unreachable. + * + * The in-sandbox gateway and the host-side forward are independent + * dimensions: the forward can die (host SSH session dropped, list shows + * STATUS=dead) while the gateway keeps listening on 127.0.0.1:. + * + * Local reachability is intentionally not sufficient: an unrelated listener + * cannot prove that OpenShell assigned this sandbox the requested host port. + */ +export function isSandboxForwardHealthy(sandboxName: string): SandboxForwardHealth { + return isSandboxPortForwardHealthy(sandboxName, resolveSandboxDashboardPort(sandboxName)); +} + +export function isSandboxPortForwardHealthy( + sandboxName: string, + port: number, +): SandboxForwardHealth { + const result = captureOpenshell(["forward", "list"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + if (!result || isCommandTimeout(result) || result.status !== 0) return null; + const entries = parseForwardList(result.output) as SandboxForwardListEntry[]; + return classifyForwardHealthWithReachability(entries, sandboxName, String(port), () => + isLocalForwardReachable(port), + ); +} + +export function ensureSandboxPortForwardForPort(sandboxName: string, port: number): boolean { + const forwardHealth = isSandboxPortForwardHealthy(sandboxName, port); + if (forwardHealth === true) return true; + if (forwardHealth === "occupied") return false; + + const stopResult = runOpenshell(["forward", "stop", String(port), sandboxName], { + ignoreError: true, + stdio: "ignore", + }); + if (stopResult.status !== 0) { + console.error( + ` Warning: openshell forward stop ${port} ${sandboxName} exited ${stopResult.status}; attempting restart anyway.`, + ); + } + const startResult = runOpenshell( + ["forward", "start", "--background", String(port), sandboxName], + { + ignoreError: true, + }, + ); + if (startResult.status !== 0) return false; + + // `forward start --background` can return before its authoritative list + // entry becomes visible. Poll for the exact live sandbox+port owner instead + // of accepting an arbitrary reachable listener or failing on the first + // metadata refresh. + let health = isSandboxPortForwardHealthy(sandboxName, port); + if (health === true) return true; + if (health === "occupied") return false; + const configuredWaitMs = Number(process.env.NEMOCLAW_FORWARD_RECOVERY_WAIT_MS ?? "3000"); + const waitMs = Number.isFinite(configuredWaitMs) ? Math.max(0, configuredWaitMs) : 3000; + if (waitMs === 0) return false; + + let occupied = false; + const settled = waitUntil( + () => { + health = isSandboxPortForwardHealthy(sandboxName, port); + if (health === "occupied") { + occupied = true; + return true; + } + return health === true; + }, + { + deadlineMs: Date.now() + waitMs, + initialIntervalMs: 100, + maxIntervalMs: 500, + backoffFactor: 1.5, + }, + ); + return settled && !occupied; +} + +export function ensureHermesDashboardPortForwardIfEnabled(sandboxName: string): boolean | null { + return ensureHermesDashboardPortForward(sandboxName, { + isPortForwardHealthy: isSandboxPortForwardHealthy, + ensurePortForward: ensureSandboxPortForwardForPort, + }); +} + +function getSandboxMessagingHostForward( + sandboxName: string, +): SandboxMessagingHostForwardPlan | null { + const entry = registry.getSandbox(sandboxName); + const parsed = parseSandboxMessagingPlan(entry?.messaging?.plan, { sandboxName }); + const plan = parsed ? hydrateDerivedSandboxMessagingPlanFields(parsed) : null; + return getActiveMessagingHostForward(plan); +} + +export function ensureMessagingHostForwardHealthy(sandboxName: string): boolean | null { + const forward = getSandboxMessagingHostForward(sandboxName); + if (!forward) return null; + const health = isSandboxPortForwardHealthy(sandboxName, forward.port); + if (health === true) return true; + if (health === "occupied") return false; + return ensureSandboxPortForwardForPort(sandboxName, forward.port); +} + +export function recoverMessagingHostForward( + sandboxName: string, + { quiet }: { quiet: boolean }, +): boolean | null { + const recovered = ensureMessagingHostForwardHealthy(sandboxName); + if (!quiet && recovered === false) { + console.error(" Messaging webhook port forward could not be re-established."); + } + return recovered; +} + +/** + * Re-establish every declared `forward_ports` entry on the active agent + * manifest that is not already owned by another recovery helper. The + * primary dashboard port is owned by `ensureSandboxPortForward`; the + * optional Hermes web dashboard port is owned by + * `ensureHermesDashboardPortForwardIfEnabled`. + */ +export function ensureDeclaredAgentForwardPortsHealthy( + sandboxName: string, + primaryPort: number, +): boolean | null { + const agent = agentRuntime.getSessionAgent(sandboxName); + if (!agent) return null; + const declared = (agent as { forward_ports?: unknown }).forward_ports; + if (!Array.isArray(declared) || declared.length === 0) return null; + const hermesDashboard = getHermesDashboardRecoveryConfig(sandboxName); + const skipSet = new Set([primaryPort]); + if (hermesDashboard && Number.isInteger(hermesDashboard.publicPort)) { + skipSet.add(hermesDashboard.publicPort); + } + let sawCovered = false; + let allHealthy = true; + for (const candidate of declared) { + if (typeof candidate !== "number") continue; + if (!Number.isInteger(candidate) || candidate < 1024 || candidate > 65535) continue; + if (skipSet.has(candidate)) continue; + sawCovered = true; + const health = isSandboxPortForwardHealthy(sandboxName, candidate); + if (health === true) continue; + if (health === "occupied") { + allHealthy = false; + continue; + } + if (!ensureSandboxPortForwardForPort(sandboxName, candidate)) { + allHealthy = false; + } + } + if (!sawCovered) return null; + return allHealthy; +} + +export function recoverDeclaredAgentForwardPorts( + sandboxName: string, + recoveryPort: number, + { quiet }: { quiet: boolean }, +): boolean | null { + const recovered = ensureDeclaredAgentForwardPortsHealthy(sandboxName, recoveryPort); + if (!quiet && recovered === false) { + console.error(" One or more agent-declared port forwards could not be re-established."); + } + return recovered; +} diff --git a/src/lib/actions/sandbox/gateway-restart.test.ts b/src/lib/actions/sandbox/gateway-restart.test.ts new file mode 100644 index 00000000000..56ef2b02f3e --- /dev/null +++ b/src/lib/actions/sandbox/gateway-restart.test.ts @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { GATEWAY_RESTART_MARKERS as MARKERS } from "../../agent/gateway-restart-markers"; +import * as agentRuntime from "../../agent/runtime"; +import * as registry from "../../state/registry"; +import { classifyGatewayRestartFailure } from "./gateway-restart"; +import { restartSandboxGateway } from "./process-recovery"; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("gateway restart failure markers", () => { + it("keeps supervisor failure markers aligned with the classifier", () => { + const expectedMarkers: Array< + [string, ReturnType["layer"]] + > = [ + ["PRIVILEGED_CONTROL_UNAVAILABLE", "privileged control unavailable"], + ["SUPERVISOR_REBUILD_REQUIRED", "privileged control unavailable"], + ["SUPERVISOR_BUSY", "privileged control unavailable"], + [MARKERS.SECRET_BOUNDARY_REFUSED, "secret-boundary refusal"], + [MARKERS.SECRET_BOUNDARY_VALIDATOR_MISSING, "unsafe config path"], + [MARKERS.GATEWAY_UNSAFE_CONFIG_PATH, "unsafe config path"], + [MARKERS.GATEWAY_CONFIG_HASH_MISMATCH, "config hash mismatch"], + ["HERMES_UNSAFE_CONFIG_PATH", "unsafe config path"], + ["HERMES_LOCKED_HASH_MISMATCH", "config hash mismatch"], + ["HERMES_CONFIG_HASH_MISMATCH", "config hash mismatch"], + ["GATEWAY_HEALTH_TIMEOUT", "health timeout"], + [MARKERS.GATEWAY_FAILED, "launch failure"], + ] as const; + + for (const [marker, layer] of expectedMarkers) { + expect( + classifyGatewayRestartFailure({ + status: 1, + stdout: marker, + stderr: "", + }), + ).toMatchObject({ layer }); + } + }); +}); + +describe("restartSandboxGateway — host-mediated gateway restart", () => { + function silenceConsole() { + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + return () => { + log.mockRestore(); + error.mockRestore(); + }; + } + + function baseDeps(overrides = {}) { + return { + getSessionAgent: () => null, + getSandbox: () => ({ name: "alpha", agent: "openclaw" }), + resolveSandboxDashboardPort: () => 18789, + requestGatewaySupervisorAction: vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=123", + stderr: "", + })), + executeSandboxExecCommand: vi.fn(() => null), + waitForRecoveredSandboxGateway: vi.fn(() => true), + ensureSandboxPortForward: vi.fn(() => true), + ensureHermesDashboardPortForwardIfEnabled: vi.fn(() => null), + recoverMessagingHostForward: vi.fn(() => null), + recoverDeclaredAgentForwardPorts: vi.fn(() => null), + printGatewayWedgeDiagnostics: vi.fn(() => false), + ...overrides, + }; + } + + it("refuses supervisor output without a completion marker", () => { + const deps = baseDeps({ + getSandbox: () => ({ name: "openclaw-box", agent: "openclaw" }), + requestGatewaySupervisorAction: vi.fn(() => null), + }); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + + const result = restartSandboxGateway("openclaw-box", { quiet: true, deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "privileged control unavailable", + }); + expect(deps.requestGatewaySupervisorAction).toHaveBeenCalledWith( + "openclaw-box", + "restart", + 210000, + ); + expect(errorSpy).toHaveBeenCalledWith( + " Failure layer: privileged control unavailable - gateway restart failed for 'openclaw-box'.", + ); + }); + + it("force-restarts through PID 1 even when a gateway might already be healthy", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps(); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); + expect(deps.requestGatewaySupervisorAction).toHaveBeenCalledWith("alpha", "restart", 210000); + expect(deps.waitForRecoveredSandboxGateway).toHaveBeenCalledWith("alpha", { + initialManagedHealthPassed: true, + quiet: false, + }); + expect(deps.ensureSandboxPortForward).toHaveBeenCalledWith("alpha"); + } finally { + restore(); + } + }); + + it("uses the injected supervisor action for the managed settle probe", () => { + const restore = silenceConsole(); + const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0.001"; + try { + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "openclaw", + openshellDriver: "docker", + }); + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=123", + stderr: "", + })); + const { waitForRecoveredSandboxGateway: _defaultWait, ...deps } = baseDeps({ + requestGatewaySupervisorAction, + }); + + const result = restartSandboxGateway("alpha", { quiet: true, deps }); + + expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); + expect(requestGatewaySupervisorAction.mock.calls).toEqual([ + ["alpha", "restart", 210000], + ["alpha", "probe"], + ]); + } finally { + previousSettleSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = previousSettleSeconds); + restore(); + } + }); + + it("suppresses restart success output in quiet mode", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps(); + const result = restartSandboxGateway("alpha", { quiet: true, deps }); + + expect(result).toMatchObject({ ok: true, restarted: true, healthPassed: true }); + expect(console.log).not.toHaveBeenCalled(); + } finally { + restore(); + } + }); + + it("reports privileged supervisor unavailability", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ requestGatewaySupervisorAction: vi.fn(() => null) }); + const result = restartSandboxGateway("alpha", { quiet: true, deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "privileged control unavailable", + }); + } finally { + restore(); + } + }); + + it("reports Hermes boundary refusals without hiding diagnostics in quiet mode", () => { + const restore = silenceConsole(); + try { + const hermesAgent = { + name: "hermes", + displayName: "Hermes Agent", + healthProbe: { port: 8642 }, + }; + const deps = baseDeps({ + getSessionAgent: () => hermesAgent, + getSandbox: () => ({ name: "alpha", agent: "hermes" }), + requestGatewaySupervisorAction: vi.fn(() => ({ + status: 1, + stdout: "SECRET_BOUNDARY_REFUSED", + stderr: "[SECURITY] TELEGRAM_BOT_TOKEN (line 2)", + })), + }); + const result = restartSandboxGateway("alpha", { quiet: true, deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "secret-boundary refusal", + }); + expect(deps.requestGatewaySupervisorAction).toHaveBeenCalledWith("alpha", "restart", 210000); + expect(console.error).toHaveBeenCalledWith( + " Failure layer: secret-boundary refusal - gateway restart failed for 'alpha'.", + ); + } finally { + restore(); + } + }); + + it("reports launch failure markers", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + requestGatewaySupervisorAction: vi.fn(() => ({ + status: 1, + stdout: "GATEWAY_FAILED", + stderr: "tail output", + })), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "launch failure" }); + } finally { + restore(); + } + }); + + it("redacts and strips restart failure detail before printing it", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + requestGatewaySupervisorAction: vi.fn(() => ({ + status: 1, + stdout: "GATEWAY_FAILED", + stderr: "\u001b[31mOPENAI_API_KEY=sk-review-secret\u001b[0m", + })), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "launch failure" }); + expect(result.ok).toBe(false); + const failure = result as Extract; + expect(failure.detail).toContain("OPENAI_API_KEY="); + expect(failure.detail).not.toContain("\u001b"); + expect(failure.detail).not.toContain("sk-review-secret"); + const errorOutput = vi.mocked(console.error).mock.calls.join("\n"); + expect(errorOutput).toContain("Failure layer: launch failure"); + expect(errorOutput).toContain("OPENAI_API_KEY="); + expect(errorOutput).not.toContain("\u001b"); + expect(errorOutput).not.toContain("sk-review-secret"); + } finally { + restore(); + } + }); + + it("reports a health timeout after the restart process marker", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ waitForRecoveredSandboxGateway: vi.fn(() => false) }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "health timeout" }); + expect(deps.printGatewayWedgeDiagnostics).toHaveBeenCalledWith( + "alpha", + deps.executeSandboxExecCommand, + ); + } finally { + restore(); + } + }); + + it("fails when the primary dashboard/API forward cannot be restored", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + ensureSandboxPortForward: vi.fn(() => false), + recoverMessagingHostForward: vi.fn(() => true), + recoverDeclaredAgentForwardPorts: vi.fn(() => true), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "forward recovery failure", + detail: expect.stringContaining("primary dashboard/API host forward"), + }); + expect(deps.recoverMessagingHostForward).toHaveBeenCalledWith("alpha", { quiet: false }); + expect(deps.recoverDeclaredAgentForwardPorts).toHaveBeenCalledWith("alpha", 18789, { + quiet: false, + }); + const errorOutput = vi.mocked(console.error).mock.calls.join("\n"); + expect(errorOutput).toContain("Failure layer: forward recovery failure"); + expect(errorOutput).toContain("primary dashboard/API host forward"); + expect(console.log).not.toHaveBeenCalledWith( + expect.stringContaining("Gateway restarted; health passed"), + ); + } finally { + restore(); + } + }); + + it("fails when an enabled auxiliary forward cannot be restored", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + ensureHermesDashboardPortForwardIfEnabled: vi.fn(() => false), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "forward recovery failure", + detail: expect.stringContaining("Hermes dashboard host forward"), + }); + expect(console.log).not.toHaveBeenCalledWith( + expect.stringContaining("Gateway restarted; health passed"), + ); + } finally { + restore(); + } + }); + + it("refuses terminal agents with the unsupported-agent support matrix", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + getSessionAgent: () => ({ + name: "langchain-deepagents-code", + displayName: "LangChain Deep Agents Code", + runtime: { kind: "terminal" }, + }), + getSandbox: () => ({ name: "alpha", agent: "langchain-deepagents-code" }), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); + expect(result.ok).toBe(false); + const failure = result as Extract; + expect(failure.detail).toContain( + "Agent 'langchain-deepagents-code' does not support gateway restart.", + ); + expect(failure.detail).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(failure.detail).toContain("LangChain Deep Agents Code has no gateway runtime."); + const errorOutput = vi.mocked(console.error).mock.calls.join("\n"); + expect(errorOutput).toContain( + "Agent 'langchain-deepagents-code' does not support gateway restart.", + ); + expect(errorOutput).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(deps.requestGatewaySupervisorAction).not.toHaveBeenCalled(); + } finally { + restore(); + } + }); + + it("refuses custom agents when the explicit runtime definition is unavailable", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + getSessionAgent: () => null, + getSandbox: () => ({ name: "alpha", agent: "custom-agent" }), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); + expect(result.ok).toBe(false); + const failure = result as Extract; + expect(failure.detail).toContain("Agent 'custom-agent' does not support gateway restart."); + expect(failure.detail).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(failure.detail).toContain("custom-agent agent definition could not be loaded"); + const errorOutput = vi.mocked(console.error).mock.calls.join("\n"); + expect(errorOutput).toContain("Agent 'custom-agent' does not support gateway restart."); + expect(errorOutput).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(deps.requestGatewaySupervisorAction).not.toHaveBeenCalled(); + } finally { + restore(); + } + }); + + it("fails closed when the persisted agent lookup fails", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + getSessionAgent: () => null, + getSandbox: () => { + throw new Error("registry unavailable"); + }, + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ + ok: false, + failureLayer: "unsupported agent", + detail: expect.stringContaining("Sandbox agent lookup failed: registry unavailable."), + }); + expect(deps.requestGatewaySupervisorAction).not.toHaveBeenCalled(); + } finally { + restore(); + } + }); + + it("refuses custom gateway agents without a supported restart runtime", () => { + const restore = silenceConsole(); + try { + const deps = baseDeps({ + getSessionAgent: () => ({ + name: "custom-gateway", + displayName: "Custom Gateway Agent", + }), + getSandbox: () => ({ name: "alpha", agent: "custom-gateway" }), + }); + const result = restartSandboxGateway("alpha", { deps }); + + expect(result).toMatchObject({ ok: false, failureLayer: "unsupported agent" }); + expect(result.ok).toBe(false); + const failure = result as Extract; + expect(failure.detail).toContain("Agent 'custom-gateway' does not support gateway restart."); + expect(failure.detail).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(failure.detail).toContain( + "Custom Gateway Agent does not declare a supported supervisor-mediated gateway restart runtime.", + ); + const errorOutput = vi.mocked(console.error).mock.calls.join("\n"); + expect(errorOutput).toContain("Agent 'custom-gateway' does not support gateway restart."); + expect(errorOutput).toContain("Gateway restart-supported agents: openclaw, hermes."); + expect(deps.requestGatewaySupervisorAction).not.toHaveBeenCalled(); + } finally { + restore(); + } + }); +}); diff --git a/src/lib/actions/sandbox/gateway-restart.ts b/src/lib/actions/sandbox/gateway-restart.ts new file mode 100644 index 00000000000..42ade503ff5 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-restart.ts @@ -0,0 +1,334 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { GATEWAY_RESTART_MARKERS as MARKERS } from "../../agent/gateway-restart-markers"; +import * as agentRuntime from "../../agent/runtime"; +import { G, R } from "../../cli/terminal-style"; +import { redactFull } from "../../security/redact"; + +export type GatewayRestartCommandResult = { + status: number; + stdout: string; + stderr: string; +}; + +export type GatewayRestartFailureLayer = + | "unsupported agent" + | "privileged control unavailable" + | "secret-boundary refusal" + | "unsafe config path" + | "config hash mismatch" + | "launch failure" + | "health timeout" + | "forward recovery failure"; + +export type GatewayRestartResult = + | { + ok: true; + restarted: true; + healthPassed: true; + forwardRecovered: boolean; + } + | { + ok: false; + failureLayer: GatewayRestartFailureLayer; + detail: string; + }; + +type SandboxAgentLookup = (sandboxName: string) => { agent?: string | null } | null | undefined; + +type SupervisorAction = ( + sandboxName: string, + action: "restart" | "recover" | "probe", + timeout?: number, +) => GatewayRestartCommandResult | null; + +type SandboxExec = ( + sandboxName: string, + command: string, + timeout?: number, +) => GatewayRestartCommandResult | null; + +const GATEWAY_RESTART_SUPPORTED_AGENTS = ["openclaw", "hermes"] as const; + +export type GatewayRestartDeps = { + getSessionAgent: typeof agentRuntime.getSessionAgent; + getSandbox: SandboxAgentLookup; + resolveSandboxDashboardPort: (sandboxName: string) => number; + requestGatewaySupervisorAction: SupervisorAction; + executeSandboxExecCommand: SandboxExec; + waitForRecoveredSandboxGateway: ( + sandboxName: string, + options?: { + quiet?: boolean; + timeoutSeconds?: number; + initialManagedHealthPassed?: boolean; + }, + ) => boolean; + ensureSandboxPortForward: (sandboxName: string) => boolean; + ensureHermesDashboardPortForwardIfEnabled: (sandboxName: string) => boolean | null; + recoverMessagingHostForward: (sandboxName: string, options: { quiet: boolean }) => boolean | null; + recoverDeclaredAgentForwardPorts: ( + sandboxName: string, + recoveryPort: number, + options: { quiet: boolean }, + ) => boolean | null; + printGatewayWedgeDiagnostics: ( + sandboxName: string, + exec: (sandboxName: string, command: string) => GatewayRestartCommandResult | null, + ) => boolean; +}; + +export type RestartSandboxGatewayOptions = { + quiet?: boolean; + deps?: Partial; +}; + +export function sandboxAgentName( + sandboxName: string, + getSandbox: SandboxAgentLookup, +): string | null { + return getSandbox(sandboxName)?.agent ?? null; +} + +function gatewayRestartOutput(result: GatewayRestartCommandResult): string { + return [result.stdout, result.stderr].filter(Boolean).join("\n"); +} + +const ANSI_CONTROL_RE = + /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\)|[@-_])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g; + +function sanitizeGatewayRestartFailureLine(line: string): string { + return redactFull(line.replace(ANSI_CONTROL_RE, "")); +} + +function sanitizeGatewayRestartFailureDetail(detail: string): string { + return detail + .split(/\r?\n/) + .map((line) => sanitizeGatewayRestartFailureLine(line.trim())) + .filter(Boolean) + .join("\n"); +} + +export function classifyGatewayRestartFailure(result: GatewayRestartCommandResult | null): { + layer: GatewayRestartFailureLayer; + detail: string; +} { + if (!result) { + return { + layer: "privileged control unavailable", + detail: "privileged gateway supervisor control did not return command output", + }; + } + + const output = gatewayRestartOutput(result); + const detail = sanitizeGatewayRestartFailureDetail(output.trim()); + if ( + output.includes(MARKERS.ROOT_EXEC_UNAVAILABLE) || + output.includes("PRIVILEGED_CONTROL_UNAVAILABLE") || + output.includes("SUPERVISOR_UNAVAILABLE") || + output.includes("SUPERVISOR_REBUILD_REQUIRED") || + output.includes("SUPERVISOR_UNSAFE_CONTROL_DIR") || + output.includes("SUPERVISOR_BUSY") || + output.includes("SUPERVISOR_SIGNAL_FAILED") || + output.includes("SUPERVISOR_INVALID_STATUS") || + output.includes(MARKERS.GOSU_MISSING) || + output.includes(MARKERS.GATEWAY_USER_MISSING) + ) { + return { + layer: "privileged control unavailable", + detail: detail || "privileged gateway supervisor control unavailable", + }; + } + if (output.includes(MARKERS.SECRET_BOUNDARY_REFUSED)) { + return { layer: "secret-boundary refusal", detail: detail || "boundary refused" }; + } + if ( + output.includes(MARKERS.GATEWAY_UNSAFE_CONFIG_PATH) || + output.includes("HERMES_UNSAFE_CONFIG_PATH") || + output.includes(MARKERS.HERMES_RUNTIME_CONFIG_GUARD_MISSING) || + output.includes(MARKERS.SECRET_BOUNDARY_VALIDATOR_MISSING) + ) { + return { layer: "unsafe config path", detail: detail || "unsafe config path" }; + } + if ( + output.includes(MARKERS.GATEWAY_CONFIG_HASH_MISMATCH) || + output.includes("HERMES_LOCKED_HASH_MISMATCH") || + output.includes("HERMES_CONFIG_HASH_MISMATCH") + ) { + return { + layer: "config hash mismatch", + detail: detail || "gateway config hash mismatch", + }; + } + if (output.includes("GATEWAY_HEALTH_TIMEOUT") || output.includes("SUPERVISOR_TIMEOUT")) { + return { layer: "health timeout", detail: detail || "gateway health timeout" }; + } + return { layer: "launch failure", detail: detail || `restart exited ${result.status}` }; +} + +export function printGatewayRestartFailure( + sandboxName: string, + layer: GatewayRestartFailureLayer, + detail: string, +): void { + console.error(` Failure layer: ${layer} - gateway restart failed for '${sandboxName}'.`); + if (!detail.trim()) return; + const lines = detail + .split(/\r?\n/) + .map((line) => sanitizeGatewayRestartFailureLine(line.trim())) + .filter(Boolean) + .slice(-12); + for (const line of lines) { + console.error(` ${line}`); + } +} + +function unsupportedGatewayRestartAgentDetail(agentName: string, reason: string): string { + return [ + `Agent '${agentName}' does not support gateway restart.`, + `Gateway restart-supported agents: ${GATEWAY_RESTART_SUPPORTED_AGENTS.join(", ")}.`, + reason, + ].join("\n"); +} + +type RestartAuxiliaryRecoveryResult = { + label: string; + recovered: boolean | null; +}; + +function failedAuxiliaryRecoveryDetail(results: RestartAuxiliaryRecoveryResult[]): string | null { + const failed = results + .filter((result) => result.recovered === false) + .map((result) => result.label); + if (failed.length === 0) return null; + return `gateway health passed but ${failed.join(", ")} could not be re-established`; +} + +export function restartSandboxGatewayWithDeps( + sandboxName: string, + { + quiet = false, + deps, + }: { + quiet?: boolean; + deps: GatewayRestartDeps; + }, +): GatewayRestartResult { + const agent = deps.getSessionAgent(sandboxName); + let persistedAgent: string | null; + try { + persistedAgent = sandboxAgentName(sandboxName, deps.getSandbox); + } catch (error) { + const reason = + error instanceof Error && error.message.trim() + ? `Sandbox agent lookup failed: ${error.message}.` + : "Sandbox agent lookup failed."; + const detail = unsupportedGatewayRestartAgentDetail("unknown", reason); + printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return { ok: false, failureLayer: "unsupported agent", detail }; + } + const agentName = agent?.name ?? persistedAgent ?? "openclaw"; + const dashboardPort = deps.resolveSandboxDashboardPort(sandboxName); + + if (!agent && persistedAgent && persistedAgent !== "openclaw") { + const detail = unsupportedGatewayRestartAgentDetail( + persistedAgent, + `${persistedAgent} agent definition could not be loaded.`, + ); + printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return { ok: false, failureLayer: "unsupported agent", detail }; + } + if (agent && !agentRuntime.hasGatewayRuntime(agent)) { + const detail = unsupportedGatewayRestartAgentDetail( + agent.name, + `${agentRuntime.getAgentDisplayName(agent)} has no gateway runtime.`, + ); + printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return { ok: false, failureLayer: "unsupported agent", detail }; + } + if (agentName === "hermes") { + if (!agent || agent.name !== "hermes") { + const detail = "Hermes agent definition could not be loaded."; + printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return { ok: false, failureLayer: "unsupported agent", detail }; + } + } else if (agentName !== "openclaw" || (agent && agent.name !== "openclaw")) { + const unsupportedAgentName = agent?.name ?? agentName; + const reason = + `${agentRuntime.getAgentDisplayName(agent)} does not declare a supported supervisor-mediated ` + + "gateway restart runtime."; + const detail = unsupportedGatewayRestartAgentDetail(unsupportedAgentName, reason); + printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return { ok: false, failureLayer: "unsupported agent", detail }; + } + + if (!quiet) { + console.log(""); + console.log( + ` Restarting ${agentRuntime.getAgentDisplayName(agent)} gateway in '${sandboxName}'...`, + ); + } + const restartResult = deps.requestGatewaySupervisorAction(sandboxName, "restart", 210000); + const hasRestartMarker = + restartResult?.status === 0 && + restartResult.stdout.split(/\r?\n/).some((line) => line.startsWith("GATEWAY_PID=")); + if (!hasRestartMarker) { + const failure = classifyGatewayRestartFailure(restartResult); + printGatewayRestartFailure(sandboxName, failure.layer, failure.detail); + return { ok: false, failureLayer: failure.layer, detail: failure.detail }; + } + + if ( + !deps.waitForRecoveredSandboxGateway(sandboxName, { + quiet, + initialManagedHealthPassed: true, + }) + ) { + const detail = "gateway process restarted but health did not pass before timeout"; + printGatewayRestartFailure(sandboxName, "health timeout", detail); + deps.printGatewayWedgeDiagnostics(sandboxName, deps.executeSandboxExecCommand); + return { ok: false, failureLayer: "health timeout", detail }; + } + + const forwardRecovered = deps.ensureSandboxPortForward(sandboxName); + const dashboardForwardRecovered = deps.ensureHermesDashboardPortForwardIfEnabled(sandboxName); + const messagingForwardRecovered = deps.recoverMessagingHostForward(sandboxName, { quiet }); + const declaredForwardsRecovered = deps.recoverDeclaredAgentForwardPorts( + sandboxName, + dashboardPort, + { quiet }, + ); + const auxiliaryFailureDetail = failedAuxiliaryRecoveryDetail([ + { label: "the Hermes dashboard host forward", recovered: dashboardForwardRecovered }, + { label: "the messaging webhook host forward", recovered: messagingForwardRecovered }, + { label: "one or more agent-declared host forwards", recovered: declaredForwardsRecovered }, + ]); + + if (!forwardRecovered) { + const detail = + "gateway health passed but the primary dashboard/API host forward could not be re-established"; + printGatewayRestartFailure(sandboxName, "forward recovery failure", detail); + return { ok: false, failureLayer: "forward recovery failure", detail }; + } + if (auxiliaryFailureDetail !== null) { + printGatewayRestartFailure(sandboxName, "forward recovery failure", auxiliaryFailureDetail); + return { ok: false, failureLayer: "forward recovery failure", detail: auxiliaryFailureDetail }; + } + + if (!quiet) { + console.log( + ` ${G}✓${R} Gateway restarted; health passed; forwards checked/recovered for '${sandboxName}'.`, + ); + } + return { + ok: true, + restarted: true, + healthPassed: true, + forwardRecovered: + forwardRecovered || + dashboardForwardRecovered === true || + messagingForwardRecovered === true || + declaredForwardsRecovered === true, + }; +} diff --git a/src/lib/actions/sandbox/hermes-dashboard-recovery.test.ts b/src/lib/actions/sandbox/hermes-dashboard-recovery.test.ts index fe8a9b3b20d..7f8f46002da 100644 --- a/src/lib/actions/sandbox/hermes-dashboard-recovery.test.ts +++ b/src/lib/actions/sandbox/hermes-dashboard-recovery.test.ts @@ -5,7 +5,6 @@ import { describe, expect, it, vi } from "vitest"; import { ensureHermesDashboardPortForwardIfEnabled, getHermesDashboardRecoveryConfig, - recoverHermesDashboardProcessIfEnabled, } from "./hermes-dashboard-recovery"; describe("Hermes dashboard recovery helpers", () => { @@ -85,7 +84,7 @@ describe("Hermes dashboard recovery helpers", () => { isPortForwardHealthy: () => true, ensurePortForward, }), - ).toBe(false); + ).toBe(true); const ensurePortForwardWhenOccupied = vi.fn(() => true); expect( @@ -105,45 +104,4 @@ describe("Hermes dashboard recovery helpers", () => { }), ).toBeNull(); }); - - it("reports dashboard process recovery only for successful recovery markers", () => { - const buildRecoveryScript = vi.fn(() => "dashboard recovery"); - const getRecoveryConfig = () => ({ - publicPort: 9119, - internalPort: 19119, - tuiEnabled: true, - }); - - expect( - recoverHermesDashboardProcessIfEnabled("alpha", { - getRecoveryConfig, - buildRecoveryScript, - executeCommand: (_sandboxName, command) => ({ - status: 0, - stdout: command === "dashboard recovery" ? "DASHBOARD_PID=42" : "", - stderr: "", - }), - }), - ).toBe(true); - expect(buildRecoveryScript).toHaveBeenCalledWith({ - publicPort: 9119, - internalPort: 19119, - tuiEnabled: true, - }); - - expect( - recoverHermesDashboardProcessIfEnabled("alpha", { - getRecoveryConfig, - buildRecoveryScript, - executeCommand: () => ({ status: 1, stdout: "DASHBOARD_FAILED", stderr: "" }), - }), - ).toBe(false); - - expect( - recoverHermesDashboardProcessIfEnabled("alpha", { - getRecoveryConfig: () => null, - executeCommand: () => ({ status: 0, stdout: "DASHBOARD_PID=42", stderr: "" }), - }), - ).toBeNull(); - }); }); diff --git a/src/lib/actions/sandbox/hermes-dashboard-recovery.ts b/src/lib/actions/sandbox/hermes-dashboard-recovery.ts index da9f5739d8c..f8053e476f4 100644 --- a/src/lib/actions/sandbox/hermes-dashboard-recovery.ts +++ b/src/lib/actions/sandbox/hermes-dashboard-recovery.ts @@ -1,13 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import * as agentRuntime from "../../agent/runtime"; import * as registry from "../../state/registry"; -import type { SandboxCommandResult, SandboxForwardHealth } from "./process-recovery"; +import type { SandboxForwardHealth } from "./forward-health"; -type RecoveryConfigReader = ( - sandboxName: string, -) => agentRuntime.HermesDashboardRecoveryConfig | null; +export type HermesDashboardRecoveryConfig = { + publicPort: number; + internalPort: number; + tuiEnabled?: boolean; +}; + +type RecoveryConfigReader = (sandboxName: string) => HermesDashboardRecoveryConfig | null; function isValidPort(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value >= 1024 && value <= 65535; @@ -16,7 +19,7 @@ function isValidPort(value: unknown): value is number { export function getHermesDashboardRecoveryConfig( sandboxName: string, getSandbox: typeof registry.getSandbox = registry.getSandbox, -): agentRuntime.HermesDashboardRecoveryConfig | null { +): HermesDashboardRecoveryConfig | null { const sandbox = getSandbox(sandboxName); if (sandbox?.agent !== "hermes" || sandbox.hermesDashboardEnabled !== true) return null; if (!isValidPort(sandbox.hermesDashboardPort)) return null; @@ -39,27 +42,7 @@ export function ensureHermesDashboardPortForwardIfEnabled( const dashboard = (deps.getRecoveryConfig ?? getHermesDashboardRecoveryConfig)(sandboxName); if (dashboard === null) return null; const forwardHealth = deps.isPortForwardHealthy(sandboxName, dashboard.publicPort); - if (forwardHealth === true || forwardHealth === "occupied") return false; + if (forwardHealth === true) return true; + if (forwardHealth === "occupied") return false; return deps.ensurePortForward(sandboxName, dashboard.publicPort); } - -export function recoverHermesDashboardProcessIfEnabled( - sandboxName: string, - deps: { - getRecoveryConfig?: RecoveryConfigReader; - executeCommand(sandboxName: string, command: string): SandboxCommandResult | null; - buildRecoveryScript?: typeof agentRuntime.buildHermesDashboardProcessRecoveryScript; - }, -): boolean | null { - const dashboard = (deps.getRecoveryConfig ?? getHermesDashboardRecoveryConfig)(sandboxName); - if (dashboard === null) return null; - const buildRecoveryScript = - deps.buildRecoveryScript ?? agentRuntime.buildHermesDashboardProcessRecoveryScript; - const result = deps.executeCommand(sandboxName, buildRecoveryScript(dashboard)); - return !!( - result && - result.status === 0 && - (result.stdout.includes("DASHBOARD_PID=") || - result.stdout.includes("DASHBOARD_ALREADY_RUNNING")) - ); -} diff --git a/src/lib/actions/sandbox/hermes-secret-boundary-recovery.test.ts b/src/lib/actions/sandbox/hermes-secret-boundary-recovery.test.ts index 0181b1ad88f..f431abf628e 100644 --- a/src/lib/actions/sandbox/hermes-secret-boundary-recovery.test.ts +++ b/src/lib/actions/sandbox/hermes-secret-boundary-recovery.test.ts @@ -7,16 +7,7 @@ vi.mock("../../state/registry", () => ({ getSandbox: vi.fn(), })); -vi.mock("../../runner", () => ({ - shellQuote: (value: unknown) => `'${String(value)}'`, -})); - import type { AgentDefinition } from "../../agent/defs"; -import { - SECRET_BOUNDARY_OK_MARKER, - SECRET_BOUNDARY_REFUSED_MARKER, - SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER, -} from "../../agent/hermes-recovery-boundary"; import * as registry from "../../state/registry"; import { enforceHermesSecretBoundaryOnRunningGateway } from "./hermes-secret-boundary-recovery"; @@ -67,24 +58,20 @@ describe("enforceHermesSecretBoundaryOnRunningGateway", () => { expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("could not be loaded")); }); - it("refuses recovery when the standalone boundary check cannot run", () => { + it("refuses recovery when the privileged controller check cannot run", () => { mockSandboxAgent("hermes"); const exec = vi.fn(() => null); const result = enforceHermesSecretBoundaryOnRunningGateway(SANDBOX, HERMES_AGENT, exec); expect(result).toEqual({ refused: true, reason: "exec-failed", stderr: "" }); - expect(exec).toHaveBeenCalledWith( - SANDBOX, - expect.stringContaining("validate-hermes-env-secret-boundary.py"), - 30000, - ); + expect(exec).toHaveBeenCalledWith(SANDBOX, "recover"); }); it("refuses recovery when the validator reports raw secret-shaped values", () => { mockSandboxAgent("hermes"); const exec = vi.fn(() => - makeExecResult(`${SECRET_BOUNDARY_REFUSED_MARKER}\n`, "[SECURITY] raw key\n", 1), + makeExecResult("SECRET_BOUNDARY_REFUSED\n", "[SECURITY] raw key\n", 1), ); const result = enforceHermesSecretBoundaryOnRunningGateway(SANDBOX, HERMES_AGENT, exec); @@ -94,33 +81,36 @@ describe("enforceHermesSecretBoundaryOnRunningGateway", () => { reason: "raw-secret", stderr: "[SECURITY] raw key\n", }); - expect(exec).toHaveBeenCalledWith( - SANDBOX, - expect.stringContaining("pkill -TERM -f '[h]ermes[[:space:]]+gateway"), - 30000, - ); - expect(exec).toHaveBeenCalledWith( - SANDBOX, - expect.stringContaining("pkill -KILL -f '[h]ermes[[:space:]]+dashboard"), - 30000, - ); + expect(exec).toHaveBeenCalledWith(SANDBOX, "recover"); expect(consoleErrorSpy).toHaveBeenCalledWith(" [SECURITY] raw key"); }); it("allows recovery when the validator accepts the env file", () => { mockSandboxAgent("hermes"); - const exec = vi.fn(() => makeExecResult(`noise\n${SECRET_BOUNDARY_OK_MARKER}\n`)); + const exec = vi.fn(() => makeExecResult("GATEWAY_PID=4242\n")); const result = enforceHermesSecretBoundaryOnRunningGateway(SANDBOX, HERMES_AGENT, exec); expect(result).toEqual({ refused: false }); }); + it("rejects a legacy-script ALREADY_RUNNING marker on the supervisor protocol", () => { + mockSandboxAgent("hermes"); + const exec = vi.fn(() => makeExecResult("ALREADY_RUNNING\n")); + + const result = enforceHermesSecretBoundaryOnRunningGateway(SANDBOX, HERMES_AGENT, exec); + + expect(result).toEqual({ + refused: true, + reason: "unexpected-marker", + stderr: "", + }); + expect(exec).toHaveBeenCalledWith(SANDBOX, "recover"); + }); + it("refuses recovery when an older sandbox image lacks the validator", () => { mockSandboxAgent("hermes"); - const exec = vi.fn(() => - makeExecResult(`${SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER}\n`, "missing\n"), - ); + const exec = vi.fn(() => makeExecResult("SECRET_BOUNDARY_VALIDATOR_MISSING\n", "missing\n", 1)); const result = enforceHermesSecretBoundaryOnRunningGateway(SANDBOX, HERMES_AGENT, exec); diff --git a/src/lib/actions/sandbox/hermes-secret-boundary-recovery.ts b/src/lib/actions/sandbox/hermes-secret-boundary-recovery.ts index 6116fdf0b02..387aa9001a0 100644 --- a/src/lib/actions/sandbox/hermes-secret-boundary-recovery.ts +++ b/src/lib/actions/sandbox/hermes-secret-boundary-recovery.ts @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { - buildHermesEnvFileBoundaryStandaloneCheck, - SECRET_BOUNDARY_OK_MARKER, - SECRET_BOUNDARY_REFUSED_MARKER, - SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER, -} from "../../agent/hermes-recovery-boundary"; import * as agentRuntime from "../../agent/runtime"; import { R } from "../../cli/terminal-style"; import * as registry from "../../state/registry"; @@ -23,9 +17,9 @@ export type HermesSecretBoundaryEnforcement = | { refused: false } | { refused: true; reason: SecretBoundaryRefusalReason; stderr: string }; -type SandboxExec = ( +type GatewaySupervisorRequest = ( sandboxName: string, - command: string, + action: "restart" | "recover" | "probe", timeout?: number, ) => SandboxCommandResult | null; @@ -41,13 +35,15 @@ function printValidatorStderr(stderr: string): void { } /** - * Re-run the Hermes env-file secret-boundary validator against a running - * gateway, before the probe path returns control to the caller. + * Re-run the Hermes env-file secret boundary through the authenticated PID 1 + * control path before a healthy recover returns. PID 1 owns the exact gateway + * child, so a raw-secret refusal can stop the listener without regex matching + * or a second process racing the supervisor. */ export function enforceHermesSecretBoundaryOnRunningGateway( sandboxName: string, agent: ReturnType, - executeSandboxExecCommand: SandboxExec, + requestGatewaySupervisorAction: GatewaySupervisorRequest, ): HermesSecretBoundaryEnforcement | null { const persistedAgent = registry.getSandbox(sandboxName)?.agent; if (persistedAgent !== "hermes") return null; @@ -59,8 +55,7 @@ export function enforceHermesSecretBoundaryOnRunningGateway( console.error(" Refusing recovery to keep the validator-enforced boundary intact."); return { refused: true, reason: "agent-missing", stderr: "" }; } - const script = buildHermesEnvFileBoundaryStandaloneCheck(); - const result = executeSandboxExecCommand(sandboxName, script, 30000); + const result = requestGatewaySupervisorAction(sandboxName, "recover"); if (!result) { console.error(""); console.error( @@ -69,11 +64,11 @@ export function enforceHermesSecretBoundaryOnRunningGateway( console.error(" Refusing recovery to keep the validator-enforced boundary intact."); return { refused: true, reason: "exec-failed", stderr: "" }; } - const stdoutMarker = result.stdout - .split(/\r?\n/) - .reverse() - .find((line) => line.trim().startsWith("SECRET_BOUNDARY_")); - if (stdoutMarker === SECRET_BOUNDARY_REFUSED_MARKER) { + const output = `${result.stdout}\n${result.stderr}`; + if (result.status === 0 && result.stdout.includes("GATEWAY_PID=")) { + return { refused: false }; + } + if (output.includes("SECRET_BOUNDARY_REFUSED")) { printValidatorStderr(result.stderr); console.error(""); console.error( @@ -85,10 +80,7 @@ export function enforceHermesSecretBoundaryOnRunningGateway( ); return { refused: true, reason: "raw-secret", stderr: result.stderr }; } - if (stdoutMarker === SECRET_BOUNDARY_OK_MARKER) { - return { refused: false }; - } - if (stdoutMarker === SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER) { + if (output.includes("SECRET_BOUNDARY_VALIDATOR_MISSING")) { printValidatorStderr(result.stderr); console.error(""); console.error( diff --git a/src/lib/actions/sandbox/markerless-recovery.test.ts b/src/lib/actions/sandbox/markerless-recovery.test.ts deleted file mode 100644 index 0c0d2e5f5d3..00000000000 --- a/src/lib/actions/sandbox/markerless-recovery.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { describe, expect, it } from "vitest"; -import { - outputLooksLikeMarkerlessGatewayLaunch, - sandboxRecoveryAttemptFromExecResult, -} from "./markerless-recovery"; - -describe("markerless recovery output", () => { - it("treats launcher-started output as provisional recovery only", () => { - expect( - outputLooksLikeMarkerlessGatewayLaunch({ - status: 0, - stdout: "OpenClaw gateway launcher started without legacy recovery marker", - stderr: "", - }), - ).toBe(true); - }); - - it("ignores generic launcher output without gateway-specific wording", () => { - expect( - outputLooksLikeMarkerlessGatewayLaunch({ - status: 0, - stdout: "launcher started for debugging", - stderr: "", - }), - ).toBe(false); - }); - - it("rejects failed or unrelated output", () => { - expect( - outputLooksLikeMarkerlessGatewayLaunch({ - status: 0, - stdout: "RECOVERY_FAILED", - stderr: "gateway failed", - }), - ).toBe(false); - expect( - outputLooksLikeMarkerlessGatewayLaunch({ - status: 0, - stdout: "plain sandbox exec output", - stderr: "", - }), - ).toBe(false); - expect( - outputLooksLikeMarkerlessGatewayLaunch({ - status: 1, - stdout: "launcher started", - stderr: "", - }), - ).toBe(false); - }); - - it("keeps markerless recovery provisional until health is verified by the caller", () => { - expect( - sandboxRecoveryAttemptFromExecResult( - { - status: 0, - stdout: "OpenClaw gateway launcher started without legacy recovery marker", - stderr: "", - }, - false, - ), - ).toEqual({ recovered: false, mayHaveStarted: true }); - expect(sandboxRecoveryAttemptFromExecResult(null, false)).toBeNull(); - expect( - sandboxRecoveryAttemptFromExecResult( - { - status: 0, - stdout: "GATEWAY_PID=123", - stderr: "", - }, - true, - ), - ).toEqual({ recovered: true, mayHaveStarted: false }); - }); -}); diff --git a/src/lib/actions/sandbox/markerless-recovery.ts b/src/lib/actions/sandbox/markerless-recovery.ts deleted file mode 100644 index c39225fa215..00000000000 --- a/src/lib/actions/sandbox/markerless-recovery.ts +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -type MarkerlessSandboxCommandResult = { - status: number; - stdout: string; - stderr: string; -} | null; - -export type SandboxProcessRecoveryAttempt = { - recovered: boolean; - mayHaveStarted: boolean; -}; - -export function sandboxRecoveryAttempt( - recovered: boolean, - mayHaveStarted = false, -): SandboxProcessRecoveryAttempt { - return { recovered, mayHaveStarted }; -} - -export function outputLooksLikeMarkerlessGatewayLaunch( - result: MarkerlessSandboxCommandResult, -): boolean { - if (!result || result.status !== 0) return false; - const output = `${result.stdout}\n${result.stderr}`; - if (/RECOVERY_FAILED|GATEWAY_FAILED|OPENCLAW_MISSING|GATEWAY_STALE_PROCESSES/i.test(output)) { - return false; - } - // Source boundary: newer OpenShell sandbox exec/relaunch output can omit the - // legacy NemoClaw recovery markers even when the gateway launcher started. - // This text heuristic only marks "may have started"; recovery is not accepted - // until waitForRecoveredSandboxGateway() verifies a serving gateway. Require - // gateway/OpenClaw-specific wording so unrelated sandbox output like - // "launcher started for debugging" does not burn the health-probe timeout. - // Remove this shim when OpenShell exposes a stable machine-readable recovery - // marker for sandbox exec relaunch output. - return ( - /\b(gateway|openclaw)\b/i.test(output) && - /\b(gateway run|launcher|started|nohup)\b/i.test(output) - ); -} - -export function sandboxRecoveryAttemptFromExecResult( - result: MarkerlessSandboxCommandResult, - hasRecoveryMarker: boolean, -): SandboxProcessRecoveryAttempt | null { - if (hasRecoveryMarker) return sandboxRecoveryAttempt(true); - if (result === null) return null; - return sandboxRecoveryAttempt(false, outputLooksLikeMarkerlessGatewayLaunch(result)); -} diff --git a/src/lib/actions/sandbox/process-recovery-lock.test.ts b/src/lib/actions/sandbox/process-recovery-lock.test.ts new file mode 100644 index 00000000000..bd949435fc7 --- /dev/null +++ b/src/lib/actions/sandbox/process-recovery-lock.test.ts @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const PROCESS_RECOVERY_MODULE = "./process-recovery.js"; +const TIMER_BOUND_LOCK_MODULE = "../../shields/timer-bound-lock.js"; +const AGENT_RUNTIME_MODULE = "../../agent/runtime.js"; + +describe("gateway process recovery timer ownership", () => { + afterEach(() => { + vi.restoreAllMocks(); + delete require.cache[requireSource.resolve(PROCESS_RECOVERY_MODULE)]; + }); + + it("rechecks the timer generation after waiting and carries the current token", () => { + delete require.cache[requireSource.resolve(PROCESS_RECOVERY_MODULE)]; + const timerBound = requireSource( + TIMER_BOUND_LOCK_MODULE, + ) as typeof import("../../shields/timer-bound-lock"); + const actualWithTimerBoundLock = timerBound.withTimerBoundShieldsMutationLock; + const oldToken = "1".repeat(32); + const currentToken = "2".repeat(32); + const tokens = [oldToken, currentToken, currentToken, currentToken]; + const owners: unknown[] = []; + + vi.spyOn(timerBound, "withTimerBoundShieldsMutationLock").mockImplementation( + (sandboxName, command, callback) => + actualWithTimerBoundLock(sandboxName, command, callback, { + readToken: () => tokens.shift(), + withLock: (_name, _command, fn, options) => { + owners.push(options); + return fn(); + }, + withLockAsync: vi.fn(), + }), + ); + const agentRuntime = requireSource( + AGENT_RUNTIME_MODULE, + ) as typeof import("../../agent/runtime"); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + runtime: { kind: "terminal" }, + } as never); + + const recovery = requireSource(PROCESS_RECOVERY_MODULE) as typeof import("./process-recovery"); + expect(recovery.checkAndRecoverSandboxProcesses("terminal-box", { quiet: true })).toEqual({ + checked: true, + wasRunning: null, + recovered: false, + forwardRecovered: false, + runtime: "terminal", + }); + expect(owners).toEqual([{ takeoverToken: oldToken }, { takeoverToken: currentToken }]); + }); +}); diff --git a/src/lib/actions/sandbox/process-recovery.test.ts b/src/lib/actions/sandbox/process-recovery.test.ts index cbfe901000a..53d56d0b02d 100644 --- a/src/lib/actions/sandbox/process-recovery.test.ts +++ b/src/lib/actions/sandbox/process-recovery.test.ts @@ -1,14 +1,95 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -// Import from compiled dist for parity with the other CLI tests in this project. +// Import source directly so this test cannot pass against a stale build. import { + confirmRecoveredSandboxGatewayManaged, probeSandboxInferenceGatewayHealth, waitForRecoveredSandboxGateway, } from "./process-recovery"; +describe("confirmRecoveredSandboxGatewayManaged scope", () => { + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); + const openClawEntry = { + name: "my-sandbox", + agent: "openclaw", + openshellDriver: "docker", + }; + + it("accepts only an authenticated recovery marker for a built-in OpenClaw sandbox", () => { + requestGatewaySupervisorAction.mockClear(); + expect( + confirmRecoveredSandboxGatewayManaged("my-sandbox", { + getSandboxImpl: () => openClawEntry, + getSessionAgentImpl: () => null, + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + ).toBe(true); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("my-sandbox", "probe"); + }); + + it("does not control custom agents or non-direct OpenShell drivers", () => { + requestGatewaySupervisorAction.mockClear(); + expect( + confirmRecoveredSandboxGatewayManaged("my-sandbox", { + getSandboxImpl: () => ({ ...openClawEntry, agent: "custom-agent" }), + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + ).toBeNull(); + expect( + confirmRecoveredSandboxGatewayManaged("my-sandbox", { + getSandboxImpl: () => ({ ...openClawEntry, openshellDriver: "kubernetes" }), + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + ).toBeNull(); + expect(requestGatewaySupervisorAction).not.toHaveBeenCalled(); + }); + + it("does not treat an unloaded Hermes definition as OpenClaw", () => { + requestGatewaySupervisorAction.mockClear(); + expect( + confirmRecoveredSandboxGatewayManaged("hermes-box", { + getSandboxImpl: () => ({ ...openClawEntry, name: "hermes-box", agent: "hermes" }), + getSessionAgentImpl: () => null, + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + ).toBeNull(); + expect(requestGatewaySupervisorAction).not.toHaveBeenCalled(); + }); + + it("allows authenticated confirmation for a loaded built-in Hermes sandbox", () => { + requestGatewaySupervisorAction.mockClear(); + expect( + confirmRecoveredSandboxGatewayManaged("hermes-box", { + getSandboxImpl: () => ({ ...openClawEntry, name: "hermes-box", agent: "hermes" }), + getSessionAgentImpl: () => ({ name: "hermes", runtime: { kind: "gateway" } }) as never, + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + ).toBe(true); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "probe"); + }); + + it("rejects a marker from a failed controller action", () => { + expect( + confirmRecoveredSandboxGatewayManaged("my-sandbox", { + getSandboxImpl: () => openClawEntry, + getSessionAgentImpl: () => null, + requestGatewaySupervisorActionImpl: () => ({ + status: 1, + stdout: "GATEWAY_PID=4242\n", + stderr: "GATEWAY_FAILED", + }), + }), + ).toBe(false); + }); +}); + describe("probeSandboxInferenceGatewayHealth gateway-chain subprobe (#3265)", () => { const makeExec = (stdout: string, status = 0) => @@ -91,10 +172,95 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () expect(sleeps).toEqual([25]); }); + it("uses one authenticated managed probe after the settle window", () => { + const sleeps: number[] = []; + const managedProbe = vi.fn(() => true); + const ordinaryProbe = vi.fn(() => false); + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + initialManagedHealthPassed: true, + probeImpl: ordinaryProbe, + managedProbeImpl: managedProbe, + sleepImpl: (seconds: number) => sleeps.push(seconds), + }); + expect(ok).toBe(true); + expect(managedProbe).toHaveBeenCalledOnce(); + expect(ordinaryProbe).not.toHaveBeenCalled(); + expect(sleeps).toEqual([25]); + }); + + it("does not let ordinary outer-namespace health override a managed probe failure", () => { + const sleeps: number[] = []; + const managedProbe = vi.fn(() => false); + const ordinaryProbe = vi.fn(() => true); + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + initialManagedHealthPassed: true, + probeImpl: ordinaryProbe, + managedProbeImpl: managedProbe, + sleepImpl: (seconds: number) => sleeps.push(seconds), + }); + expect(ok).toBe(false); + expect(managedProbe).toHaveBeenCalledOnce(); + expect(ordinaryProbe).not.toHaveBeenCalled(); + expect(sleeps).toEqual([25]); + }); + + it("accepts the initial managed proof without another probe when settling is disabled", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + const managedProbe = vi.fn(() => false); + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + initialManagedHealthPassed: true, + probeImpl: () => false, + managedProbeImpl: managedProbe, + sleepImpl: () => {}, + }); + expect(ok).toBe(true); + expect(managedProbe).not.toHaveBeenCalled(); + }); + + it("uses the bounded recovery window for transient stopped probes", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; + const sleeps: number[] = []; + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + probeImpl: makeProbe([true, false, false, true]), + sleepImpl: (seconds: number) => sleeps.push(seconds), + }); + expect(ok).toBe(true); + expect(sleeps).toEqual([25, 3, 3]); + }); + + it("uses the bounded recovery window for inconclusive post-settle transport", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; + const sleeps: number[] = []; + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + probeImpl: makeProbe([true, null, null, true]), + sleepImpl: (seconds: number) => sleeps.push(seconds), + }); + expect(ok).toBe(true); + expect(sleeps).toEqual([25, 3, 3]); + }); + + it("fails closed when post-settle transport stays inconclusive for the bounded window", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; + const sleeps: number[] = []; + const ok = waitForRecoveredSandboxGateway("my-sandbox", { + probeImpl: makeProbe([true, null]), + sleepImpl: (seconds: number) => sleeps.push(seconds), + }); + expect(ok).toBe(false); + expect(sleeps).toEqual([25, 3, 3]); + }); + it("fails recovery when the gateway serves once and then drops its listener (wedge)", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; const sleeps: number[] = []; const ok = waitForRecoveredSandboxGateway("my-sandbox", { - probeImpl: makeProbe([true, false]), + initialManagedHealthPassed: true, + probeImpl: makeProbe([true]), + managedProbeImpl: () => false, sleepImpl: (seconds: number) => sleeps.push(seconds), }); expect(ok).toBe(false); @@ -135,4 +301,41 @@ describe("waitForRecoveredSandboxGateway settle-window confirmation (#4710)", () }); expect(ok).toBe(false); }); + + it("uses the manifest health timeout threaded by the recovery caller", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + let probes = 0; + + const ok = waitForRecoveredSandboxGateway("hermes-box", { + probeImpl: () => { + probes += 1; + return false; + }, + sleepImpl: () => {}, + timeoutSeconds: 90, + }); + + expect(ok).toBe(false); + expect(probes).toBe(31); + }); + + it("lets the recovery wait environment override take precedence over the manifest timeout", () => { + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "6"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "3"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + let probes = 0; + + const ok = waitForRecoveredSandboxGateway("hermes-box", { + probeImpl: () => { + probes += 1; + return false; + }, + sleepImpl: () => {}, + timeoutSeconds: 90, + }); + + expect(ok).toBe(false); + expect(probes).toBe(3); + }); }); diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 8af05be82ee..ace53afb8ef 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -2,50 +2,62 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; import { dockerSpawnSync } from "../../adapters/docker"; import { - captureOpenshell, captureOpenshellForStatus, captureSandboxSshConfig, getOpenshellBinary, isCommandTimeout, - runOpenshell, } from "../../adapters/openshell/runtime"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import * as agentRuntime from "../../agent/runtime"; import { G, R } from "../../cli/terminal-style"; -import { DASHBOARD_PORT } from "../../core/ports"; import { sleepSeconds, waitUntil } from "../../core/wait"; -import { getActiveMessagingHostForward } from "../../messaging/host-forward"; -import type { SandboxMessagingHostForwardPlan } from "../../messaging/manifest"; -import { hydrateDerivedSandboxMessagingPlanFields } from "../../messaging/persistence"; -import { parseSandboxMessagingPlan } from "../../messaging/plan-validation"; import { ROOT, shellQuote } from "../../runner"; +import { + isDirectSandboxFallbackUnavailableError, + privilegedSandboxExecArgv, +} from "../../sandbox/privileged-exec"; import { createTempSshConfig } from "../../sandbox/temp-ssh-config"; +import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; import * as registry from "../../state/registry"; -import { parseForwardList } from "../../state/sandbox-session"; -import { classifyForwardHealthWithReachability, isLocalForwardReachable } from "./forward-health"; -import { printGatewayWedgeDiagnostics } from "./gateway-wedge-diagnostics"; import { - ensureHermesDashboardPortForwardIfEnabled as ensureHermesDashboardPortForward, - getHermesDashboardRecoveryConfig, - recoverHermesDashboardProcessIfEnabled as recoverHermesDashboardProcess, -} from "./hermes-dashboard-recovery"; -import { enforceHermesSecretBoundaryOnRunningGateway } from "./hermes-secret-boundary-recovery"; + ensureHermesDashboardPortForwardIfEnabled, + ensureSandboxPortForward, + isSandboxForwardHealthy, + recoverDeclaredAgentForwardPorts, + recoverMessagingHostForward, + resolveSandboxDashboardPort, +} from "./forward-recovery"; import { - type SandboxProcessRecoveryAttempt, - sandboxRecoveryAttempt, - sandboxRecoveryAttemptFromExecResult, -} from "./markerless-recovery"; + classifyGatewayRestartFailure, + type GatewayRestartDeps, + type GatewayRestartResult, + printGatewayRestartFailure, + type RestartSandboxGatewayOptions, + restartSandboxGatewayWithDeps, + sandboxAgentName, +} from "./gateway-restart"; +import { printGatewayWedgeDiagnostics } from "./gateway-wedge-diagnostics"; +import { enforceHermesSecretBoundaryOnRunningGateway } from "./hermes-secret-boundary-recovery"; import { buildSandboxExecMarkedCommand, extractSandboxExecCommandStdout, } from "./sandbox-exec-output"; +export type { SandboxForwardHealth, SandboxForwardListEntry } from "./forward-health"; export { classifyForwardHealthWithReachability, classifySandboxForwardHealth, } from "./forward-health"; +export { resolveSandboxDashboardPort } from "./forward-recovery"; +export type { + GatewayRestartDeps, + GatewayRestartFailureLayer, + GatewayRestartResult, + RestartSandboxGatewayOptions, +} from "./gateway-restart"; export type SandboxCommandResult = { status: number; @@ -53,38 +65,28 @@ export type SandboxCommandResult = { stderr: string; }; -type SandboxPortAgent = { forwardPort?: unknown; runtime?: { kind?: unknown } } | null; - -type SandboxPortDeps = { - getSandbox?: typeof registry.getSandbox; - getSessionAgent?: (sandboxName?: string) => SandboxPortAgent; -}; +const DEFAULT_SANDBOX_EXEC_TIMEOUT_MS = 15000; -export type SandboxForwardListEntry = { - sandboxName: string; - port: string; - status: string; +type AuxiliaryRecoveryResult = { + label: string; + recovered: boolean | null; }; -export type SandboxForwardHealth = boolean | "occupied" | null; - -function isValidPort(value: unknown): value is number { - return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; +function auxiliaryRecoveryFailureDetail(results: AuxiliaryRecoveryResult[]): string | null { + const failed = results + .filter((result) => result.recovered === false) + .map((result) => result.label); + if (failed.length === 0) return null; + return `${failed.join(", ")} could not be re-established`; } -export function resolveSandboxDashboardPort( - sandboxName: string, - deps: SandboxPortDeps = {}, -): number { - const getSessionAgent = deps.getSessionAgent ?? agentRuntime.getSessionAgent; - const agent = getSessionAgent(sandboxName); - if (agent && agentRuntime.hasGatewayRuntime(agent) && isValidPort(agent.forwardPort)) { - return agent.forwardPort; - } +function anyAuxiliaryRecovered(results: AuxiliaryRecoveryResult[]): boolean { + return results.some((result) => result.recovered === true); +} - const getSandbox = deps.getSandbox ?? registry.getSandbox; - const sandbox = getSandbox(sandboxName); - return isValidPort(sandbox?.dashboardPort) ? sandbox.dashboardPort : DASHBOARD_PORT; +function resolveSandboxExecTimeout(timeout = DEFAULT_SANDBOX_EXEC_TIMEOUT_MS): number { + const timeoutOverride = Number(process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS || ""); + return Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; } function getSandboxHealthProbeUrl(sandboxName: string): string { @@ -155,35 +157,26 @@ function parseSandboxCommandResult( }; } -function findLocalDockerSandboxContainer(sandboxName: string): string | null { - const expectedName = `openshell-${sandboxName}`; - try { - const result = dockerSpawnSync(["ps", "--format", "{{.ID}}\t{{.Names}}"], { - encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], - timeout: 5000, - }); - if (result.error || result.status !== 0) return null; - for (const line of String(result.stdout || "").split(/\r?\n/)) { - const [id = "", names = ""] = line.split("\t"); - const containerNames = names.split(",").map((name) => name.trim()); - if (id && containerNames.includes(expectedName)) return id; - } - return null; - } catch { - return null; - } -} - function executeLocalDockerSandboxCommand( sandboxName: string, markedCommand: string, timeout: number, ): SandboxCommandResult | null { - const containerId = findLocalDockerSandboxContainer(sandboxName); - if (!containerId) return null; + let argv: string[]; try { - const result = dockerSpawnSync(["exec", "-u", "root", containerId, "sh", "-c", markedCommand], { + argv = privilegedSandboxExecArgv(sandboxName, ["sh", "-c", markedCommand]); + } catch (error) { + // Docker discovery failure or a stopped/nonexistent direct container means + // there is no local fallback. Identity refusals, unsupported drivers, + // registry corruption, and ambiguous matches are security-boundary + // diagnostics: let callers surface them instead of collapsing them into an + // inconclusive OpenShell transport result. + if (isDirectSandboxFallbackUnavailableError(error)) return null; + throw error; + } + + try { + const result = dockerSpawnSync(argv, { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], timeout, @@ -197,12 +190,10 @@ function executeLocalDockerSandboxCommand( export function executeSandboxExecCommand( sandboxName: string, command: string, - timeout = 15000, + timeout = DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, ): SandboxCommandResult | null { const markedCommand = buildSandboxExecMarkedCommand(command); - const timeoutOverride = Number(process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS || ""); - const effectiveTimeout = - Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; + const effectiveTimeout = resolveSandboxExecTimeout(timeout); try { const result = spawnSync( getOpenshellBinary(), @@ -215,13 +206,57 @@ export function executeSandboxExecCommand( timeout: effectiveTimeout, }, ); - return ( - parseSandboxCommandResult(result) ?? - executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout) - ); + const parsed = parseSandboxCommandResult(result); + if (parsed !== null) return parsed; } catch { - return executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout); + // OpenShell transport failed; try the trusted direct-container fallback. + } + // Keep the fallback outside the OpenShell try/catch so a fail-closed identity + // refusal cannot be caught and retried against changing container state. + return executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout); +} + +export function executeGatewaySupervisorAction( + sandboxName: string, + action: "restart" | "recover" | "probe", + timeout = 210000, +): SandboxCommandResult | null { + const nonce = randomBytes(32).toString("hex"); + let argv: string[]; + try { + argv = privilegedSandboxExecArgv( + sandboxName, + ["/usr/local/bin/nemoclaw-gateway-control", action, nonce], + false, + true, + ); + } catch (error) { + const detail = error instanceof Error ? error.message : "privileged container unavailable"; + return { + status: 1, + stdout: "", + stderr: `PRIVILEGED_CONTROL_UNAVAILABLE: ${detail}`, + }; + } + + const result = dockerSpawnSync(argv, { + cwd: ROOT, + encoding: "utf-8", + env: process.env, + stdio: ["ignore", "pipe", "pipe"], + timeout, + }); + if (result.error) return null; + const status = result.status ?? 1; + const stdout = String(result.stdout || "").trim(); + let stderr = String(result.stderr || "").trim(); + if ( + (status === 126 || status === 127) && + /(?:not found|no such file|executable file)/i.test(`${stdout}\n${stderr}`) + ) { + stderr = ["SUPERVISOR_REBUILD_REQUIRED", stderr].filter(Boolean).join("\n"); } + return { status, stdout, stderr }; } async function executeSandboxExecCommandForStatus( @@ -268,9 +303,65 @@ function isSandboxGatewayRunning(sandboxName: string): boolean | null { const command = `HTTP_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 ${shellQuote(probeUrl)} 2>/dev/null || echo 000); case "$HTTP_CODE" in 200|401) echo RUNNING ;; *) echo STOPPED ;; esac`; const execProbe = parseSandboxGatewayProbe(executeSandboxExecCommand(sandboxName, command)); if (execProbe !== null) return execProbe; + + // Built-in OpenClaw and Hermes lifecycle control is host-mediated through + // the controller for the live topology. If the trusted sandbox-exec path is + // unavailable or times out, do not silently cross back into the sandbox over + // SSH just to classify the gateway and then make a privileged recovery + // decision. Legacy custom gateway agents are the sole compatibility case: + // their recovery contract is explicitly SSH-owned until manifests can + // declare a trusted runtime user/supervisor. + if (!agent || agent.name === "openclaw" || agent.name === "hermes") return null; return parseSandboxGatewayProbe(executeSandboxCommand(sandboxName, command)); } +function hasGatewayRecoveryMarker(result: SandboxCommandResult | null): boolean { + return !!( + result && + result.status === 0 && + (result.stdout.includes("GATEWAY_PID=") || result.stdout.includes("ALREADY_RUNNING")) + ); +} + +function isExactlyRetryableManagedRecoveryFailure(result: SandboxCommandResult | null): boolean { + if (result === null) return false; + if (result.status !== 1) return false; + if (result.stdout.trim() !== "") return false; + const lines = result.stderr + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + return lines.length === 1 && ["SUPERVISOR_UNAVAILABLE", "SUPERVISOR_BUSY"].includes(lines[0]); +} + +export function confirmRecoveredSandboxGatewayManaged( + sandboxName: string, + options: { + getSandboxImpl?: typeof registry.getSandbox; + getSessionAgentImpl?: typeof agentRuntime.getSessionAgent; + requestGatewaySupervisorActionImpl?: typeof executeGatewaySupervisorAction; + } = {}, +): boolean | null { + const getSandbox = options.getSandboxImpl ?? registry.getSandbox; + const entry = getSandbox(sandboxName); + if (!entry) return null; + const persistedAgent = entry.agent ?? "openclaw"; + if (persistedAgent !== "openclaw" && persistedAgent !== "hermes") return null; + + const driver = entry.openshellDriver?.trim().toLowerCase() ?? null; + if (driver !== null && driver !== "docker" && driver !== "vm") return null; + + const getSessionAgent = options.getSessionAgentImpl ?? agentRuntime.getSessionAgent; + const agent = getSessionAgent(sandboxName); + if (persistedAgent === "hermes" && agent?.name !== "hermes") return null; + if (agent && !agentRuntime.hasGatewayRuntime(agent)) return null; + const requestGatewaySupervisorAction = + options.requestGatewaySupervisorActionImpl ?? executeGatewaySupervisorAction; + const result = requestGatewaySupervisorAction(sandboxName, "probe"); + if (hasGatewayRecoveryMarker(result)) return true; + return result === null ? null : false; +} + export async function isSandboxGatewayRunningForStatus( sandboxName: string, ): Promise { @@ -330,59 +421,121 @@ export async function probeSandboxInferenceGatewayHealth( * Cleans stale lock/temp files, sources proxy config, and launches the gateway * in the background. Returns true on success. */ -function recoverSandboxProcesses(sandboxName: string): SandboxProcessRecoveryAttempt { +function recoverSandboxProcesses( + sandboxName: string, + { + quiet = false, + requestGatewaySupervisorAction = executeGatewaySupervisorAction, + }: { + quiet?: boolean; + requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; + } = {}, +): "managed" | "custom" | null { const agent = agentRuntime.getSessionAgent(sandboxName); const dashboardPort = resolveSandboxDashboardPort(sandboxName); - const agentScript = agentRuntime.buildRecoveryScript(agent, dashboardPort, { - hermesDashboard: getHermesDashboardRecoveryConfig(sandboxName), - }); - const hasRecoveryMarker = (result: SandboxCommandResult | null) => - !!( - result && - (result.stdout.includes("GATEWAY_PID=") || result.stdout.includes("ALREADY_RUNNING")) - ); + let persistedAgent: string | null; + try { + persistedAgent = sandboxAgentName(sandboxName, registry.getSandbox); + } catch (error) { + const detail = + error instanceof Error && error.message.trim() + ? `Sandbox agent lookup failed: ${error.message}.` + : "Sandbox agent lookup failed."; + quiet || printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return null; + } const recoveredSsh = (result: SandboxCommandResult | null) => - !!(result && result.status === 0 && hasRecoveryMarker(result)); + !!(result && result.status === 0 && hasGatewayRecoveryMarker(result)); + const recoverManagedGateway = (): boolean => { + const maxAttempts = 3; + const retryIntervalSeconds = readNonNegativeNumberEnv( + "NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", + 3, + ); + let execResult: SandboxCommandResult | null = null; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + execResult = requestGatewaySupervisorAction(sandboxName, "recover"); + if (hasGatewayRecoveryMarker(execResult)) return true; + + // PID 1 may replace the gateway between the host's stopped observation + // and the controller's process-tree capture. Retry only exact transient + // controller results; integrity/config/launch refusals are terminal. + if (!isExactlyRetryableManagedRecoveryFailure(execResult) || attempt === maxAttempts) break; + sleepSeconds(retryIntervalSeconds); + } + const failure = classifyGatewayRestartFailure(execResult); + if (!quiet) printGatewayRestartFailure(sandboxName, failure.layer, failure.detail); + return false; + }; + if (persistedAgent === "hermes") { + if (!isHermesAgent(agent)) { + const detail = "Hermes agent definition could not be loaded."; + if (!quiet) printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return null; + } + return recoverManagedGateway() ? "managed" : null; + } - if (agentRuntime.isTerminalAgentRecoveryScript(agentScript)) return sandboxRecoveryAttempt(false); - if (agentScript) { - // Non-OpenClaw manifests do not yet declare a runtime user for root - // sandbox exec. Recover them over SSH so the launch inherits the sandbox - // login user instead of creating root-owned agent state under /sandbox. - return sandboxRecoveryAttempt(recoveredSsh(executeSandboxCommand(sandboxName, agentScript))); + // A persisted non-OpenClaw runtime whose manifest cannot be loaded is not + // evidence that the sandbox is OpenClaw. Falling through here would run the + // OpenClaw recovery script against an unknown custom or terminal runtime. + // Keep legacy registry entries with no agent name on the OpenClaw fallback, + // but fail closed for an explicit non-OpenClaw agent. + if (persistedAgent && persistedAgent !== "openclaw" && !agent) { + const detail = `${persistedAgent} agent definition could not be loaded.`; + if (!quiet) printGatewayRestartFailure(sandboxName, "unsupported agent", detail); + return null; } - const script = agentRuntime.buildOpenClawRecoveryScript(dashboardPort); - const execResult = executeSandboxExecCommand(sandboxName, script, 30000); - const execAttempt = sandboxRecoveryAttemptFromExecResult( - execResult, - hasRecoveryMarker(execResult), - ); - if (execAttempt) return execAttempt; - return sandboxRecoveryAttempt(recoveredSsh(executeSandboxCommand(sandboxName, script))); -} + if ((!persistedAgent || persistedAgent === "openclaw") && (!agent || agent.name === "openclaw")) { + return recoverManagedGateway() ? "managed" : null; + } -function recoverDeclaredAgentForwardPorts( - sandboxName: string, - recoveryPort: number, - { quiet }: { quiet: boolean }, -): boolean | null { - const recovered = ensureDeclaredAgentForwardPortsHealthy(sandboxName, recoveryPort); - if (!quiet && recovered === false) { - console.error(" One or more agent-declared port forwards could not be re-established."); + const agentScript = agentRuntime.buildRecoveryScript(agent, dashboardPort); + if (agentRuntime.isTerminalAgentRecoveryScript(agentScript)) return null; + if (agentScript) { + // Non-Hermes custom manifests do not yet declare a supported host-side + // runtime user. Recover them over SSH so the launch inherits the sandbox + // login user instead of creating root-owned agent state under /sandbox. + return recoveredSsh(executeSandboxCommand(sandboxName, agentScript)) ? "custom" : null; } - return recovered; + + return null; } -function recoverMessagingHostForward( +export function restartSandboxGateway( sandboxName: string, - { quiet }: { quiet: boolean }, -): boolean | null { - const recovered = ensureMessagingHostForwardHealthy(sandboxName); - if (!quiet && recovered === false) { - console.error(" Messaging webhook port forward could not be re-established."); - } - return recovered; + { quiet = false, deps = {} }: RestartSandboxGatewayOptions = {}, +): GatewayRestartResult { + return withTimerBoundShieldsMutationLock(sandboxName, "gateway restart", () => + restartSandboxGatewayWithDeps(sandboxName, { + quiet, + deps: { + getSessionAgent: agentRuntime.getSessionAgent, + getSandbox: registry.getSandbox, + resolveSandboxDashboardPort, + requestGatewaySupervisorAction: executeGatewaySupervisorAction, + executeSandboxExecCommand, + waitForRecoveredSandboxGateway: (name, options) => + waitForRecoveredSandboxGateway(name, { + ...options, + initialManagedHealthPassed: true, + timeoutSeconds: gatewayRecoveryTimeoutSeconds(agentRuntime.getSessionAgent(name)), + managedProbeImpl: (sandboxName) => + confirmRecoveredSandboxGatewayManaged(sandboxName, { + requestGatewaySupervisorActionImpl: + deps.requestGatewaySupervisorAction ?? executeGatewaySupervisorAction, + }), + }), + ensureSandboxPortForward, + ensureHermesDashboardPortForwardIfEnabled, + recoverMessagingHostForward, + recoverDeclaredAgentForwardPorts, + printGatewayWedgeDiagnostics, + ...deps, + }, + }), + ); } function readNonNegativeNumberEnv(name: string, fallback: number): number { @@ -392,17 +545,82 @@ function readNonNegativeNumberEnv(name: string, fallback: number): number { return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; } +function gatewayRecoveryTimeoutSeconds( + agent: ReturnType, +): number { + const timeoutSeconds = agent?.healthProbe?.timeout_seconds; + return typeof timeoutSeconds === "number" && + Number.isFinite(timeoutSeconds) && + timeoutSeconds >= 0 + ? timeoutSeconds + : 30; +} + +function printHostManagedGatewayRecoveryHints( + sandboxName: string, + agent: ReturnType, +): void { + const quotedSandboxName = shellQuote(sandboxName); + let agentName = agent?.name ?? null; + if (!agentName) { + try { + agentName = registry.getSandbox(sandboxName)?.agent ?? null; + } catch { + // Preserve the legacy OpenClaw hint when registry lookup itself failed. + } + } + if (!agentName || agentName === "openclaw" || agentName === "hermes") { + console.error(" Retry the managed restart from the host:"); + console.error(` nemoclaw ${quotedSandboxName} gateway restart`); + } else { + console.error(" This custom agent does not support the managed gateway restart command."); + console.error(" After addressing its gateway log, retry agent-aware recovery from the host:"); + console.error(` nemoclaw ${quotedSandboxName} recover`); + } + console.error(" If the sandbox image is incompatible or restart still fails, rebuild it:"); + console.error(` nemoclaw ${quotedSandboxName} rebuild --yes`); +} + +function recoveryAgentDisplayName( + sandboxName: string, + agent: ReturnType, +): string { + if (agent) return agentRuntime.getAgentDisplayName(agent); + try { + const persistedAgent = registry.getSandbox(sandboxName)?.agent; + if (persistedAgent && persistedAgent !== "openclaw") return persistedAgent; + } catch { + // The recovery path below reports registry lookup failures with the + // structured unsupported-agent diagnostic. + } + return agentRuntime.getAgentDisplayName(null); +} + export function waitForRecoveredSandboxGateway( sandboxName: string, options: { + managedProbeImpl?: (sandboxName: string) => boolean | null; + initialManagedHealthPassed?: boolean; probeImpl?: (sandboxName: string) => boolean | null; sleepImpl?: (seconds: number) => void; quiet?: boolean; + timeoutSeconds?: number; } = {}, ): boolean { const probe = options.probeImpl ?? isSandboxGatewayRunning; + const managedProbe = + options.managedProbeImpl ?? (options.probeImpl ? null : confirmRecoveredSandboxGatewayManaged); const sleep = options.sleepImpl ?? sleepSeconds; - const timeoutSeconds = readNonNegativeNumberEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", 30); + const requestedTimeoutSeconds = + typeof options.timeoutSeconds === "number" && + Number.isFinite(options.timeoutSeconds) && + options.timeoutSeconds >= 0 + ? options.timeoutSeconds + : 30; + const timeoutSeconds = readNonNegativeNumberEnv( + "NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", + requestedTimeoutSeconds, + ); const intervalSeconds = readNonNegativeNumberEnv( "NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", 3, @@ -412,13 +630,27 @@ export function waitForRecoveredSandboxGateway( ? Math.max(1, Math.floor(timeoutSeconds / intervalSeconds) + 1) : Math.max(1, Math.floor(timeoutSeconds) + 1); - const recovered = waitUntil(() => probe(sandboxName) === true, { - initialIntervalMs: intervalSeconds * 1000, - maxIntervalMs: intervalSeconds * 1000, - backoffFactor: 1, - maxAttempts: attempts, - sleep: (ms) => sleep(ms / 1000), - }); + const probeDuringRecoveryWait = () => { + const managedResult = managedProbe?.(sandboxName) ?? null; + if (managedResult !== null) return managedResult; + return probe(sandboxName); + }; + + // A successful managed restart/recover marker is already emitted only after + // the controller proves the exact child, listener, HTTP health, and declared + // auxiliaries from inside the gateway network namespace. Trust that as the + // initial observation; the settle check below still independently re-proves + // health and catches a delayed #4710 wedge. + const initialManagedHealthPassed = options.initialManagedHealthPassed === true; + const recovered = + initialManagedHealthPassed || + waitUntil(() => probeDuringRecoveryWait() === true, { + initialIntervalMs: intervalSeconds * 1000, + maxIntervalMs: intervalSeconds * 1000, + backoffFactor: 1, + maxAttempts: attempts, + sleep: (ms) => sleep(ms / 1000), + }); if (!recovered) return false; // #4710: a freshly relaunched gateway can serve for ~20s and then drop @@ -437,155 +669,31 @@ export function waitForRecoveredSandboxGateway( console.log(` Confirming the gateway stays responsive (~${settleSeconds}s)...`); } sleep(settleSeconds); - return probe(sandboxName) === true; -} - -/** - * Re-establish the dashboard port forward to the sandbox. - * Uses the recorded dashboard port for OpenClaw sandboxes, or the agent's - * declared forward port when a non-OpenClaw agent is active. - * Returns true when `forward start` succeeded and a follow-up probe - * confirms the new entry is running, false otherwise. - */ -function ensureSandboxPortForward(sandboxName: string): boolean { - return ensureSandboxPortForwardForPort(sandboxName, resolveSandboxDashboardPort(sandboxName)); -} - -/** - * Probe `openshell forward list` for the sandbox's dashboard forward. - * Returns true when an entry exists for the expected sandbox+port pair - * with STATUS=running, false when the entry is missing or non-running, - * "occupied" when another sandbox already owns the expected port, and - * null when openshell is unreachable. - * - * The in-sandbox gateway and the host-side forward are independent - * dimensions: the forward can die (host SSH session dropped, list shows - * STATUS=dead) while the gateway keeps listening on 127.0.0.1:. - * - * Also falls back to a local TCP/HTTP probe of 127.0.0.1: when - * `forward list` would classify the entry as not-running. openshell's - * STATUS column lags real state — it can show "dead" for an entry that - * is still serving traffic, or hide an entry whose SSH session was just - * recycled (#3334). Trusting the column verbatim made every `connect` - * print a "missing or dead" preamble followed by a "Failed to - * re-establish" line even though the forward worked. - */ -function isSandboxForwardHealthy(sandboxName: string): SandboxForwardHealth { - return isSandboxPortForwardHealthy(sandboxName, resolveSandboxDashboardPort(sandboxName)); -} - -function isSandboxPortForwardHealthy(sandboxName: string, port: number): SandboxForwardHealth { - const result = captureOpenshell(["forward", "list"], { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (!result || isCommandTimeout(result) || result.status !== 0) return null; - const entries = parseForwardList(result.output) as SandboxForwardListEntry[]; - return classifyForwardHealthWithReachability(entries, sandboxName, String(port), () => - isLocalForwardReachable(port), - ); -} - -function ensureSandboxPortForwardForPort(sandboxName: string, port: number): boolean { - const forwardHealth = isSandboxPortForwardHealthy(sandboxName, port); - if (forwardHealth === true) return true; - if (forwardHealth === "occupied") return false; - - runOpenshell(["forward", "stop", String(port), sandboxName], { - ignoreError: true, - stdio: "ignore", - }); - const startResult = runOpenshell( - ["forward", "start", "--background", String(port), sandboxName], - { - ignoreError: true, - }, - ); - if (startResult.status !== 0) return false; - return isSandboxPortForwardHealthy(sandboxName, port) === true; -} - -function ensureHermesDashboardPortForwardIfEnabled(sandboxName: string): boolean | null { - return ensureHermesDashboardPortForward(sandboxName, { - isPortForwardHealthy: isSandboxPortForwardHealthy, - ensurePortForward: ensureSandboxPortForwardForPort, - }); -} - -function getSandboxMessagingHostForward( - sandboxName: string, -): SandboxMessagingHostForwardPlan | null { - const entry = registry.getSandbox(sandboxName); - const parsed = parseSandboxMessagingPlan(entry?.messaging?.plan, { sandboxName }); - const plan = parsed ? hydrateDerivedSandboxMessagingPlanFields(parsed) : null; - return getActiveMessagingHostForward(plan); -} - -function ensureMessagingHostForwardHealthy(sandboxName: string): boolean | null { - const forward = getSandboxMessagingHostForward(sandboxName); - if (!forward) return null; - const health = isSandboxPortForwardHealthy(sandboxName, forward.port); - if (health === true) return true; - if (health === "occupied") return false; - return ensureSandboxPortForwardForPort(sandboxName, forward.port); -} - -/** - * Re-establish every declared `forward_ports` entry on the active agent - * manifest that is not already owned by another recovery helper. The - * primary dashboard port is owned by `ensureSandboxPortForward`; the - * optional Hermes web dashboard port (a registry-recorded per-sandbox - * override that the manifest cannot statically declare) is owned by - * `ensureHermesDashboardPortForwardIfEnabled`. Skipping both here keeps - * the helpers orthogonal and avoids issuing duplicate `forward start` - * calls when an operator pins the Hermes dashboard to one of the - * manifest-declared ports. - * - * Without this helper, any remaining manifest-declared port (e.g. - * Hermes' OpenAI-compatible API on 8642) would be silently dropped after - * a gateway restart and never re-established by the recovery flow. - * - * Returns true when every covered declared port is healthy (probed or - * re-established), false when at least one declared port could not be - * re-established, and `null` when there is no active agent or no - * declared port left to manage after the skip set is applied. - */ -function ensureDeclaredAgentForwardPortsHealthy( - sandboxName: string, - primaryPort: number, -): boolean | null { - const agent = agentRuntime.getSessionAgent(sandboxName); - if (!agent) return null; - const declared = (agent as { forward_ports?: unknown }).forward_ports; - if (!Array.isArray(declared) || declared.length === 0) return null; - const hermesDashboard = getHermesDashboardRecoveryConfig(sandboxName); - const skipSet = new Set([primaryPort]); - if (hermesDashboard && Number.isInteger(hermesDashboard.publicPort)) { - skipSet.add(hermesDashboard.publicPort); - } - let sawCovered = false; - let allHealthy = true; - for (const candidate of declared) { - if (typeof candidate !== "number") continue; - if (!Number.isInteger(candidate) || candidate < 1 || candidate > 65535) continue; - if (skipSet.has(candidate)) continue; - sawCovered = true; - const health = isSandboxPortForwardHealthy(sandboxName, candidate); - if (health === true) continue; - if (health === "occupied") { - allHealthy = false; - continue; - } - if (!ensureSandboxPortForwardForPort(sandboxName, candidate)) { - allHealthy = false; - } + if (initialManagedHealthPassed) { + // The managed probe is a read-only, authenticated point check in the exact + // gateway network namespace. Its typed failure is authoritative: never let + // an outer-namespace HTTP response override it or extend this settle check + // beyond the controller's single bounded probe. + return managedProbe?.(sandboxName) === true; } - if (!sawCovered) return null; - return allHealthy; + // A stopped HTTP probe is still only a point-in-time observation. PID 1 can + // have respawned the gateway while OpenClaw is still finishing its startup + // transition, so multiple stopped results may precede a healthy listener. + // Give stopped and inconclusive probes the same bounded recovery window. + // A persistent #4710 wedge still fails closed when that window expires. + return waitUntil(() => probeDuringRecoveryWait() === true, { + initialIntervalMs: intervalSeconds * 1000, + maxIntervalMs: intervalSeconds * 1000, + backoffFactor: 1, + maxAttempts: attempts, + sleep: (ms) => sleep(ms / 1000), + }); } -function recoverHermesDashboardProcessIfEnabled(sandboxName: string): boolean | null { - return recoverHermesDashboardProcess(sandboxName, { executeCommand: executeSandboxCommand }); +function isHermesAgent( + agent: ReturnType, +): agent is NonNullable> & { name: "hermes" } { + return !!agent && agent.name === "hermes"; } /** @@ -593,13 +701,20 @@ function recoverHermesDashboardProcessIfEnabled(sandboxName: string): boolean | * whose OpenClaw processes are not running. Also re-establishes the * host-side dashboard port-forward when it has gone dead independently * of the gateway. Returns an object describing the outcome: - * `{ checked, wasRunning, recovered, forwardRecovered, secretBoundaryRefused?, secretBoundaryReason? }`. + * `{ checked, wasRunning, recovered, forwardRecovered, forwardRecoveryFailed?, secretBoundaryRefused?, secretBoundaryReason? }`. */ -export function checkAndRecoverSandboxProcesses( +function checkAndRecoverSandboxProcessesWithoutHostLock( sandboxName: string, - { quiet = false }: { quiet?: boolean } = {}, + { + quiet = false, + requestGatewaySupervisorAction = executeGatewaySupervisorAction, + }: { + quiet?: boolean; + requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; + } = {}, ) { const recoveryAgent = agentRuntime.getSessionAgent(sandboxName); + const recoveryDisplayName = recoveryAgentDisplayName(sandboxName, recoveryAgent); if (recoveryAgent && !agentRuntime.hasGatewayRuntime(recoveryAgent)) { return { checked: true, @@ -618,7 +733,7 @@ export function checkAndRecoverSandboxProcesses( const enforcement = enforceHermesSecretBoundaryOnRunningGateway( sandboxName, recoveryAgent, - executeSandboxExecCommand, + requestGatewaySupervisorAction, ); if (enforcement?.refused) { return { @@ -635,7 +750,6 @@ export function checkAndRecoverSandboxProcesses( // Gateway is alive but the host-side forward can still be dead or // owned by another sandbox. Probe and re-establish only when // necessary so the live-and-healthy path stays a no-op. - const dashboardProcessRecovered = recoverHermesDashboardProcessIfEnabled(sandboxName); const forwardHealthy = isSandboxForwardHealthy(sandboxName); if (forwardHealthy === false) { if (!quiet) { @@ -653,26 +767,52 @@ export function checkAndRecoverSandboxProcesses( quiet, }, ); + const auxiliaryResults = [ + { label: "the Hermes dashboard host forward", recovered: dashboardForwardRecovered }, + { label: "the messaging webhook host forward", recovered: messagingForwardRecovered }, + { + label: "one or more agent-declared host forwards", + recovered: declaredForwardsRecovered, + }, + ]; + const auxiliaryFailureDetail = auxiliaryRecoveryFailureDetail(auxiliaryResults); if (!quiet) { if (forwardRecovered) { console.log(` ${G}✓${R} Dashboard port forward re-established.`); } else { console.error(" Failed to re-establish the dashboard port forward."); console.error( - ` Run \`openshell forward start --background ${sandboxName}\` manually.`, + ` Run \`openshell forward start --background ${recoveryPort} ${sandboxName}\` manually.`, ); } } + if (!forwardRecovered) { + return { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the primary dashboard/API host forward could not be re-established", + }; + } + if (auxiliaryFailureDetail !== null) { + if (!quiet) console.error(` ${auxiliaryFailureDetail}.`); + return { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: auxiliaryFailureDetail, + }; + } return { checked: true, wasRunning: true, recovered: false, - forwardRecovered: - forwardRecovered || - dashboardForwardRecovered === true || - dashboardProcessRecovered === true || - messagingForwardRecovered === true || - declaredForwardsRecovered === true, + forwardRecovered: forwardRecovered || anyAuxiliaryRecovered(auxiliaryResults), }; } if (forwardHealthy === "occupied") { @@ -681,22 +821,43 @@ export function checkAndRecoverSandboxProcesses( console.error(` Dashboard port forward for '${sandboxName}' is owned by another sandbox.`); console.error(" Leaving the existing port forward unchanged."); } - return { checked: true, wasRunning: true, recovered: false, forwardRecovered: false }; + return { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the primary dashboard/API host forward is owned by another sandbox", + }; } const dashboardForwardRecovered = ensureHermesDashboardPortForwardIfEnabled(sandboxName); const messagingForwardRecovered = recoverMessagingHostForward(sandboxName, { quiet }); const declaredForwardsRecovered = recoverDeclaredAgentForwardPorts(sandboxName, recoveryPort, { quiet, }); + const auxiliaryResults = [ + { label: "the Hermes dashboard host forward", recovered: dashboardForwardRecovered }, + { label: "the messaging webhook host forward", recovered: messagingForwardRecovered }, + { label: "one or more agent-declared host forwards", recovered: declaredForwardsRecovered }, + ]; + const auxiliaryFailureDetail = auxiliaryRecoveryFailureDetail(auxiliaryResults); + if (auxiliaryFailureDetail !== null) { + if (!quiet) console.error(` ${auxiliaryFailureDetail}.`); + return { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: auxiliaryFailureDetail, + }; + } return { checked: true, wasRunning: true, recovered: false, - forwardRecovered: - dashboardForwardRecovered === true || - dashboardProcessRecovered === true || - messagingForwardRecovered === true || - declaredForwardsRecovered === true, + forwardRecovered: anyAuxiliaryRecovered(auxiliaryResults), }; } @@ -704,89 +865,105 @@ export function checkAndRecoverSandboxProcesses( if (!quiet) { console.log(""); console.log( - ` ${agentRuntime.getAgentDisplayName(recoveryAgent)} gateway is not running inside the sandbox (sandbox likely restarted).`, + ` ${recoveryDisplayName} gateway is not running inside the sandbox (sandbox likely restarted).`, ); console.log(" Recovering..."); } - const recoveryAttempt = recoverSandboxProcesses(sandboxName); - let recovered = recoveryAttempt.recovered; - let recoveredHealthVerified = false; - if ( - !recovered && - recoveryAttempt.mayHaveStarted && - waitForRecoveredSandboxGateway(sandboxName, { quiet }) - ) { - recovered = true; - recoveredHealthVerified = true; - } - if (recovered) { + const recoveryKind = recoverSandboxProcesses(sandboxName, { + quiet, + requestGatewaySupervisorAction, + }); + if (recoveryKind !== null) { // Wait for gateway to bind its HTTP port before declaring success. The // recovered process can be alive before the OpenAI-compatible API is ready. - if (!recoveredHealthVerified && !waitForRecoveredSandboxGateway(sandboxName, { quiet })) { + if ( + !waitForRecoveredSandboxGateway(sandboxName, { + quiet, + initialManagedHealthPassed: recoveryKind === "managed", + timeoutSeconds: gatewayRecoveryTimeoutSeconds(recoveryAgent), + managedProbeImpl: (name) => + confirmRecoveredSandboxGatewayManaged(name, { + requestGatewaySupervisorActionImpl: requestGatewaySupervisorAction, + }), + }) + ) { if (!quiet) { console.error(" Gateway process started but is not responding."); printGatewayWedgeDiagnostics(sandboxName, executeSandboxExecCommand); console.error(" Check /tmp/gateway.log inside the sandbox for details."); - console.error(" Connect to the sandbox and run manually:"); - console.error( - ` ${agentRuntime.buildManualRecoveryCommand(recoveryAgent, recoveryPort)}`, - ); + printHostManagedGatewayRecoveryHints(sandboxName, recoveryAgent); } return { checked: true, wasRunning: false, recovered: false, forwardRecovered: false }; } - const enforcement = enforceHermesSecretBoundaryOnRunningGateway( - sandboxName, - recoveryAgent, - executeSandboxExecCommand, - ); - if (enforcement?.refused) { - return { - checked: true, - wasRunning: false, - recovered: false, - forwardRecovered: false, - secretBoundaryRefused: true, - secretBoundaryReason: enforcement.reason, - }; - } const forwardRecovered = ensureSandboxPortForward(sandboxName); const dashboardForwardRecovered = ensureHermesDashboardPortForwardIfEnabled(sandboxName); const messagingForwardRecovered = recoverMessagingHostForward(sandboxName, { quiet }); const declaredForwardsRecovered = recoverDeclaredAgentForwardPorts(sandboxName, recoveryPort, { quiet, }); + const auxiliaryResults = [ + { label: "the Hermes dashboard host forward", recovered: dashboardForwardRecovered }, + { label: "the messaging webhook host forward", recovered: messagingForwardRecovered }, + { label: "one or more agent-declared host forwards", recovered: declaredForwardsRecovered }, + ]; + const auxiliaryFailureDetail = auxiliaryRecoveryFailureDetail(auxiliaryResults); if (!quiet) { - console.log( - ` ${G}✓${R} ${agentRuntime.getAgentDisplayName(recoveryAgent)} gateway restarted inside sandbox.`, - ); + console.log(` ${G}✓${R} ${recoveryDisplayName} gateway restarted inside sandbox.`); if (forwardRecovered) { console.log(` ${G}✓${R} Dashboard port forward re-established.`); } else { console.error(" Failed to re-establish the dashboard port forward."); console.error( - ` Run \`openshell forward start --background ${sandboxName}\` manually.`, + ` Run \`openshell forward start --background ${recoveryPort} ${sandboxName}\` manually.`, ); } } + if (!forwardRecovered) { + return { + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the primary dashboard/API host forward could not be re-established", + }; + } + if (auxiliaryFailureDetail !== null) { + if (!quiet) console.error(` ${auxiliaryFailureDetail}.`); + return { + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: auxiliaryFailureDetail, + }; + } return { checked: true, wasRunning: false, - recovered, - forwardRecovered: - forwardRecovered || - dashboardForwardRecovered === true || - messagingForwardRecovered === true || - declaredForwardsRecovered === true, + recovered: true, + forwardRecovered: forwardRecovered || anyAuxiliaryRecovered(auxiliaryResults), }; } if (!quiet) { - console.error( - ` Could not restart ${agentRuntime.getAgentDisplayName(recoveryAgent)} gateway automatically.`, - ); - console.error(" Connect to the sandbox and run manually:"); - console.error(` ${agentRuntime.buildManualRecoveryCommand(recoveryAgent, recoveryPort)}`); + console.error(` Could not restart ${recoveryDisplayName} gateway automatically.`); + printHostManagedGatewayRecoveryHints(sandboxName, recoveryAgent); } - return { checked: true, wasRunning: false, recovered, forwardRecovered: false }; + return { checked: true, wasRunning: false, recovered: false, forwardRecovered: false }; +} + +export function checkAndRecoverSandboxProcesses( + sandboxName: string, + options: { + quiet?: boolean; + requestGatewaySupervisorAction?: typeof executeGatewaySupervisorAction; + } = {}, +) { + return withTimerBoundShieldsMutationLock(sandboxName, "gateway process recovery", () => + checkAndRecoverSandboxProcessesWithoutHostLock(sandboxName, options), + ); } diff --git a/src/lib/actions/sandbox/rebuild-shields.ts b/src/lib/actions/sandbox/rebuild-shields.ts index c370edc7394..5a371fc39b3 100644 --- a/src/lib/actions/sandbox/rebuild-shields.ts +++ b/src/lib/actions/sandbox/rebuild-shields.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { G, R, RD as _RD, YW } from "../../cli/terminal-style"; +import { RD as _RD, G, R, YW } from "../../cli/terminal-style"; import * as shields from "../../shields"; export interface RebuildShieldsWindow { @@ -24,15 +24,32 @@ export function openRebuildShieldsWindow( try { shields.shieldsDown(sandboxName, { reason: "auto-unlock for rebuild", - skipTimer: true, + // Rebuild owns the normal close path, while the bounded timer remains + // recovery authority if the host process is killed mid-backup/recreate. + timeout: "30m", throwOnError: true, + // The timer's deadline remains authoritative if rebuild dies, but it + // must not lock a replacement halfway through an active recreate. The + // exact rebuild PID/start identity acts as a renewable liveness lease; + // after owner death the timer retries until restoration can complete. + deferAutoRestoreWhileOwnerAlive: true, + // Existing Hermes sandboxes may predate the sealed root-guard protocol. + // This narrowly scoped rebuild path may use the descriptor-safe legacy + // transition so the old image can be backed up and replaced. Interactive + // shields commands remain fail-closed and require the rebuild. + allowLegacyHermesProtocol: true, }); } catch (err) { const message = err instanceof Error ? err.message : String(err); console.error(""); console.error(` ${_RD}Failed to auto-unlock shields:${R} ${message}`); console.error(" Sandbox is untouched — no data was lost."); - console.error(` Run \`${cliName} ${sandboxName} shields down\` manually, then retry rebuild.`); + console.error( + ` Correct the reported issue, then retry \`${cliName} ${sandboxName} rebuild\`.`, + ); + console.error( + " If the trusted config posture cannot be recovered, restore a trusted backup and recreate the sandbox.", + ); return null; } return window; @@ -67,14 +84,19 @@ export function relockRebuildShieldsWindow( console.log(""); console.log(" Re-applying shields lockdown..."); try { - shields.shieldsUp(sandboxName, { throwOnError: true }); + shields.shieldsUp(sandboxName, { + throwOnError: true, + allowLegacyHermesProtocol: true, + }); console.log(` ${G}✓${R} Shields restored to UP`); window.relocked = true; return true; } catch (err) { const message = err instanceof Error ? err.message : String(err); console.error(` ${YW}⚠${R} Failed to re-apply shields lockdown: ${message}`); - console.error(` Run \`${cliName} ${sandboxName} shields up\` manually to restore lockdown.`); + console.error( + ` Retry \`${cliName} ${sandboxName} rebuild\` after correcting the reported issue. If lockdown cannot be restored, recover from a trusted backup and recreate the sandbox.`, + ); return false; } } diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 5349182c0a7..7b841b94c68 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -13,7 +13,13 @@ type OpenshellCaptureResult = { error?: Error; signal?: NodeJS.Signals | null; }; -type SandboxRecord = { name: string; agent?: string | null }; +type SandboxRecord = { + name: string; + agent?: string | null; + gatewayName?: string | null; + imageTag?: string | null; + openshellDriver?: string | null; +}; type DcodeProbeState = "active" | "idle" | "unverifiable" | "no-runtime"; function dcodeProbeOutput(state: DcodeProbeState, extra = ""): string { @@ -39,9 +45,17 @@ function defaultOpenshellResponses(args: string[]): OpenshellCaptureResult { const shieldsMock = vi.hoisted(() => { const isShieldsDownMock = vi.fn(() => true); + const repairMutableConfigPermsMock = vi.fn(() => ({ + applied: true, + verified: true, + errors: [], + })); + const shieldsUpMock = vi.fn(); let isShieldsDownExport: unknown = isShieldsDownMock; return { isShieldsDownMock, + repairMutableConfigPermsMock, + shieldsUpMock, getIsShieldsDownExport: () => isShieldsDownExport, setIsShieldsDownExport: (value: unknown) => { isShieldsDownExport = value; @@ -49,6 +63,21 @@ const shieldsMock = vi.hoisted(() => { }; }); +const lifecycleMock = vi.hoisted(() => { + const events: string[] = []; + return { + events, + cleanupShieldsDestroyArtifactsMock: vi.fn(() => events.push("cleanup-shields")), + readTimerMarkerMock: vi.fn(() => null as Record | null), + withTimerBoundMock: vi.fn( + (_sandboxName: string, command: string, fn: () => unknown): unknown => { + events.push(`lock:${command}`); + return fn(); + }, + ), + }; +}); + const backupSandboxStateMock = vi.fn(); const captureOpenshellMock = vi.fn< (args: string[], opts?: Record) => OpenshellCaptureResult @@ -71,6 +100,15 @@ const listBackupsMock = vi.fn<() => Array>>(() => []); const parseLiveSandboxNamesMock = vi.fn(() => new Set(["alpha"])); const registerSandboxMock = vi.fn(); const restoreSandboxStateMock = vi.fn(); +const runOpenshellMock = vi.fn((args: string[]) => { + args[0] === "sandbox" && args[1] === "delete" && lifecycleMock.events.push("delete"); + return { status: 0, output: "" }; +}); +const streamSandboxCreateMock = vi.fn(async () => ({ + status: 0, + output: "", + forcedReady: false, +})); const dcodeSandboxEntry = { name: "alpha", agent: "langchain-deepagents-code", @@ -84,7 +122,7 @@ vi.mock("../../adapters/docker", () => ({ vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: captureOpenshellMock, getOpenshellBinary: vi.fn(() => "openshell"), - runOpenshell: vi.fn(() => ({ status: 0, output: "" })), + runOpenshell: runOpenshellMock, })); vi.mock("../../credentials/store", () => ({ @@ -95,6 +133,11 @@ vi.mock("../../domain/sandbox/destroy", () => ({ getSandboxDeleteOutcome: vi.fn(() => ({ alreadyGone: false })), })); +vi.mock("../../inference/nim", () => ({ + stopNimContainer: vi.fn(), + stopNimContainerByName: vi.fn(), +})); + vi.mock("../../policy", () => ({ applyPreset: applyPresetMock, applyPresetContent: applyPresetContentMock, @@ -106,7 +149,7 @@ vi.mock("../../runner", () => ({ ROOT: "/repo", run: vi.fn(() => ({ status: 0 })), shellQuote: (value: string) => `'${value}'`, - validateName: vi.fn(), + validateName: vi.fn((value: string) => value), })); vi.mock("../../runtime-recovery", () => ({ @@ -117,11 +160,20 @@ vi.mock("../../shields", () => ({ get isShieldsDown() { return shieldsMock.getIsShieldsDownExport(); }, - repairMutableConfigPerms: vi.fn(() => ({ - applied: true, - verified: true, - errors: [], - })), + repairMutableConfigPerms: shieldsMock.repairMutableConfigPermsMock, + shieldsUp: shieldsMock.shieldsUpMock, +})); + +vi.mock("../../shields/timer-bound-lock", () => ({ + withTimerBoundShieldsMutationLock: lifecycleMock.withTimerBoundMock, +})); + +vi.mock("../../shields/timer-control", () => ({ + readTimerMarker: lifecycleMock.readTimerMarkerMock, +})); + +vi.mock("../../sandbox/create-stream", () => ({ + streamSandboxCreate: streamSandboxCreateMock, })); vi.mock("../../state/gateway", () => ({ @@ -147,7 +199,7 @@ vi.mock("../../state/sandbox", () => ({ })); vi.mock("./destroy", () => ({ - cleanupShieldsDestroyArtifacts: vi.fn(), + cleanupShieldsDestroyArtifacts: lifecycleMock.cleanupShieldsDestroyArtifactsMock, removeSandboxRegistryEntry: vi.fn(), })); @@ -156,6 +208,9 @@ describe("runSandboxSnapshot", () => { vi.clearAllMocks(); shieldsMock.setIsShieldsDownExport(shieldsMock.isShieldsDownMock); shieldsMock.isShieldsDownMock.mockReturnValue(true); + shieldsMock.shieldsUpMock.mockImplementation(() => lifecycleMock.events.push("harden")); + lifecycleMock.events.length = 0; + lifecycleMock.readTimerMarkerMock.mockReturnValue(null); captureOpenshellMock.mockImplementation((args) => defaultOpenshellResponses(args)); dockerInspectMock.mockReturnValue({ status: 0, stdout: "true\n" }); findBackupMock.mockReturnValue({ match: null }); @@ -502,7 +557,7 @@ describe("runSandboxSnapshot", () => { }); } expect(consoleLog.mock.calls.flat().join("\n")).toContain("Snapshot v3 created"); - }); + }, 15_000); it("renders a stable snapshot list with versions, names, timestamps, and paths", async () => { const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); @@ -558,6 +613,100 @@ describe("runSandboxSnapshot", () => { expect(output).toContain("Restored 1 directories, 1 files"); }); + it("keeps active-timer restore, permission repair, and policy reconciliation serialized", async () => { + lifecycleMock.readTimerMarkerMock.mockReturnValue({ + pid: 4242, + sandboxName: "alpha", + snapshotPath: "/tmp/policy.yaml", + restoreAt: "2026-06-27T06:00:00.000Z", + processToken: "a".repeat(32), + }); + getLatestBackupMock.mockReturnValue({ + timestamp: "2026-06-15T00:00:00.000Z", + backupPath: "/tmp/backup-alpha", + policyPresets: ["github"], + }); + restoreSandboxStateMock.mockReturnValue({ + success: true, + restoredDirs: ["workspace"], + restoredFiles: ["openclaw.json"], + failedDirs: [], + failedFiles: [], + }); + const { runSandboxSnapshot } = await import("./snapshot"); + + await runSandboxSnapshot("alpha", { kind: "restore" }); + + expect(lifecycleMock.events).toContain("lock:restore sandbox snapshot"); + expect(restoreSandboxStateMock).toHaveBeenCalledWith("alpha", "/tmp/backup-alpha"); + expect(shieldsMock.repairMutableConfigPermsMock).toHaveBeenCalledWith("alpha"); + expect(applyPresetMock).toHaveBeenCalledWith("alpha", "github"); + }); + + it("hardens an active timer window before force-deleting a restore destination", async () => { + lifecycleMock.readTimerMarkerMock.mockReturnValue({ + pid: 4242, + sandboxName: "beta", + snapshotPath: "/tmp/policy.yaml", + restoreAt: "2026-06-27T06:00:00.000Z", + processToken: "b".repeat(32), + }); + getSandboxMock.mockImplementation((name) => + name === "alpha" + ? { + name: "alpha", + agent: "openclaw", + imageTag: "nemoclaw-alpha:test", + openshellDriver: "docker", + } + : { + name: "beta", + agent: "openclaw", + imageTag: "nemoclaw-beta:test", + openshellDriver: "docker", + }, + ); + parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"])); + captureOpenshellMock.mockImplementation((args) => + openshellResponses(args, { + "sandbox exec": { status: 0, output: dcodeProbeOutput("no-runtime") }, + "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, + }), + ); + getLatestBackupMock.mockReturnValue({ + timestamp: "2026-06-15T00:00:00.000Z", + backupPath: "/tmp/backup-alpha", + }); + restoreSandboxStateMock.mockReturnValue({ + success: true, + restoredDirs: ["workspace"], + restoredFiles: ["user.md"], + failedDirs: [], + failedFiles: [], + }); + const { runSandboxSnapshot } = await import("./snapshot"); + + await runSandboxSnapshot("alpha", { + kind: "restore", + to: "beta", + force: true, + yes: true, + }); + + expect(shieldsMock.shieldsUpMock).toHaveBeenCalledWith("beta", { + throwOnError: true, + allowLegacyHermesProtocol: true, + }); + expect(lifecycleMock.events.indexOf("harden")).toBeLessThan( + lifecycleMock.events.indexOf("delete"), + ); + expect(lifecycleMock.events.indexOf("delete")).toBeLessThan( + lifecycleMock.events.indexOf("cleanup-shields"), + ); + expect(streamSandboxCreateMock).toHaveBeenCalled(); + expect(restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); + }); + it("refuses snapshot creation before backup when the sandbox is not live", async () => { parseLiveSandboxNamesMock.mockReturnValue(new Set(["beta"])); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 9e0b069c70f..79f2b1b5932 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -13,12 +13,17 @@ import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; +import * as nim from "../../inference/nim"; import { listMessagingProviderSuffixes } from "../../messaging/channels"; import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as policies from "../../policy"; import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; +import { streamSandboxCreate } from "../../sandbox/create-stream"; import * as shields from "../../shields"; +import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; +import { readTimerMarker } from "../../shields/timer-control"; +import { isSandboxReady } from "../../state/gateway"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import * as sandboxState from "../../state/sandbox"; @@ -205,8 +210,6 @@ async function autoCreateSandboxFromSource( srcEntry: SandboxEntry | { name: string }, fromImage: string, ): Promise { - const sandboxCreateStream = require("../../sandbox/create-stream"); - const { isSandboxReady } = require("../../state/gateway"); const basePolicy = path.join(ROOT, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"); const openshellBin = getOpenshellBinary(); @@ -228,7 +231,7 @@ async function autoCreateSandboxFromSource( console.log(` '${dstName}' does not exist. Creating from '${srcName}' image (${fromImage})...`); - const createResult = await sandboxCreateStream.streamSandboxCreate(command, process.env, { + const createResult = await streamSandboxCreate(command, process.env, { // Use a pre-built image, so skip build+push and jump to pod creation. initialPhase: "create", // Wait until the sandbox actually reaches Ready state, not just appears in the list. @@ -299,10 +302,6 @@ async function autoCreateSandboxFromSource( // deliberately skipped here because they can also affect the source sandbox // we are about to clone from. function deleteSandboxForRestore(name: string): void { - const nim = require("../../inference/nim") as { - stopNimContainer: (sandboxName: string, opts?: { silent?: boolean }) => void; - stopNimContainerByName: (name: string) => void; - }; const sbMeta = registry.getSandbox(name); if (sbMeta?.nimContainer) { nim.stopNimContainerByName(sbMeta.nimContainer); @@ -310,37 +309,49 @@ function deleteSandboxForRestore(name: string): void { nim.stopNimContainer(name, { silent: true }); } console.log(` Deleting existing destination '${name}' before restore...`); - const deleteResult = runOpenshell(["sandbox", "delete", name], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - const { alreadyGone } = getSandboxDeleteOutcome(deleteResult); - if (deleteResult.status !== 0 && !alreadyGone) { - console.error(` Failed to delete '${name}' (exit ${deleteResult.status}). Aborting restore.`); - snapshotExit(1); - } - // Destination-only cleanup so the recreated sandbox does not inherit stale - // host-side state or hit provider-name conflicts (Codex #3796 P2): - // - /tmp/nemoclaw-services-: PID dir for this sandbox's services - // - OpenShell per-sandbox messaging bridge providers declared by channel - // manifests. - // - shields-.json + shields timer: per-sandbox shields artifacts - try { - fs.rmSync(`/tmp/nemoclaw-services-${name}`, { - recursive: true, - force: true, - }); - } catch { - // PID dir may not exist \u2014 ignore. - } - for (const suffix of listMessagingProviderSuffixes()) { - runOpenshell(["provider", "delete", `${name}${suffix}`], { + withTimerBoundShieldsMutationLock(name, "delete snapshot restore destination", () => { + if (readTimerMarker(name)) { + shields.shieldsUp(name, { + throwOnError: true, + allowLegacyHermesProtocol: true, + }); + } + const deleteResult = runOpenshell(["sandbox", "delete", name], { ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], + stdio: ["ignore", "pipe", "pipe"], }); - } - cleanupShieldsDestroyArtifacts(name); - removeSandboxRegistryEntry(name); + const { alreadyGone } = getSandboxDeleteOutcome(deleteResult); + if (deleteResult.status !== 0 && !alreadyGone) { + // Any active timer was cleared only after shieldsUp verified the live + // destination was hardened. Preserve that locked state on failure. + console.error( + ` Failed to delete '${name}' (exit ${deleteResult.status}). Aborting restore.`, + ); + snapshotExit(1); + } + // Destination-only cleanup so the recreated sandbox does not inherit stale + // host-side state or hit provider-name conflicts (Codex #3796 P2): + // - /tmp/nemoclaw-services-: PID dir for this sandbox's services + // - OpenShell per-sandbox messaging bridge providers declared by channel + // manifests. + // - shields-.json + shields timer: per-sandbox shields artifacts + try { + fs.rmSync(`/tmp/nemoclaw-services-${name}`, { + recursive: true, + force: true, + }); + } catch { + // PID dir may not exist \u2014 ignore. + } + for (const suffix of listMessagingProviderSuffixes()) { + runOpenshell(["provider", "delete", `${name}${suffix}`], { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }); + } + cleanupShieldsDestroyArtifacts(name); + removeSandboxRegistryEntry(name); + }); console.log(` ${G}\u2713${R} '${name}' deleted`); } @@ -456,44 +467,49 @@ function runSnapshotCreate( console.error(` Sandbox '${sandboxName}' is not running. Cannot create snapshot.`); snapshotExit(1); } - if (!isSnapshotCreationAllowedByShields(sandboxName)) { - console.error(" Cannot create snapshot while shields are up."); - console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); - snapshotExit(1); - } - if ( - shouldCheckDcodeActivity(sandboxName) && - !isSnapshotCreationAllowedByDcodeActivity(sandboxName) - ) { - snapshotExit(1); - } - const label = request.name ? ` (--name ${request.name})` : ""; - console.log(` Creating snapshot of '${sandboxName}'${label}...`); - const result = sandboxState.backupSandboxState(sandboxName, { - name: request.name ?? null, - }); - if (result.success) { - const manifest = result.manifest!; - const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; - const v = formatSnapshotVersion(entry); - const nameSuffix = entry.name ? ` name=${entry.name}` : ""; - const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; - console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); - console.log(` ${manifest.backupPath}`); - return; - } - if (result.error) { - console.error(` ${result.error}`); - } else { - console.error(" Snapshot failed."); - if (result.failedDirs.length > 0) { - console.error(` Failed directories: ${result.failedDirs.join(", ")}`); + return withTimerBoundShieldsMutationLock(sandboxName, "create sandbox snapshot", () => { + // Keep the shields check and backup in one timer-bound interval. Normal + // auto-restore waits; at the absolute deadline it may preempt this process + // and reclaim the token rather than changing policy/config mid-copy. + if (!isSnapshotCreationAllowedByShields(sandboxName)) { + console.error(" Cannot create snapshot while shields are up."); + console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); + snapshotExit(1); } - if (result.failedFiles.length > 0) { - console.error(` Failed files: ${result.failedFiles.join(", ")}`); + if ( + shouldCheckDcodeActivity(sandboxName) && + !isSnapshotCreationAllowedByDcodeActivity(sandboxName) + ) { + snapshotExit(1); } - } - snapshotExit(1); + const label = request.name ? ` (--name ${request.name})` : ""; + console.log(` Creating snapshot of '${sandboxName}'${label}...`); + const result = sandboxState.backupSandboxState(sandboxName, { + name: request.name ?? null, + }); + if (result.success) { + const manifest = result.manifest!; + const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; + const v = formatSnapshotVersion(entry); + const nameSuffix = entry.name ? ` name=${entry.name}` : ""; + const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; + console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); + console.log(` ${manifest.backupPath}`); + return; + } + if (result.error) { + console.error(` ${result.error}`); + } else { + console.error(" Snapshot failed."); + if (result.failedDirs.length > 0) { + console.error(` Failed directories: ${result.failedDirs.join(", ")}`); + } + if (result.failedFiles.length > 0) { + console.error(` Failed files: ${result.failedFiles.join(", ")}`); + } + } + snapshotExit(1); + }); } function repairRestoredOpenClawConfigPerms( @@ -743,42 +759,48 @@ async function runSnapshotRestore( } await autoCreateSandboxFromSource(sandboxName, targetSandbox, srcEntry, fromImage); } - if (targetSandbox !== sandboxName) { - console.log(` Restoring snapshot from '${sandboxName}' into '${targetSandbox}'...`); - } else { - console.log(` Restoring snapshot into '${sandboxName}'...`); - } - const result = sandboxState.restoreSandboxState(targetSandbox, backupPath); - if (result.success) { - console.log( - ` ${G}\u2713${R} Restored ${result.restoredDirs.length} directories, ${result.restoredFiles.length} files`, - ); - } else { - console.error(` Restore failed.`); - if (result.restoredDirs.length > 0) { - console.error(` Partial: ${result.restoredDirs.join(", ")}`); + withTimerBoundShieldsMutationLock(targetSandbox, "restore sandbox snapshot", () => { + // Serialize filesystem restore, mutable-permission repair, and policy + // reconciliation under the active timer generation. Normal auto-restore + // waits; the absolute deadline may preempt this process and reclaim the + // token, preventing policy/config mutation after lockdown resumes. + if (targetSandbox !== sandboxName) { + console.log(` Restoring snapshot from '${sandboxName}' into '${targetSandbox}'...`); + } else { + console.log(` Restoring snapshot into '${sandboxName}'...`); } - if (result.failedDirs.length > 0) { - console.error(` Failed: ${result.failedDirs.join(", ")}`); - } - if (result.failedFiles.length > 0) { - console.error(` Failed files: ${result.failedFiles.join(", ")}`); + const result = sandboxState.restoreSandboxState(targetSandbox, backupPath); + if (result.success) { + console.log( + ` ${G}\u2713${R} Restored ${result.restoredDirs.length} directories, ${result.restoredFiles.length} files`, + ); + } else { + console.error(` Restore failed.`); + if (result.restoredDirs.length > 0) { + console.error(` Partial: ${result.restoredDirs.join(", ")}`); + } + if (result.failedDirs.length > 0) { + console.error(` Failed: ${result.failedDirs.join(", ")}`); + } + if (result.failedFiles.length > 0) { + console.error(` Failed files: ${result.failedFiles.join(", ")}`); + } + snapshotExit(1); } - snapshotExit(1); - } - // Post-restore security-state reconciliation is best-effort by design: the - // filesystem restore succeeded and old snapshots may target hosts where policy - // providers or mutable-config repair are temporarily unavailable. Surface every - // failure as a warning, but keep the restore result tied to state restoration. - // #5027/#4538: openclaw.json restores via the generic copy strategy, which - // lands it at 0640. Repair the mutable config contract when needed. - repairRestoredOpenClawConfigPerms(targetSandbox, result); - // Reconcile the target's policy presets to match the snapshot manifest - // exactly. Skip legacy snapshots that predate the `policyPresets` field. - reconcileSnapshotPolicyPresets(targetSandbox, resolvedSnapshot); - // Reconcile custom policy presets (applied via --from-file/--from-dir). - // Skipped for legacy snapshots that predate the `customPolicies` field. - reconcileSnapshotCustomPolicies(targetSandbox, resolvedSnapshot); + // Post-restore security-state reconciliation is best-effort by design: the + // filesystem restore succeeded and old snapshots may target hosts where policy + // providers or mutable-config repair are temporarily unavailable. Surface every + // failure as a warning, but keep the restore result tied to state restoration. + // #5027/#4538: openclaw.json restores via the generic copy strategy, which + // lands it at 0640. Repair the mutable config contract when needed. + repairRestoredOpenClawConfigPerms(targetSandbox, result); + // Reconcile the target's policy presets to match the snapshot manifest + // exactly. Skip legacy snapshots that predate the `policyPresets` field. + reconcileSnapshotPolicyPresets(targetSandbox, resolvedSnapshot); + // Reconcile custom policy presets (applied via --from-file/--from-dir). + // Skipped for legacy snapshots that predate the `customPolicies` field. + reconcileSnapshotCustomPolicies(targetSandbox, resolvedSnapshot); + }); } export async function runSandboxSnapshot( diff --git a/src/lib/agent/defs.test.ts b/src/lib/agent/defs.test.ts index 216707f8b05..22565843099 100644 --- a/src/lib/agent/defs.test.ts +++ b/src/lib/agent/defs.test.ts @@ -174,15 +174,17 @@ describe("agent definitions", () => { }); it("rejects invalid forward_ports values in manifests", () => { - const agentName = `invalid-forward-port-${String(Date.now())}`; - writeTempAgentManifest( - agentName, - [`name: ${agentName}`, "display_name: Broken Ports", "forward_ports:", " - 70000"].join( - "\n", - ), - ); - - expect(() => loadAgent(agentName)).toThrow(/forward_ports\[0\]/); + for (const port of [1023, 70000]) { + const agentName = `invalid-forward-port-${String(port)}-${String(Date.now())}`; + writeTempAgentManifest( + agentName, + [`name: ${agentName}`, "display_name: Broken Ports", "forward_ports:", ` - ${port}`].join( + "\n", + ), + ); + + expect(() => loadAgent(agentName)).toThrow(/forward_ports\[0\]/); + } }); it("rejects invalid health_probe.port values in manifests", () => { diff --git a/src/lib/agent/defs.ts b/src/lib/agent/defs.ts index 64541b2d9eb..a00ea536959 100644 --- a/src/lib/agent/defs.ts +++ b/src/lib/agent/defs.ts @@ -13,12 +13,12 @@ import { resolveAgentNameAlias as resolveKnownAgentNameAlias, } from "./aliases"; import { type AgentDashboardUi, readDashboardUi } from "./dashboard-ui"; -import { readAgentRuntime, type AgentRuntime } from "./runtime-manifest"; +import { type AgentRuntime, readAgentRuntime } from "./runtime-manifest"; import { type AgentWebAuth, readWebAuth } from "./web-auth"; export type { AgentRuntime, AgentRuntimeKind } from "./runtime-manifest"; -export type { AgentWebAuth, AgentWebAuthMethod } from "./web-auth"; export { getAgentRuntimeKind, isTerminalAgent } from "./runtime-manifest"; +export type { AgentWebAuth, AgentWebAuthMethod } from "./web-auth"; export const AGENTS_DIR = path.join(ROOT, "agents"); @@ -259,8 +259,8 @@ function readStateFiles(record: ManifestRecord): AgentStateFile[] | undefined { }); } -function isValidPort(value: unknown): value is number { - return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; +function isValidPort(value: unknown, min = 1): value is number { + return typeof value === "number" && Number.isInteger(value) && value >= min && value <= 65535; } function readPortArray(record: ManifestRecord, key: string): number[] | undefined { @@ -271,9 +271,9 @@ function readPortArray(record: ManifestRecord, key: string): number[] | undefine } const ports = value.map((entry, index) => { - if (!isValidPort(entry)) { + if (!isValidPort(entry, 1024)) { throw new Error( - `Agent manifest field '${key}[${String(index)}]' must be an integer TCP port between 1 and 65535`, + `Agent manifest field '${key}[${String(index)}]' must be an integer TCP port between 1024 and 65535`, ); } return entry; diff --git a/src/lib/agent/gateway-restart-markers.ts b/src/lib/agent/gateway-restart-markers.ts new file mode 100644 index 00000000000..6f6a90940f5 --- /dev/null +++ b/src/lib/agent/gateway-restart-markers.ts @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const GATEWAY_RESTART_MARKERS = Object.freeze({ + ROOT_EXEC_UNAVAILABLE: "ROOT_EXEC_UNAVAILABLE", + GOSU_MISSING: "GOSU_MISSING", + GATEWAY_USER_MISSING: "GATEWAY_USER_MISSING", + SECRET_BOUNDARY_REFUSED: "SECRET_BOUNDARY_REFUSED", + SECRET_BOUNDARY_OK: "SECRET_BOUNDARY_OK", + SECRET_BOUNDARY_VALIDATOR_MISSING: "SECRET_BOUNDARY_VALIDATOR_MISSING", + HERMES_RUNTIME_CONFIG_GUARD_MISSING: "HERMES_RUNTIME_CONFIG_GUARD_MISSING", + GATEWAY_UNSAFE_CONFIG_PATH: "GATEWAY_UNSAFE_CONFIG_PATH", + GATEWAY_CONFIG_HASH_MISMATCH: "GATEWAY_CONFIG_HASH_MISMATCH", + GATEWAY_STALE_PROCESSES: "GATEWAY_STALE_PROCESSES", + GATEWAY_FAILED: "GATEWAY_FAILED", +} as const); diff --git a/src/lib/agent/gateway-restart-scripts.ts b/src/lib/agent/gateway-restart-scripts.ts new file mode 100644 index 00000000000..84886d19f22 --- /dev/null +++ b/src/lib/agent/gateway-restart-scripts.ts @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Gateway recovery/restart shell generation. Kept separate from runtime.ts so +// agent lookup and display metadata do not grow around security-sensitive +// process-control scripts. + +import { DASHBOARD_PORT } from "../core/ports"; +import { shellQuote } from "../runner"; +import { type AgentDefinition, isTerminalAgent } from "./defs"; +import { GATEWAY_RESTART_MARKERS as MARKERS } from "./gateway-restart-markers"; +import { + buildGatewayGuardRecoveryLines, + buildGatewayLogSelection, + buildGatewayLogSetup, + gatewayGuardRefusalCommand, + gatewayLaunchCommand, +} from "./gateway-script-shared"; + +export const TERMINAL_AGENT_RECOVERY_SCRIPT = Object.freeze({ kind: "terminal" } as const); + +export type AgentRecoveryScript = string | typeof TERMINAL_AGENT_RECOVERY_SCRIPT | null; + +export function isTerminalAgentRecoveryScript( + script: AgentRecoveryScript, +): script is typeof TERMINAL_AGENT_RECOVERY_SCRIPT { + return script === TERMINAL_AGENT_RECOVERY_SCRIPT; +} + +export function getTerminalCommand( + agent: AgentDefinition | null, + mode: "interactive" | "headless" = "interactive", +): string | null { + if (!agent || !isTerminalAgent(agent)) return null; + if (mode === "headless") return agent.runtime?.headless_command ?? null; + return agent.runtime?.interactive_command ?? agent.runtime?.headless_command ?? null; +} + +function getRecoveryHealthProbeUrl( + agent: AgentDefinition | null, + fallbackPort = DASHBOARD_PORT, +): string { + if (!agent) return `http://127.0.0.1:${fallbackPort}/health`; + if (isTerminalAgent(agent)) return ""; + return agent.healthProbe?.url || `http://127.0.0.1:${fallbackPort}/health`; +} + +function escapeEre(value: string): string { + return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); +} + +function escapeCharClass(value: string): string { + return value.replace(/[\\\]\[\^\-]/g, "\\$&"); +} + +function selfSafeGatewayProcessPattern(command: string): string { + const [executable = "", ...args] = command.trim().split(/\s+/).filter(Boolean); + const [first = "", ...rest] = Array.from(executable); + if (!first) return ""; + const executablePattern = `[${escapeCharClass(first)}]${escapeEre(rest.join(""))}`; + const commandPattern = [executablePattern, ...args.map(escapeEre)].join("[[:space:]]+"); + return `${commandPattern}([[:space:]]|$)`; +} + +/** + * Build the legacy SSH recovery shell for custom gateway agents. OpenClaw and + * Hermes are deliberately excluded: their topology-specific controllers own + * lifecycle control and must never be raced by a second regex-based launcher. + */ +export function buildRecoveryScript( + agent: AgentDefinition & { runtime: { kind: "terminal" } }, + port?: number, +): typeof TERMINAL_AGENT_RECOVERY_SCRIPT; +export function buildRecoveryScript(agent: AgentDefinition | null, port?: number): string | null; +export function buildRecoveryScript( + agent: AgentDefinition | null, + port = agent?.forwardPort ?? agent?.healthProbe?.port ?? DASHBOARD_PORT, +): AgentRecoveryScript { + if (!agent) return null; + if (isTerminalAgent(agent)) return TERMINAL_AGENT_RECOVERY_SCRIPT; + if (agent.name === "openclaw" || agent.name === "hermes") return null; + + const probeUrl = getRecoveryHealthProbeUrl(agent, port); + const binaryPath = agent.binary_path || "/usr/local/bin/openclaw"; + const binaryName = binaryPath.split("/").pop() ?? "openclaw"; + const defaultGatewayCommand = `${binaryName} gateway run`; + const configuredGatewayCommand = agent.gateway_command?.trim() || defaultGatewayCommand; + const usesValidatedBinary = configuredGatewayCommand === defaultGatewayCommand; + const customGatewayExecutable = configuredGatewayCommand.split(/\s+/)[0] ?? binaryName; + const staleGatewayPattern = selfSafeGatewayProcessPattern(configuredGatewayCommand); + const validationSteps = usesValidatedBinary + ? [ + `AGENT_BIN=${shellQuote(binaryPath)}; if [ ! -x "$AGENT_BIN" ]; then AGENT_BIN="$(command -v ${shellQuote(binaryName)})"; fi;`, + 'if [ -z "$AGENT_BIN" ]; then echo AGENT_MISSING; exit 1; fi;', + ] + : [ + `GATEWAY_CMD_BIN=${shellQuote(customGatewayExecutable)};`, + 'case "$GATEWAY_CMD_BIN" in */*) [ -x "$GATEWAY_CMD_BIN" ] || { echo AGENT_MISSING; exit 1; } ;; *) command -v "$GATEWAY_CMD_BIN" >/dev/null 2>&1 || { echo AGENT_MISSING; exit 1; } ;; esac;', + ]; + // Append (>>) rather than truncate (>) so the [gateway-recovery] WARNING + // lines that the recovery script writes to gateway.log moments earlier + // survive past the gateway launch. Otherwise the warning explaining why the + // gateway is about to crash gets wiped by the same launch that is about to + // crash on a missing guard. (#2478) + const launchCommand = usesValidatedBinary + ? gatewayLaunchCommand(`"$AGENT_BIN" gateway run --port ${port}`) + : gatewayLaunchCommand(`${configuredGatewayCommand} --port ${port}`); + + // Validate or rebuild /tmp/nemoclaw-proxy-env.sh before shell init and the + // health fast path so a healthy gateway cannot leave a wiped guard chain + // unrepaired. Recovery also stops stale launcher/gateway processes that may + // have respawned between the health probe and relaunch. + return [ + ...buildGatewayLogSetup(false), + buildGatewayLogSelection(), + ...buildGatewayGuardRecoveryLines(), + gatewayGuardRefusalCommand(), + "[ -f ~/.bashrc ] && . ~/.bashrc;", + `_GW_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 ${shellQuote(probeUrl)} 2>/dev/null || echo 000); case "$_GW_CODE" in 200|401) echo ALREADY_RUNNING; exit 0 ;; esac;`, + `_GATEWAY_PROC_PATTERN=${shellQuote(staleGatewayPattern)};`, + `if [ -n "$_GATEWAY_PROC_PATTERN" ]; then pkill -TERM -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; pkill -KILL -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; if pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1; then echo ${MARKERS.GATEWAY_STALE_PROCESSES}; exit 1; fi; fi;`, + ...validationSteps, + launchCommand, + "GPID=$!; sleep 2;", + `if kill -0 "$GPID" 2>/dev/null; then echo "GATEWAY_PID=$GPID"; else echo ${MARKERS.GATEWAY_FAILED}; tail -5 "$_GATEWAY_LOG" 2>/dev/null; exit 1; fi`, + ].join(" "); +} diff --git a/src/lib/agent/gateway-script-shared.ts b/src/lib/agent/gateway-script-shared.ts new file mode 100644 index 00000000000..49d4ea65b62 --- /dev/null +++ b/src/lib/agent/gateway-script-shared.ts @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { shellQuote } from "../runner"; +import { buildGatewayGuardRecoveryLines } from "./runtime-recovery-preload"; + +export function buildNoFollowLogSetupCommand( + path: string, + logOwnerUser?: string, + ownerMode = "0o644", +): string { + const displayPath = path.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); + const prepareLog = [ + "import errno, os, pwd, stat, sys", + "path = sys.argv[1]", + "owner = sys.argv[2] if len(sys.argv) > 2 else ''", + `owner_mode = ${ownerMode}`, + "fallback_mode = 0o600", + "flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0)", + "try:", + " fd = os.open(path, flags, 0o644)", + "except OSError as exc:", + " if exc.errno == errno.ELOOP:", + ` print('[gateway-recovery] ERROR: refusing to prepare symlinked ${displayPath}', file=sys.stderr)`, + " sys.exit(1)", + " if exc.errno == errno.ENXIO:", + ` print('[gateway-recovery] ERROR: ${displayPath} is not a regular file', file=sys.stderr)`, + " sys.exit(1)", + " if exc.errno in (errno.EACCES, errno.EPERM):", + ` print('[gateway-recovery] ERROR: ${displayPath} is not writable by recovery user', file=sys.stderr)`, + " sys.exit(0)", + ` print(f'[gateway-recovery] ERROR: cannot prepare ${displayPath}: {exc}', file=sys.stderr)`, + " sys.exit(1)", + "try:", + " if not stat.S_ISREG(os.fstat(fd).st_mode):", + ` print('[gateway-recovery] ERROR: ${displayPath} is not a regular file', file=sys.stderr)`, + " sys.exit(1)", + " if owner and os.geteuid() == 0:", + " try:", + " pw = pwd.getpwnam(owner)", + " except KeyError:", + " os.fchmod(fd, fallback_mode)", + " else:", + " os.fchown(fd, pw.pw_uid, pw.pw_gid)", + " os.fchmod(fd, owner_mode)", + " else:", + " os.fchmod(fd, fallback_mode)", + "finally:", + " os.close(fd)", + ].join("\n"); + return [ + "python3", + "-c", + shellQuote(prepareLog), + path, + ...(logOwnerUser ? [shellQuote(logOwnerUser)] : []), + ].join(" "); +} + +export function buildGatewayLogSetup(includeAutoPairLog = false, logOwnerUser?: string): string[] { + const lines = [`${buildNoFollowLogSetupCommand("/tmp/gateway.log", logOwnerUser)} || exit 1;`]; + if (includeAutoPairLog) { + lines.push( + `${buildNoFollowLogSetupCommand("/tmp/auto-pair.log", "sandbox", "0o600")} || exit 1;`, + ); + } + return lines; +} + +export function buildGatewayLogSelection(): string { + return '_GATEWAY_LOG=/tmp/gateway.log; if ! : >> "$_GATEWAY_LOG" 2>/dev/null; then _GATEWAY_LOG=/tmp/gateway-recovery.log; : >> "$_GATEWAY_LOG" 2>/dev/null || true; fi;'; +} + +export function gatewayGuardRefusalCommand(): string { + return '[ "$_GUARDS_MISSING" = "1" ] && { _E="[gateway-recovery] ERROR: NODE_OPTIONS missing safety-net preload or ciao preload after trusted recovery - refusing unguarded gateway relaunch (#2478/#2701)"; echo "$_E" >&2; echo "$_E" >> "$_GATEWAY_LOG"; exit 1; };'; +} + +export function gatewayLaunchCommand(command: string, runAsUser?: string): string { + const logSelection = buildGatewayLogSelection(); + const userLaunch = `nohup ${command} >> "$_GATEWAY_LOG" 2>&1 &`; + if (!runAsUser) { + return `${logSelection} ${userLaunch}`; + } + return `${logSelection} if [ "$(id -u)" = "0" ] && command -v gosu >/dev/null 2>&1 && id ${shellQuote(runAsUser)} >/dev/null 2>&1; then nohup gosu ${shellQuote(runAsUser)} ${command} >> "$_GATEWAY_LOG" 2>&1 & else ${userLaunch} fi;`; +} + +export { buildGatewayGuardRecoveryLines }; diff --git a/src/lib/agent/hermes-recovery-boundary.ts b/src/lib/agent/hermes-recovery-boundary.ts deleted file mode 100644 index b9f9e38bfd6..00000000000 --- a/src/lib/agent/hermes-recovery-boundary.ts +++ /dev/null @@ -1,176 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Hermes secret-boundary guards for the host-side recovery path. -// -// The Hermes startup entrypoint (agents/hermes/start.sh) already runs -// validate-env-secret-boundary.py at cold start. `sandbox recover` / -// `connect --probe-only` does NOT re-enter that entrypoint — it spawns a -// recovery shell directly. The helpers in this file emit shell snippets that -// re-run the same validator from the recovery shell so the documented secret -// boundary applies on every relaunch path: gateway recovery, dashboard-only -// recovery, and the manual copy-paste command surfaced when automatic recovery -// fails. -// -// Kept in its own module so this security-sensitive shell generation does not -// continue to grow agent/runtime.ts and so the regression-test surface stays -// focused. runtime.ts imports the public guards; tests exercise both the -// generated shell shape and the live shell execution against stubbed binaries. - -import { shellQuote } from "../runner"; - -export const HERMES_SECRET_BOUNDARY_VALIDATOR_PATH = - "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py"; - -export const SECRET_BOUNDARY_REFUSED_MARKER = "SECRET_BOUNDARY_REFUSED"; -export const SECRET_BOUNDARY_OK_MARKER = "SECRET_BOUNDARY_OK"; -export const SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER = "SECRET_BOUNDARY_VALIDATOR_MISSING"; - -const HERMES_GATEWAY_PROC_PATTERN = "[h]ermes[[:space:]]+gateway([[:space:]]|$)"; -const HERMES_DASHBOARD_PROC_PATTERN = "[h]ermes[[:space:]]+dashboard([[:space:]]|$)"; -const HERMES_BOUNDARY_RECOVERY_LOG = "/tmp/gateway-recovery.log"; - -function buildHermesBoundaryKillSnippet(): string { - return [ - `pkill -TERM -f ${shellQuote(HERMES_GATEWAY_PROC_PATTERN)} 2>/dev/null || true;`, - `pkill -TERM -f ${shellQuote(HERMES_DASHBOARD_PROC_PATTERN)} 2>/dev/null || true;`, - "sleep 1;", - `pkill -KILL -f ${shellQuote(HERMES_GATEWAY_PROC_PATTERN)} 2>/dev/null || true;`, - `pkill -KILL -f ${shellQuote(HERMES_DASHBOARD_PROC_PATTERN)} 2>/dev/null || true;`, - ].join(" "); -} - -/** - * Pipe a validator invocation's stderr through `tee` so the detailed `[SECURITY]` - * lines emitted by `validate-env-secret-boundary.py` are persisted to - * `/tmp/gateway-recovery.log` inside the sandbox AND mirrored back onto stderr. - * The recovery caller currently treats the command result as a boolean, so - * without this duplication the documented `[SECURITY] Refusing Hermes startup ...` - * line and the offending key never surface anywhere a user can inspect after - * the sandbox recovers — failing the issue's log-acceptance clause even when - * relaunch is correctly refused. - * - * SECURITY: `tee -a` to `/tmp/gateway-recovery.log` is invoked here BEFORE - * `buildGatewayLogSetup` runs, so the log path is not pre-opened with the - * O_NOFOLLOW helper. This is safe today because non-OpenClaw recovery runs as - * the sandbox user over SSH; the sandbox user owns `/tmp` and cannot win a - * symlink race with itself for files under its own control. Do not move this - * snippet into a root-exec recovery path without first prepending an - * O_NOFOLLOW-prepared log file via the shared no-follow helper. - */ -function buildHermesValidatorInvocation(args: string): string { - return `python3 ${shellQuote(HERMES_SECRET_BOUNDARY_VALIDATOR_PATH)} ${args} 2> >(tee -a ${shellQuote(HERMES_BOUNDARY_RECOVERY_LOG)} >&2)`; -} - -function buildHermesValidatorMissingLog(): string { - const message = `[gateway-recovery] REFUSING: secret-boundary validator script ${HERMES_SECRET_BOUNDARY_VALIDATOR_PATH} is missing on this sandbox image; recovery cannot verify /sandbox/.hermes/.env. Re-image the sandbox with a current Hermes build.`; - return `printf '%s\\n' ${shellQuote(message)} | tee -a ${shellQuote(HERMES_BOUNDARY_RECOVERY_LOG)} >&2;`; -} - -// Missing-validator recovery is fail-closed: the host CLI cannot prove the -// Hermes entrypoint's env-file boundary without this source validator, so older -// images must be re-imaged before gateway/dashboard recovery can proceed. - -/** - * Build the shell snippet that re-runs the documented Hermes secret-boundary - * check against `/sandbox/.hermes/.env` before any in-sandbox Hermes process is - * relaunched. The startup entrypoint already runs this validator, but - * `sandbox recover` / `connect --probe-only` does not re-enter the entrypoint, - * so without this guard the boundary would only apply on cold start. - * - * Fail-closed when the validator runs and refuses: kill any currently-running - * Hermes gateway and dashboard so `/health` cannot keep answering with the - * poisoned configuration, emit `SECRET_BOUNDARY_REFUSED` on stdout, and exit 1. - * The validator's detailed `[SECURITY]` lines are appended to - * `/tmp/gateway-recovery.log` so a user inspecting the sandbox after a refused - * recovery can identify the offending key. - * - * Older sandbox images that do not yet bake the validator fail closed with a - * re-image message, so recovery never reports success without re-checking the - * documented env-file secret boundary. - */ -export function buildHermesEnvFileBoundaryGuard(): string { - const validator = HERMES_SECRET_BOUNDARY_VALIDATOR_PATH; - const kill = buildHermesBoundaryKillSnippet(); - const missingLog = buildHermesValidatorMissingLog(); - const invocation = buildHermesValidatorInvocation("env-file /sandbox/.hermes/.env"); - return `if [ ! -f ${shellQuote(validator)} ]; then ${missingLog} ${kill} echo SECRET_BOUNDARY_VALIDATOR_MISSING; exit 1; elif ! ${invocation}; then ${kill} echo SECRET_BOUNDARY_REFUSED; exit 1; fi;`; -} - -/** - * Build the shell snippet that runs the Hermes runtime-env boundary validator - * against the recovery shell's environment. Wire this in AFTER any preload env - * file (e.g. `/tmp/nemoclaw-proxy-env.sh`) has been sourced and BEFORE the - * launch command, so the final environment the relaunched gateway will inherit - * is the one checked. - * - * Same semantics as the env-file guard: fail-closed when the validator runs and - * refuses, and fail-closed when the validator script is absent from an older - * image. - */ -export function buildHermesRuntimeEnvBoundaryGuard(): string { - const validator = HERMES_SECRET_BOUNDARY_VALIDATOR_PATH; - const kill = buildHermesBoundaryKillSnippet(); - const missingLog = buildHermesValidatorMissingLog(); - const invocation = buildHermesValidatorInvocation("runtime-env"); - return `if [ ! -f ${shellQuote(validator)} ]; then ${missingLog} ${kill} echo SECRET_BOUNDARY_VALIDATOR_MISSING; exit 1; elif ! ${invocation}; then ${kill} echo SECRET_BOUNDARY_REFUSED; exit 1; fi;`; -} - -/** - * Build a standalone shell snippet that evaluates the Hermes env-file - * secret-boundary contract without relaunching anything. Intended for the - * `sandbox recover` / `connect --probe-only` probe path, where the gateway - * is already running and the relaunch script is not reached: the host can - * exec this snippet inside the sandbox, parse the marker on stdout, and - * decide whether to refuse the probe. - * - * Marker contract on stdout (one of): - * - `SECRET_BOUNDARY_OK` — validator ran and accepted the env file. - * - `SECRET_BOUNDARY_REFUSED` — validator ran and refused; the snippet - * killed any running gateway/dashboard process before exiting non-zero. - * - `SECRET_BOUNDARY_VALIDATOR_MISSING` — validator script absent on this - * sandbox image; the snippet killed gateway/dashboard processes and exits - * non-zero so the caller can refuse recovery. - * - * Validator stderr (`[SECURITY] …` lines) is left on the exec command's - * stderr; the caller surfaces it directly. This keeps the snippet - * independent of any `/tmp/gateway-recovery.log` setup, which matters when - * the snippet runs via `openshell sandbox exec` (root) rather than the - * sandbox-user SSH recovery shell that the relaunch path uses. - * - * The kill snippet is intentionally invoked from a context the caller - * arranges to have authority over: a sandbox-user SSH shell cannot signal - * gateway-user processes (test/e2e-gateway-isolation.sh test 13), so a - * refusal that did not also bring the listener down would log a refusal - * while `/health` kept serving. Run this via the root sandbox-exec path so - * the kill has authority. - */ -export function buildHermesEnvFileBoundaryStandaloneCheck(): string { - const validator = HERMES_SECRET_BOUNDARY_VALIDATOR_PATH; - const kill = buildHermesBoundaryKillSnippet(); - const invocation = `python3 ${shellQuote(validator)} env-file /sandbox/.hermes/.env`; - return [ - `if [ ! -f ${shellQuote(validator)} ]; then`, - ` ${kill}`, - ` echo ${SECRET_BOUNDARY_VALIDATOR_MISSING_MARKER};`, - ` exit 1;`, - `fi;`, - `if ${invocation}; then`, - ` echo ${SECRET_BOUNDARY_OK_MARKER}; exit 0;`, - `else`, - ` ${kill}`, - ` echo ${SECRET_BOUNDARY_REFUSED_MARKER};`, - ` exit 1;`, - `fi;`, - ].join("\n"); -} - -export const __testing = { - buildHermesEnvFileBoundaryGuard, - buildHermesRuntimeEnvBoundaryGuard, - buildHermesEnvFileBoundaryStandaloneCheck, - buildHermesBoundaryKillSnippet, - HERMES_GATEWAY_PROC_PATTERN, - HERMES_DASHBOARD_PROC_PATTERN, - HERMES_BOUNDARY_RECOVERY_LOG, -}; diff --git a/src/lib/agent/onboard.test.ts b/src/lib/agent/onboard.test.ts index 55f3c0f1a20..8d11f8860ec 100644 --- a/src/lib/agent/onboard.test.ts +++ b/src/lib/agent/onboard.test.ts @@ -248,41 +248,6 @@ describe("printDashboardUi with port 8642 outside the chat UI (#2078)", () => { expect(output).not.toContain("http://127.0.0.1:9100/v1"); }); - it("emits a URL for a secondary forward port that resolves to the scheme default", () => { - // Regression: `new URL("http://h:80").port === ""`. A strict equality - // filter against String(port) silently drops the URL line. The helper - // must normalise scheme-default ports before filtering. - const buildUrlsWithDefaultPort = (_token: string | null, port: number): string[] => { - if (port === 80) return ["http://127.0.0.1:80/"]; - return [`http://127.0.0.1:${port}/`]; - }; - - const httpAgent = makeAgent({ - name: "experimental", - displayName: "Experimental", - forwardPort: 18789, - forward_ports: [18789, 80], - healthProbe: { url: "http://localhost:18789/health", port: 18789, timeout_seconds: 30 }, - dashboard: { - kind: "ui", - label: "Dashboard", - path: "/", - healthPath: "/health", - auth: "session", - }, - }); - - printDashboardUi("agent-box", null, httpAgent, { - note: noteSpy, - buildControlUiUrls: buildUrlsWithDefaultPort, - }); - - const output = logSpy.mock.calls.map((args) => String(args[0])).join("\n"); - expect(output).toContain("Experimental additional port"); - expect(output).toContain("Port 80 must be forwarded before connecting."); - expect(output).toMatch(/http:\/\/127\.0\.0\.1(:80)?\//); - }); - it("redacts tokenized URLs for UI-kind agents and shows the token retrieval command", () => { const token = "a".repeat(64); printDashboardUi("sandbox-y", token, uiAgent, { diff --git a/src/lib/agent/onboard.ts b/src/lib/agent/onboard.ts index a86468b2bfe..ffb6d68cfa8 100644 --- a/src/lib/agent/onboard.ts +++ b/src/lib/agent/onboard.ts @@ -566,10 +566,10 @@ export function printDashboardUi( * The URL filter normalises empty `URL.port` results to the scheme * default. `new URL("http://h:80").port` returns `""` because WHATWG * URL elides the default scheme port; a strict `urlPort === String(port)` - * comparison would silently drop URLs for ports 80 and 443 even though - * the underlying `forward_ports` validation accepts them. The - * normalisation keeps the filter sound while still excluding any URL - * whose port truly does not match the declared entry. + * comparison would silently drop scheme-default URLs from older or + * direct-call agent definitions. The normalisation keeps the filter + * sound while still excluding any URL whose port truly does not match + * the declared entry. */ function printAdditionalForwardPorts( agent: AgentDefinition, @@ -580,7 +580,7 @@ function printAdditionalForwardPorts( if (declared.length === 0) return; const apiPort = agent.healthProbe?.port; for (const port of declared) { - if (!Number.isInteger(port) || port < 1 || port > 65535) continue; + if (!Number.isInteger(port) || port < 1024 || port > 65535) continue; if (port === primaryPort) continue; const isApi = port === apiPort; const sectionLabel = isApi ? "OpenAI-compatible API" : "additional port"; diff --git a/src/lib/agent/runtime-hermes-secret-boundary-behavioural.test.ts b/src/lib/agent/runtime-hermes-secret-boundary-behavioural.test.ts deleted file mode 100644 index c488470d1d8..00000000000 --- a/src/lib/agent/runtime-hermes-secret-boundary-behavioural.test.ts +++ /dev/null @@ -1,409 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Behavioural tests for the Hermes recovery boundary guards. These spawn `bash` -// on the synthesised shell snippets or full recovery scripts with stubbed -// `python3`/`pkill`/`pgrep`/`curl`/`hermes` binaries and assert real exit codes, -// kill invocations, and persisted `/tmp/gateway-recovery.log` contents. Pure -// generated-shell shape assertions live in -// runtime-hermes-secret-boundary-shape.test.ts. - -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"; -import { - createRecoveryPreloadHarnessPaths, - type RecoveryPreloadHarnessPaths, - rewriteRecoveryPreloadPaths, -} from "../../../test/helpers/runtime-recovery-preload-test-helpers"; -import { __testing, HERMES_SECRET_BOUNDARY_VALIDATOR_PATH } from "./hermes-recovery-boundary"; -import { hermesAgent } from "./hermes-recovery-boundary-fixtures"; -import { buildRecoveryScript } from "./runtime"; - -function writeStub(dir: string, name: string, body: string) { - const stub = path.join(dir, name); - fs.writeFileSync(stub, `#!/usr/bin/env bash\n${body}\n`, { mode: 0o755 }); - return stub; -} - -function removeTempDir(dir: string) { - fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); -} - -describe("Hermes secret-boundary guard — guard snippet behaviour", () => { - function runGuard(opts: { guard: string; pythonExit: 0 | 1; validatorExists: boolean }) { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-guard-")); - const stubsDir = path.join(tmp, "bin"); - const validatorRoot = path.join(tmp, "usr-local-lib-nemoclaw"); - const pkillLog = path.join(tmp, "pkill.log"); - const recoveryLogPath = path.join(tmp, "gateway-recovery.log"); - fs.mkdirSync(stubsDir, { recursive: true }); - if (opts.validatorExists) { - fs.mkdirSync(validatorRoot, { recursive: true }); - fs.writeFileSync( - path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"), - "#!/usr/bin/env python3\nimport sys\nsys.exit(0)\n", - ); - } - writeStub( - stubsDir, - "python3", - `printf '[SECURITY] stub validator stderr for %s\\n' "$*" >&2\nexit ${opts.pythonExit}`, - ); - writeStub(stubsDir, "pkill", `printf '%s\\n' "$*" >> ${JSON.stringify(pkillLog)}\nexit 0`); - writeStub(stubsDir, "sleep", "exit 0"); - - const scriptPath = path.join(tmp, "guard.sh"); - const validatorPath = path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"); - const guardWithStubs = opts.guard - .replace(new RegExp(HERMES_SECRET_BOUNDARY_VALIDATOR_PATH, "g"), validatorPath) - .replace(/\/tmp\/gateway-recovery\.log/g, recoveryLogPath); - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - "set -u", - `export PATH=${JSON.stringify(stubsDir)}:/usr/bin:/bin`, - guardWithStubs, - "wait", - 'printf "REACHED_LAUNCH\\n"', - ].join("\n"), - { mode: 0o700 }, - ); - - try { - const result = spawnSync("bash", [scriptPath], { - encoding: "utf-8", - timeout: 10000, - env: { PATH: `${stubsDir}:/usr/bin:/bin`, HOME: tmp }, - }); - return { - status: result.status, - stdout: result.stdout, - stderr: result.stderr, - pkillCalls: fs.existsSync(pkillLog) - ? fs.readFileSync(pkillLog, "utf-8").trim().split("\n").filter(Boolean) - : [], - recoveryLog: fs.existsSync(recoveryLogPath) - ? fs.readFileSync(recoveryLogPath, "utf-8") - : "", - }; - } finally { - removeTempDir(tmp); - } - } - - it("env-file guard exits 1, kills hermes processes, and persists [SECURITY] to the recovery log when python validator fails", { - timeout: 15_000, - }, () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryGuard(), - pythonExit: 1, - validatorExists: true, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("REACHED_LAUNCH"); - const gatewayKills = result.pkillCalls.filter( - (line) => line.includes("[h]ermes") && line.includes("gateway"), - ); - const dashboardKills = result.pkillCalls.filter( - (line) => line.includes("[h]ermes") && line.includes("dashboard"), - ); - expect(gatewayKills.length).toBeGreaterThanOrEqual(2); - expect(dashboardKills.length).toBeGreaterThanOrEqual(2); - expect(result.recoveryLog).toContain("[SECURITY]"); - expect(result.stderr).toContain("[SECURITY]"); - }); - - it("env-file guard passes through and lets the launch proceed when python validator succeeds", () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryGuard(), - pythonExit: 0, - validatorExists: true, - }); - expect(result.status).toBe(0); - expect(result.stdout).toContain("REACHED_LAUNCH"); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.pkillCalls.length).toBe(0); - }); - - it("env-file guard refuses recovery when the validator script is absent", () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryGuard(), - pythonExit: 0, - validatorExists: false, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_VALIDATOR_MISSING"); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("REACHED_LAUNCH"); - expect(result.pkillCalls.length).toBeGreaterThanOrEqual(2); - expect(result.recoveryLog).toContain("[gateway-recovery] REFUSING"); - expect(result.recoveryLog).toContain("missing on this sandbox image"); - expect(result.stderr).toContain("[gateway-recovery] REFUSING"); - }); - - it("runtime-env guard exits 1 on python validator failure, kills processes, and logs [SECURITY]", { - timeout: 20_000, - }, () => { - const result = runGuard({ - guard: __testing.buildHermesRuntimeEnvBoundaryGuard(), - pythonExit: 1, - validatorExists: true, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("REACHED_LAUNCH"); - expect(result.pkillCalls.length).toBeGreaterThanOrEqual(2); - expect(result.recoveryLog).toContain("[SECURITY]"); - }); - - it("standalone env-file check exits 1, emits SECRET_BOUNDARY_REFUSED, kills processes when validator refuses", { - timeout: 15_000, - }, () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryStandaloneCheck(), - pythonExit: 1, - validatorExists: true, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_OK"); - expect(result.stdout).not.toContain("REACHED_LAUNCH"); - expect(result.pkillCalls.length).toBeGreaterThanOrEqual(2); - expect(result.stderr).toContain("[SECURITY]"); - }); - - it("standalone env-file check exits 0 and emits SECRET_BOUNDARY_OK when validator accepts", () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryStandaloneCheck(), - pythonExit: 0, - validatorExists: true, - }); - expect(result.status).toBe(0); - expect(result.stdout).toContain("SECRET_BOUNDARY_OK"); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.pkillCalls.length).toBe(0); - }); - - it("standalone env-file check refuses and kills processes when validator script is absent", () => { - const result = runGuard({ - guard: __testing.buildHermesEnvFileBoundaryStandaloneCheck(), - pythonExit: 0, - validatorExists: false, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_VALIDATOR_MISSING"); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("REACHED_LAUNCH"); - expect(result.pkillCalls.length).toBeGreaterThanOrEqual(2); - }); -}); - -describe("Hermes secret-boundary guard — full recovery script behaviour", () => { - function prepareRecoveryHarness(name: string) { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `nemoclaw-hermes-recovery-${name}-`)); - const stubsDir = path.join(tmp, "bin"); - const pkillLog = path.join(tmp, "pkill.log"); - const recoveryLogPath = path.join(tmp, "gateway-recovery.log"); - const hermesLaunchMarker = path.join(tmp, "hermes-launched"); - const gatewayLogPath = path.join(tmp, "gateway.log"); - const recoveryFallbackLog = path.join(tmp, "gateway-recovery-fallback.log"); - fs.mkdirSync(stubsDir, { recursive: true }); - return { - tmp, - stubsDir, - pkillLog, - recoveryLogPath, - hermesLaunchMarker, - gatewayLogPath, - recoveryFallbackLog, - ...createRecoveryPreloadHarnessPaths(tmp), - }; - } - - function stubBaselineUtilities(stubsDir: string, pkillLog: string, hermesLaunchMarker: string) { - writeStub(stubsDir, "pkill", `printf '%s\\n' "$*" >> ${JSON.stringify(pkillLog)}\nexit 0`); - writeStub(stubsDir, "pgrep", "exit 1"); - writeStub(stubsDir, "sleep", "exit 0"); - writeStub(stubsDir, "curl", 'printf "000"\nexit 0'); - writeStub(stubsDir, "hermes", `: > ${JSON.stringify(hermesLaunchMarker)}\n/bin/sleep 5`); - } - - function runRecovery( - opts: { - stubsDir: string; - validatorPath: string; - envFilePath?: string; - proxyEnvPath?: string; - recoveryLogPath: string; - gatewayLogPath: string; - recoveryFallbackLog: string; - tmp: string; - extraEnv?: NodeJS.ProcessEnv; - } & RecoveryPreloadHarnessPaths, - ) { - const recoveryScript = buildRecoveryScript(hermesAgent, 8642); - expect(recoveryScript).not.toBeNull(); - let stubbed = rewriteRecoveryPreloadPaths(recoveryScript!, opts) - .replace(new RegExp(HERMES_SECRET_BOUNDARY_VALIDATOR_PATH, "g"), opts.validatorPath) - .replace(/\/tmp\/gateway-recovery\.log/g, opts.recoveryLogPath) - .replace(/\/tmp\/gateway\.log/g, opts.gatewayLogPath) - .replace( - /_GATEWAY_LOG=\/tmp\/gateway-recovery\.log/g, - `_GATEWAY_LOG=${opts.recoveryFallbackLog}`, - ); - if (opts.envFilePath) { - stubbed = stubbed.replace(/\/sandbox\/\.hermes\/\.env/g, opts.envFilePath); - } - if (opts.proxyEnvPath) { - stubbed = stubbed.replace(/\/tmp\/nemoclaw-proxy-env\.sh/g, opts.proxyEnvPath); - } - - const scriptPath = path.join(opts.tmp, "recovery.sh"); - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - `export PATH=${JSON.stringify(opts.stubsDir)}:/usr/bin:/bin`, - stubbed, - ].join("\n"), - { mode: 0o700 }, - ); - return spawnSync("bash", [scriptPath], { - encoding: "utf-8", - timeout: 15000, - env: { - PATH: `${opts.stubsDir}:/usr/bin:/bin`, - HOME: opts.tmp, - ...opts.extraEnv, - }, - }); - } - - it("exits 1 with stubbed python3 returning [SECURITY] lines, kills hermes processes, never reaches the gateway launch", () => { - const harness = prepareRecoveryHarness("stub"); - const validatorRoot = path.join(harness.tmp, "usr-local-lib-nemoclaw"); - fs.mkdirSync(validatorRoot, { recursive: true }); - fs.writeFileSync( - path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"), - "#!/usr/bin/env python3\n", - ); - writeStub( - harness.stubsDir, - "python3", - 'printf "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values.\\n" >&2\nprintf "[SECURITY] TELEGRAM_BOT_TOKEN (line 2)\\n" >&2\nexit 1', - ); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - - try { - const result = runRecovery({ - ...harness, - validatorPath: path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"), - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("GATEWAY_PID="); - expect(result.stdout).not.toContain("ALREADY_RUNNING"); - expect(fs.existsSync(harness.hermesLaunchMarker)).toBe(false); - const pkillCalls = fs.readFileSync(harness.pkillLog, "utf-8"); - expect(pkillCalls).toContain("[h]ermes"); - expect(pkillCalls).toContain("gateway"); - expect(pkillCalls).toContain("dashboard"); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).toContain("[SECURITY] Refusing Hermes startup"); - expect(log).toContain("TELEGRAM_BOT_TOKEN (line 2)"); - } finally { - removeTempDir(harness.tmp); - } - }); - - it("refuses against an actual poisoned .env using the real Python validator", () => { - const harness = prepareRecoveryHarness("real-envfile"); - const envFile = path.join(harness.tmp, "hermes-dot-env"); - const realValidator = path.join( - import.meta.dirname, - "..", - "..", - "..", - "agents", - "hermes", - "validate-env-secret-boundary.py", - ); - fs.writeFileSync( - envFile, - "API_SERVER_PORT=18642\nTELEGRAM_BOT_TOKEN=1234567890:AAExample-RawSecretValueHere\n", - ); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - - try { - const result = runRecovery({ - ...harness, - validatorPath: realValidator, - envFilePath: envFile, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(fs.existsSync(harness.hermesLaunchMarker)).toBe(false); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).toContain("[SECURITY] Refusing Hermes startup"); - expect(log).toContain("TELEGRAM_BOT_TOKEN"); - expect(log).toContain("(line 2)"); - expect(log).not.toContain("1234567890:AAExample-RawSecretValueHere"); - } finally { - removeTempDir(harness.tmp); - } - }); - - it("refuses before /health can accept an already-serving poisoned gateway", () => { - const harness = prepareRecoveryHarness("health-already-serving"); - const envFile = path.join(harness.tmp, "hermes-dot-env"); - const curlLog = path.join(harness.tmp, "curl.log"); - const realValidator = path.join( - import.meta.dirname, - "..", - "..", - "..", - "agents", - "hermes", - "validate-env-secret-boundary.py", - ); - fs.writeFileSync( - envFile, - "API_SERVER_PORT=18642\nTELEGRAM_BOT_TOKEN=1234567890:AAExample-RawSecretValueHere\n", - ); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - writeStub( - harness.stubsDir, - "curl", - `printf '%s\\n' "$*" >> ${JSON.stringify(curlLog)}\nprintf "200"\nexit 0`, - ); - - try { - const result = runRecovery({ - ...harness, - validatorPath: realValidator, - envFilePath: envFile, - }); - // Unit-level HEALTH_DOWN evidence for #4957: the boundary refusal wins - // before recovery can trust a still-serving /health endpoint. - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stdout).not.toContain("ALREADY_RUNNING"); - expect(fs.existsSync(curlLog)).toBe(false); - expect(fs.existsSync(harness.hermesLaunchMarker)).toBe(false); - const pkillCalls = fs.readFileSync(harness.pkillLog, "utf-8"); - expect(pkillCalls).toContain("[h]ermes"); - expect(pkillCalls).toContain("gateway"); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).toContain("[SECURITY] Refusing Hermes startup"); - expect(log).toContain("TELEGRAM_BOT_TOKEN"); - expect(log).not.toContain("1234567890:AAExample-RawSecretValueHere"); - } finally { - removeTempDir(harness.tmp); - } - }); -}); diff --git a/src/lib/agent/runtime-hermes-secret-boundary-recovery.test.ts b/src/lib/agent/runtime-hermes-secret-boundary-recovery.test.ts deleted file mode 100644 index d6159ef25c2..00000000000 --- a/src/lib/agent/runtime-hermes-secret-boundary-recovery.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -// 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"; -import { HERMES_SECRET_BOUNDARY_VALIDATOR_PATH } from "./hermes-recovery-boundary"; -import { buildRecoveryScript } from "./runtime"; -import { - createRecoveryPreloadHarnessPaths, - type RecoveryPreloadHarnessPaths, - rewriteRecoveryPreloadPaths, -} from "../../../test/helpers/runtime-recovery-preload-test-helpers"; -import { hermesAgent } from "./hermes-recovery-boundary-fixtures"; - -function writeStub(dir: string, name: string, body: string) { - const stub = path.join(dir, name); - fs.writeFileSync(stub, `#!/usr/bin/env bash\n${body}\n`, { mode: 0o755 }); - return stub; -} - -function removeTempDir(dir: string) { - fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); -} - -function waitForPath(filePath: string, timeoutMs = 1000) { - const sleepView = new Int32Array(new SharedArrayBuffer(4)); - const deadline = Date.now() + timeoutMs; - while (!fs.existsSync(filePath) && Date.now() < deadline) { - Atomics.wait(sleepView, 0, 0, 10); - } - return fs.existsSync(filePath); -} - -const SHARED_PYTHON_STUB_BY_MODE = [ - 'if [ "$1" = "-c" ]; then', - " exit 0", - "fi", - 'mode="$2"', - 'if [ -n "${STUB_VALIDATOR_MODE_LOG:-}" ]; then', - ' printf "%s\\n" "$mode" >>"$STUB_VALIDATOR_MODE_LOG"', - "fi", - 'if [ "$mode" = "env-file" ]; then', - ' if [ "${STUB_ENVFILE_EXIT:-0}" = "1" ]; then', - ' printf "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values.\\n" >&2', - ' printf "[SECURITY] TELEGRAM_BOT_TOKEN (line 2)\\n" >&2', - " exit 1", - " fi", - " exit 0", - "fi", - 'if [ "$mode" = "runtime-env" ]; then', - ' if [ "${STUB_RUNTIMEENV_EXIT:-0}" = "1" ]; then', - ' printf "[SECURITY] Refusing Hermes startup because the process environment contains raw secret-shaped values.\\n" >&2', - ' printf "[SECURITY] TELEGRAM_BOT_TOKEN\\n" >&2', - " exit 1", - " fi", - " exit 0", - "fi", - "exit 2", -].join("\n"); - -describe("Hermes secret-boundary guard - runtime recovery behaviour", () => { - function prepareRecoveryHarness(name: string) { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `nemoclaw-hermes-recovery-${name}-`)); - const stubsDir = path.join(tmp, "bin"); - const pkillLog = path.join(tmp, "pkill.log"); - const recoveryLogPath = path.join(tmp, "gateway-recovery.log"); - const hermesLaunchMarker = path.join(tmp, "hermes-launched"); - const gatewayLogPath = path.join(tmp, "gateway.log"); - const recoveryFallbackLog = path.join(tmp, "gateway-recovery-fallback.log"); - fs.mkdirSync(stubsDir, { recursive: true }); - return { - tmp, - stubsDir, - pkillLog, - recoveryLogPath, - hermesLaunchMarker, - gatewayLogPath, - recoveryFallbackLog, - ...createRecoveryPreloadHarnessPaths(tmp), - }; - } - - function stubBaselineUtilities(stubsDir: string, pkillLog: string, hermesLaunchMarker: string) { - writeStub(stubsDir, "pkill", `printf '%s\\n' "$*" >> ${JSON.stringify(pkillLog)}\nexit 0`); - writeStub(stubsDir, "pgrep", "exit 1"); - writeStub(stubsDir, "sleep", "exit 0"); - writeStub(stubsDir, "curl", 'printf "000"\nexit 0'); - writeStub(stubsDir, "hermes", `: > ${JSON.stringify(hermesLaunchMarker)}\n/bin/sleep 5`); - } - - function runRecovery( - opts: { - stubsDir: string; - validatorPath: string; - envFilePath?: string; - proxyEnvPath?: string; - recoveryLogPath: string; - gatewayLogPath: string; - recoveryFallbackLog: string; - tmp: string; - extraEnv?: NodeJS.ProcessEnv; - } & RecoveryPreloadHarnessPaths, - ) { - const recoveryScript = buildRecoveryScript(hermesAgent, 8642); - expect(recoveryScript).not.toBeNull(); - let stubbed = rewriteRecoveryPreloadPaths(recoveryScript!, opts) - .replace(new RegExp(HERMES_SECRET_BOUNDARY_VALIDATOR_PATH, "g"), opts.validatorPath) - .replace(/\/tmp\/gateway-recovery\.log/g, opts.recoveryLogPath) - .replace(/\/tmp\/gateway\.log/g, opts.gatewayLogPath) - .replace( - /_GATEWAY_LOG=\/tmp\/gateway-recovery\.log/g, - `_GATEWAY_LOG=${opts.recoveryFallbackLog}`, - ); - stubbed = opts.envFilePath - ? stubbed.replace(/\/sandbox\/\.hermes\/\.env/g, opts.envFilePath) - : stubbed; - stubbed = opts.proxyEnvPath - ? stubbed.replace(/\/tmp\/nemoclaw-proxy-env\.sh/g, opts.proxyEnvPath) - : stubbed; - - const scriptPath = path.join(opts.tmp, "recovery.sh"); - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - `export PATH=${JSON.stringify(opts.stubsDir)}:/usr/bin:/bin`, - stubbed, - ].join("\n"), - { mode: 0o700 }, - ); - return spawnSync("bash", [scriptPath], { - encoding: "utf-8", - timeout: 15000, - env: { - PATH: `${opts.stubsDir}:/usr/bin:/bin`, - HOME: opts.tmp, - ...opts.extraEnv, - }, - }); - } - - it("refuses on runtime-env violation after sourcing proxy-env", () => { - const harness = prepareRecoveryHarness("runtime-env-stub"); - const validatorRoot = path.join(harness.tmp, "usr-local-lib-nemoclaw"); - const validatorPath = path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"); - fs.mkdirSync(validatorRoot, { recursive: true }); - fs.writeFileSync(validatorPath, "#!/usr/bin/env python3\n"); - const proxyEnvFile = path.join(harness.tmp, "nemoclaw-proxy-env.sh"); - fs.writeFileSync( - proxyEnvFile, - "export NODE_OPTIONS='--require=nemoclaw-sandbox-safety-net --require=nemoclaw-ciao-network-guard'\n", - ); - fs.chmodSync(proxyEnvFile, 0o444); - writeStub(harness.stubsDir, "python3", `${SHARED_PYTHON_STUB_BY_MODE}\n`); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - - try { - const result = runRecovery({ - ...harness, - validatorPath, - proxyEnvPath: proxyEnvFile, - extraEnv: { STUB_ENVFILE_EXIT: "0", STUB_RUNTIMEENV_EXIT: "1" }, - }); - expect(result.status).toBe(1); - expect(result.stdout).toContain("SECRET_BOUNDARY_REFUSED"); - expect(fs.existsSync(harness.hermesLaunchMarker)).toBe(false); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).toContain("[SECURITY] Refusing Hermes startup because the process environment"); - expect(log).toContain("TELEGRAM_BOT_TOKEN"); - } finally { - removeTempDir(harness.tmp); - } - }, 20_000); - - it("lets an env-file refusal win before a simultaneous hostile runtime env", () => { - const harness = prepareRecoveryHarness("dual-boundary-violation"); - const validatorRoot = path.join(harness.tmp, "usr-local-lib-nemoclaw"); - const validatorPath = path.join(validatorRoot, "validate-hermes-env-secret-boundary.py"); - const envFile = path.join(harness.tmp, "hermes-dot-env"); - const proxyEnvFile = path.join(harness.tmp, "nemoclaw-proxy-env.sh"); - const validatorModeLog = path.join(harness.tmp, "validator-modes.log"); - fs.mkdirSync(validatorRoot, { recursive: true }); - fs.writeFileSync(validatorPath, "#!/usr/bin/env python3\n"); - fs.writeFileSync( - envFile, - "API_SERVER_PORT=18642\nTELEGRAM_BOT_TOKEN=1234567890:AAExample-RawSecretValueHere\n", - ); - fs.writeFileSync( - proxyEnvFile, - [ - "export NODE_OPTIONS='--require=nemoclaw-sandbox-safety-net --require=nemoclaw-ciao-network-guard'", - "export SLACK_BOT_TOKEN=xoxb-example-hostile-runtime-secret", - "", - ].join("\n"), - ); - fs.chmodSync(proxyEnvFile, 0o444); - writeStub(harness.stubsDir, "python3", `${SHARED_PYTHON_STUB_BY_MODE}\n`); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - - try { - const result = runRecovery({ - ...harness, - validatorPath, - envFilePath: envFile, - proxyEnvPath: proxyEnvFile, - extraEnv: { - STUB_ENVFILE_EXIT: "1", - STUB_RUNTIMEENV_EXIT: "1", - STUB_VALIDATOR_MODE_LOG: validatorModeLog, - }, - }); - expect(result.status).toBe(1); - expect(result.stdout.match(/SECRET_BOUNDARY_REFUSED/g)).toHaveLength(1); - expect(fs.existsSync(harness.hermesLaunchMarker)).toBe(false); - expect(fs.readFileSync(validatorModeLog, "utf-8").trim().split("\n")).toEqual(["env-file"]); - const pkillCalls = fs.readFileSync(harness.pkillLog, "utf-8"); - expect(pkillCalls).toContain("[h]ermes"); - expect(pkillCalls).toContain("gateway"); - expect(pkillCalls).toContain("dashboard"); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).toContain("/sandbox/.hermes/.env contains raw secret-shaped values"); - expect(log).not.toContain("the process environment contains raw secret-shaped values"); - } finally { - removeTempDir(harness.tmp); - } - }, 20_000); - - it("does not import a raw secret from a metadata-safe proxy-env", () => { - const harness = prepareRecoveryHarness("runtime-env-real"); - const envFile = path.join(harness.tmp, "hermes-dot-env"); - const proxyEnvFile = path.join(harness.tmp, "nemoclaw-proxy-env.sh"); - const realValidator = path.join( - import.meta.dirname, - "..", - "..", - "..", - "agents", - "hermes", - "validate-env-secret-boundary.py", - ); - fs.writeFileSync(envFile, "API_SERVER_PORT=18642\n"); - fs.writeFileSync( - proxyEnvFile, - [ - "export NODE_OPTIONS='--require=nemoclaw-sandbox-safety-net --require=nemoclaw-ciao-network-guard'", - "export TELEGRAM_BOT_TOKEN=1234567890:AAExample-RawSecretValueHere", - "", - ].join("\n"), - ); - fs.chmodSync(proxyEnvFile, 0o444); - stubBaselineUtilities(harness.stubsDir, harness.pkillLog, harness.hermesLaunchMarker); - - try { - const result = runRecovery({ - ...harness, - validatorPath: realValidator, - envFilePath: envFile, - proxyEnvPath: proxyEnvFile, - }); - expect(result.status).toBe(0); - expect(waitForPath(harness.hermesLaunchMarker)).toBe(true); - expect(result.stdout).not.toContain("SECRET_BOUNDARY_REFUSED"); - expect(result.stderr).not.toContain("TELEGRAM_BOT_TOKEN"); - const proxyEnv = fs.readFileSync(proxyEnvFile, "utf-8"); - expect(proxyEnv).not.toContain("TELEGRAM_BOT_TOKEN"); - expect(proxyEnv).toContain(harness.preloadTmpSafetyNet); - expect(proxyEnv).toContain(harness.preloadTmpCiao); - const log = fs.readFileSync(harness.recoveryLogPath, "utf-8"); - expect(log).not.toContain("[SECURITY] Refusing Hermes startup"); - expect(log).not.toContain("TELEGRAM_BOT_TOKEN"); - expect(log).not.toContain("1234567890:AAExample-RawSecretValueHere"); - } finally { - removeTempDir(harness.tmp); - } - }, 20_000); -}); diff --git a/src/lib/agent/runtime-hermes-secret-boundary-shape.test.ts b/src/lib/agent/runtime-hermes-secret-boundary-shape.test.ts deleted file mode 100644 index b9c9a8a2b2f..00000000000 --- a/src/lib/agent/runtime-hermes-secret-boundary-shape.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Shape-only assertions for the Hermes recovery boundary guards. These tests -// check the generated shell string — what calls appear, in what order, and -// where the refusal markers land — without spawning a child shell. Behavioural -// tests that actually execute the synthesised script live in -// runtime-hermes-secret-boundary-behavioural.test.ts. - -import { describe, expect, it } from "vitest"; -import { HERMES_SECRET_BOUNDARY_VALIDATOR_PATH } from "./hermes-recovery-boundary"; -import { hermesAgent, minimalAgent } from "./hermes-recovery-boundary-fixtures"; -import { - buildHermesDashboardProcessRecoveryScript, - buildManualRecoveryCommand, - buildRecoveryScript, -} from "./runtime"; - -const VALIDATOR_PATH = HERMES_SECRET_BOUNDARY_VALIDATOR_PATH; - -describe("Hermes secret-boundary guard — generated shell shape", () => { - it("invokes the env-file validator before launching the Hermes gateway", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).not.toBeNull(); - expect(script).toContain(VALIDATOR_PATH); - expect(script).toContain(`python3 '${VALIDATOR_PATH}' env-file /sandbox/.hermes/.env`); - }); - - it("invokes the runtime-env validator after sourcing the generated recovery env", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).not.toBeNull(); - const proxyEnvIdx = script!.indexOf('. "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); - const runtimeGuardIdx = script!.indexOf(`python3 '${VALIDATOR_PATH}' runtime-env`); - const launchIdx = script!.indexOf("nohup"); - expect(proxyEnvIdx).toBeGreaterThanOrEqual(0); - expect(runtimeGuardIdx).toBeGreaterThanOrEqual(0); - expect(launchIdx).toBeGreaterThanOrEqual(0); - expect(proxyEnvIdx).toBeLessThan(runtimeGuardIdx); - expect(runtimeGuardIdx).toBeLessThan(launchIdx); - }); - - it("refuses the relaunch with SECRET_BOUNDARY_REFUSED on env-file violation", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).toContain("SECRET_BOUNDARY_REFUSED"); - expect(script).toContain("exit 1"); - }); - - it("env-file guard runs before the ALREADY_RUNNING health probe so a poisoned gateway gets stopped", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).not.toBeNull(); - const guardIdx = script!.indexOf(`python3 '${VALIDATOR_PATH}' env-file /sandbox/.hermes/.env`); - const probeIdx = script!.indexOf("ALREADY_RUNNING"); - expect(guardIdx).toBeGreaterThanOrEqual(0); - expect(probeIdx).toBeGreaterThanOrEqual(0); - expect(guardIdx).toBeLessThan(probeIdx); - }); - - it("kills running Hermes gateway and dashboard on boundary failure", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).toContain("[h]ermes[[:space:]]+gateway"); - expect(script).toContain("[h]ermes[[:space:]]+dashboard"); - expect(script).toContain("pkill -TERM -f"); - expect(script).toContain("pkill -KILL -f"); - }); - - it("refuses recovery on older sandbox images that lack the validator", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).toContain("SECRET_BOUNDARY_VALIDATOR_MISSING"); - expect(script).toContain("[gateway-recovery] REFUSING"); - expect(script).toContain("secret-boundary validator"); - expect(script).toContain("missing on this sandbox image"); - expect(script).toContain("exit 1"); - }); - - it("does not gate non-Hermes recovery on the Hermes-specific validator", () => { - const script = buildRecoveryScript(minimalAgent, 19000); - expect(script).not.toContain("validate-hermes-env-secret-boundary.py"); - expect(script).not.toContain("SECRET_BOUNDARY_REFUSED"); - }); - - it("guards the dashboard-only recovery path with env-file before generated sourcing and runtime-env after", () => { - const script = buildHermesDashboardProcessRecoveryScript({ - publicPort: 9119, - internalPort: 19119, - tuiEnabled: false, - }); - const envFileIdx = script.indexOf(`python3 '${VALIDATOR_PATH}' env-file /sandbox/.hermes/.env`); - const guardRecoveryIdx = script.indexOf("_nemoclaw_validate_recovery_proxy_env"); - const proxyEnvIdx = script.indexOf('. "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); - const bashrcIdx = script.indexOf("[ -f ~/.bashrc ] && . ~/.bashrc;"); - const runtimeIdx = script.indexOf(`python3 '${VALIDATOR_PATH}' runtime-env`); - const launchIdx = script.indexOf('"$AGENT_BIN" dashboard'); - expect(envFileIdx).toBeGreaterThanOrEqual(0); - expect(guardRecoveryIdx).toBeGreaterThanOrEqual(0); - expect(proxyEnvIdx).toBeGreaterThanOrEqual(0); - expect(bashrcIdx).toBeGreaterThanOrEqual(0); - expect(runtimeIdx).toBeGreaterThanOrEqual(0); - expect(launchIdx).toBeGreaterThanOrEqual(0); - expect(envFileIdx).toBeLessThan(proxyEnvIdx); - expect(guardRecoveryIdx).toBeLessThan(proxyEnvIdx); - expect(proxyEnvIdx).toBeLessThan(runtimeIdx); - expect(proxyEnvIdx).toBeLessThan(bashrcIdx); - expect(bashrcIdx).toBeLessThan(runtimeIdx); - expect(runtimeIdx).toBeLessThan(launchIdx); - expect(script).not.toContain("if [ -r /tmp/nemoclaw-proxy-env.sh ]; then ."); - expect(script).toContain("SECRET_BOUNDARY_REFUSED"); - }); - - it("guards manual Hermes recovery copy-paste command", () => { - const cmd = buildManualRecoveryCommand(hermesAgent, 8642); - expect(cmd).toContain(`python3 '${VALIDATOR_PATH}' env-file /sandbox/.hermes/.env`); - expect(cmd).toContain(`python3 '${VALIDATOR_PATH}' runtime-env`); - expect(cmd).toContain("SECRET_BOUNDARY_REFUSED"); - const guardIdx = cmd.indexOf(`python3 '${VALIDATOR_PATH}'`); - const launchIdx = cmd.indexOf("nohup hermes gateway run"); - expect(guardIdx).toBeGreaterThanOrEqual(0); - expect(launchIdx).toBeGreaterThanOrEqual(0); - expect(guardIdx).toBeLessThan(launchIdx); - }); - - it("does not gate the non-Hermes manual recovery command", () => { - const cmd = buildManualRecoveryCommand(minimalAgent, 19000); - expect(cmd).not.toContain("validate-hermes-env-secret-boundary.py"); - expect(cmd).not.toContain("SECRET_BOUNDARY_REFUSED"); - }); -}); diff --git a/src/lib/agent/runtime-recovery-preload.test.ts b/src/lib/agent/runtime-recovery-preload.test.ts index 5d889f4109a..9bc1a36cab8 100644 --- a/src/lib/agent/runtime-recovery-preload.test.ts +++ b/src/lib/agent/runtime-recovery-preload.test.ts @@ -7,7 +7,7 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { minimalAgent } from "./hermes-recovery-boundary-fixtures"; -import { buildOpenClawRecoveryScript, buildRecoveryScript } from "./runtime"; +import { buildRecoveryScript } from "./runtime"; import { buildGatewayGuardRecoveryLines, GATEWAY_PRELOAD_GUARDS } from "./runtime-recovery-preload"; const [SAFETY_NET_GUARD, CIAO_GUARD] = GATEWAY_PRELOAD_GUARDS; @@ -402,73 +402,58 @@ describe("gateway recovery preload repair", () => { expect(result.files.gatewayLog).toContain("unsafe mode=664"); }); - it("wires the repair helper into both recovery script builders", () => { - const genericScript = buildRecoveryScript(minimalAgent, 19000); - const openClawScript = buildOpenClawRecoveryScript(18789); - for (const script of [genericScript, openClawScript]) { - expect(script).toContain("restoring library guards from packaged preloads"); - expect(script).toContain("/usr/local/lib/nemoclaw/preloads/sandbox-safety-net.js"); - expect(script).toContain("/usr/local/lib/nemoclaw/preloads/ciao-network-guard.js"); - expect(script).not.toContain("gateway launching without library guards"); - } + it("wires the repair helper into custom-agent recovery", () => { + const script = buildRecoveryScript(minimalAgent, 19000); + expect(script).toContain("restoring library guards from packaged preloads"); + expect(script).toContain("/usr/local/lib/nemoclaw/preloads/sandbox-safety-net.js"); + expect(script).toContain("/usr/local/lib/nemoclaw/preloads/ciao-network-guard.js"); + expect(script).not.toContain("gateway launching without library guards"); }); it("validates proxy-env.sh before sourcing it in gateway recovery scripts", () => { - for (const script of [ - buildRecoveryScript(minimalAgent, 19000), - buildOpenClawRecoveryScript(18789), - ]) { - expect(script).not.toContain("[ -r /tmp/nemoclaw-proxy-env.sh ]; then ."); - const validateIdx = script!.indexOf( - "_nemoclaw_validate_recovery_proxy_env /tmp/nemoclaw-proxy-env.sh", - ); - const sourceIdx = script!.indexOf('then . "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); - expect(validateIdx).toBeGreaterThanOrEqual(0); - expect(sourceIdx).toBeGreaterThanOrEqual(0); - expect(validateIdx).toBeLessThan(sourceIdx); - } + const script = buildRecoveryScript(minimalAgent, 19000); + expect(script).not.toContain("[ -r /tmp/nemoclaw-proxy-env.sh ]; then ."); + const validateIdx = script!.indexOf( + "_nemoclaw_validate_recovery_proxy_env /tmp/nemoclaw-proxy-env.sh", + ); + const sourceIdx = script!.indexOf('then . "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); + expect(validateIdx).toBeGreaterThanOrEqual(0); + expect(sourceIdx).toBeGreaterThanOrEqual(0); + expect(validateIdx).toBeLessThan(sourceIdx); }); it("validates proxy-env.sh before shell init hooks can source it", () => { - for (const script of [ - buildRecoveryScript(minimalAgent, 19000), - buildOpenClawRecoveryScript(18789), - ]) { - expect(script).not.toBeNull(); - const validateIdx = script!.indexOf( - "_nemoclaw_validate_recovery_proxy_env /tmp/nemoclaw-proxy-env.sh", - ); - const bashrcIdx = script!.indexOf("[ -f ~/.bashrc ] && . ~/.bashrc;"); - const healthIdx = script!.indexOf("_GW_CODE="); - expect(validateIdx).toBeGreaterThanOrEqual(0); - expect(bashrcIdx).toBeGreaterThanOrEqual(0); - expect(healthIdx).toBeGreaterThanOrEqual(0); - expect(validateIdx).toBeLessThan(bashrcIdx); - expect(bashrcIdx).toBeLessThan(healthIdx); - } + const script = buildRecoveryScript(minimalAgent, 19000); + expect(script).not.toBeNull(); + const validateIdx = script!.indexOf( + "_nemoclaw_validate_recovery_proxy_env /tmp/nemoclaw-proxy-env.sh", + ); + const bashrcIdx = script!.indexOf("[ -f ~/.bashrc ] && . ~/.bashrc;"); + const healthIdx = script!.indexOf("_GW_CODE="); + expect(validateIdx).toBeGreaterThanOrEqual(0); + expect(bashrcIdx).toBeGreaterThanOrEqual(0); + expect(healthIdx).toBeGreaterThanOrEqual(0); + expect(validateIdx).toBeLessThan(bashrcIdx); + expect(bashrcIdx).toBeLessThan(healthIdx); }); it("repairs guard files before health probing and the ALREADY_RUNNING fast path", () => { - for (const script of [ - buildRecoveryScript(minimalAgent, 19000), - buildOpenClawRecoveryScript(18789), - ]) { - expect(script).not.toBeNull(); - const safetyNetStageIdx = script!.indexOf( - `_nemoclaw_stage_recovery_preload ${SAFETY_NET_GUARD.tmpPath} ${SAFETY_NET_GUARD.sourcePath}`, - ); - const ciaoStageIdx = script!.indexOf( - `_nemoclaw_stage_recovery_preload ${CIAO_GUARD.tmpPath} ${CIAO_GUARD.sourcePath}`, - ); - const healthIdx = script!.indexOf("_GW_CODE="); - const alreadyRunningIdx = script!.indexOf("echo ALREADY_RUNNING; exit 0"); - expect(safetyNetStageIdx).toBeGreaterThanOrEqual(0); - expect(ciaoStageIdx).toBeGreaterThanOrEqual(0); - expect(healthIdx).toBeGreaterThanOrEqual(0); - expect(alreadyRunningIdx).toBeGreaterThanOrEqual(0); - expect(safetyNetStageIdx).toBeLessThan(healthIdx); - expect(ciaoStageIdx).toBeLessThan(healthIdx); - expect(healthIdx).toBeLessThan(alreadyRunningIdx); - } + const script = buildRecoveryScript(minimalAgent, 19000); + expect(script).not.toBeNull(); + const safetyNetStageIdx = script!.indexOf( + `_nemoclaw_stage_recovery_preload ${SAFETY_NET_GUARD.tmpPath} ${SAFETY_NET_GUARD.sourcePath}`, + ); + const ciaoStageIdx = script!.indexOf( + `_nemoclaw_stage_recovery_preload ${CIAO_GUARD.tmpPath} ${CIAO_GUARD.sourcePath}`, + ); + const healthIdx = script!.indexOf("_GW_CODE="); + const alreadyRunningIdx = script!.indexOf("echo ALREADY_RUNNING; exit 0"); + expect(safetyNetStageIdx).toBeGreaterThanOrEqual(0); + expect(ciaoStageIdx).toBeGreaterThanOrEqual(0); + expect(healthIdx).toBeGreaterThanOrEqual(0); + expect(alreadyRunningIdx).toBeGreaterThanOrEqual(0); + expect(safetyNetStageIdx).toBeLessThan(healthIdx); + expect(ciaoStageIdx).toBeLessThan(healthIdx); + expect(healthIdx).toBeLessThan(alreadyRunningIdx); }); }); diff --git a/src/lib/agent/runtime-terminal.test.ts b/src/lib/agent/runtime-terminal.test.ts index 5a6d3e2ca2c..0279afb8202 100644 --- a/src/lib/agent/runtime-terminal.test.ts +++ b/src/lib/agent/runtime-terminal.test.ts @@ -5,12 +5,7 @@ import { describe, expect, it } from "vitest"; import type { AgentDefinition } from "./defs"; import { loadAgent } from "./defs"; // Import source directly so tests cannot pass against a stale build. -import { - buildManualRecoveryCommand, - buildRecoveryScript, - getTerminalCommand, - TERMINAL_AGENT_RECOVERY_SCRIPT, -} from "./runtime"; +import { buildRecoveryScript, getTerminalCommand, TERMINAL_AGENT_RECOVERY_SCRIPT } from "./runtime"; const terminalAgent = { name: "terminal-agent", @@ -31,7 +26,6 @@ describe("terminal agent runtime helpers", () => { it("resolves terminal launch commands without synthesizing gateway recovery", () => { expect(getTerminalCommand(terminalAgent)).toBe("terminal-agent"); expect(getTerminalCommand(terminalAgent, "headless")).toBe("terminal-agent -n"); - expect(buildManualRecoveryCommand(terminalAgent, 18789)).toBe("terminal-agent"); }); it("resolves Deep Agents Code interactive and headless commands from the real manifest", () => { @@ -39,6 +33,5 @@ describe("terminal agent runtime helpers", () => { expect(getTerminalCommand(deepAgentsCode, "interactive")).toBe("dcode"); expect(getTerminalCommand(deepAgentsCode, "headless")).toBe("dcode -n"); - expect(buildManualRecoveryCommand(deepAgentsCode, 18789)).toBe("dcode"); }); }); diff --git a/src/lib/agent/runtime.test.ts b/src/lib/agent/runtime.test.ts index 6c98edc1881..9b591c941b6 100644 --- a/src/lib/agent/runtime.test.ts +++ b/src/lib/agent/runtime.test.ts @@ -4,12 +4,7 @@ import { describe, expect, it } from "vitest"; import type { AgentDefinition } from "./defs"; // Import source directly so tests cannot pass against a stale build. -import { - buildHermesDashboardProcessRecoveryScript, - buildManualRecoveryCommand, - buildOpenClawRecoveryScript, - buildRecoveryScript, -} from "./runtime"; +import { buildRecoveryScript } from "./runtime"; function makeAgent(overrides: Partial = {}): AgentDefinition { return { @@ -75,10 +70,14 @@ function toJsRegex(pattern: string): RegExp { } describe("buildRecoveryScript", () => { - it("returns null for null agent (OpenClaw inline script handles it)", () => { + it("returns null for null agent because PID 1 owns OpenClaw recovery", () => { expect(buildRecoveryScript(null, 18789)).toBeNull(); }); + it("returns null for Hermes because PID 1 owns Hermes recovery", () => { + expect(buildRecoveryScript(hermesAgent, 8642)).toBeNull(); + }); + it("embeds the port in the gateway launch command (#1925)", () => { const script = buildRecoveryScript(minimalAgent, 19000); expect(script).toContain("--port 19000"); @@ -89,95 +88,18 @@ describe("buildRecoveryScript", () => { expect(script).toContain("--port 18789"); }); + it("derives the recovery port from agent metadata when omitted", () => { + const script = buildRecoveryScript(minimalAgent); + expect(script).toContain("--port 19000"); + expect(script).not.toContain("--port undefined"); + }); + it("launches the default gateway command through the validated agent binary", () => { const script = buildRecoveryScript(minimalAgent, 19000); expect(script).toContain("command -v 'test-agent'"); expect(script).toContain('"$AGENT_BIN" gateway run --port 19000'); }); - it("omits --port for Hermes so config.yaml controls the internal listen port (#2426)", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).toContain("export HERMES_HOME=/sandbox/.hermes"); - expect(script).toContain("HERMES_HOME=/sandbox/.hermes"); - expect(script).not.toContain("DISCORD_PROXY="); - expect(script).not.toContain("PYTHONPATH=/opt/nemoclaw-hermes-discord-preload"); - expect(script).not.toContain("HTTPS_PROXY=http://127.0.0.1:3129"); - expect(script).not.toContain("nemoclaw-decode-proxy"); - expect(script).not.toContain("nemoclaw-discord-facade"); - expect(script).not.toContain("NEMOCLAW_DISCORD_FACADE_URL"); - expect(script).toContain('"$AGENT_BIN" gateway run'); - expect(script).not.toContain('"$AGENT_BIN" gateway run --port 8642'); - expect(script).not.toContain("hermes gateway run --port 8642"); - }); - - it("relaunches the optional Hermes dashboard during recovery", () => { - const script = buildRecoveryScript(hermesAgent, 8642, { - hermesDashboard: { publicPort: 9119, internalPort: 19119, tuiEnabled: true }, - }); - expect(script).toContain("/tmp/hermes-dashboard.log"); - expect(script).toContain("_HERMES_DASHBOARD_HOME=/sandbox/.hermes/dashboard-home"); - expect(script).toContain("/usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py"); - expect(script).toContain("${_HERMES_DASHBOARD_HOME}/gateway_state.json"); - expect(script).toContain('HERMES_HOME="$_HERMES_DASHBOARD_HOME"'); - expect(script).not.toContain("HERMES_HOME=/sandbox/.hermes nohup"); - expect(script).toContain( - '"$AGENT_BIN" dashboard --host 127.0.0.1 --port 19119 --skip-build --no-open --tui', - ); - expect(script).toContain("DASHBOARD_PID=$DPID"); - expect(script).toContain("DASHBOARD_FAILED"); - }); - - it("can recover only the optional Hermes dashboard process", () => { - const script = buildHermesDashboardProcessRecoveryScript({ - publicPort: 9119, - internalPort: 19119, - tuiEnabled: false, - }); - const validationIndex = script.indexOf( - "_nemoclaw_validate_recovery_proxy_env /tmp/nemoclaw-proxy-env.sh", - ); - const sourceIndex = script.indexOf('. "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); - expect(validationIndex).toBeGreaterThanOrEqual(0); - expect(sourceIndex).toBeGreaterThan(validationIndex); - expect(script).toContain('. "$_NEMOCLAW_RECOVERY_SOURCE_ENV"'); - expect(script).toContain("/usr/local/bin/hermes"); - expect(script).toContain("_HERMES_DASHBOARD_HOME=/sandbox/.hermes/dashboard-home"); - expect(script).toContain("/usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py"); - expect(script).toContain('HERMES_HOME="$_HERMES_DASHBOARD_HOME"'); - expect(script).toContain( - '"$AGENT_BIN" dashboard --host 127.0.0.1 --port 19119 --skip-build --no-open', - ); - expect(script).not.toContain("HERMES_HOME=/sandbox/.hermes nohup"); - expect(script).not.toContain("--tui"); - }); - - it("does not launch a Hermes decode proxy during recovery", () => { - const script = buildRecoveryScript(hermesAgent, 8642); - expect(script).not.toContain("/usr/local/bin/nemoclaw-decode-proxy"); - expect(script).not.toContain("/opt/hermes/.venv/bin/python"); - expect(script).not.toContain("nemoclaw-discord-facade"); - }); - - it("does not wait for removed Hermes bridge ports during recovery", () => { - const recoveryScript = buildRecoveryScript(hermesAgent, 8642); - expect(recoveryScript).not.toBeNull(); - for (const script of [recoveryScript!, buildManualRecoveryCommand(hermesAgent, 8642)]) { - expect(script).not.toContain("127\\.0\\.0\\.1:3129"); - expect(script).not.toContain('grep -q "127.0.0.1:3129"'); - expect(script).not.toContain('grep -q "127.0.0.1:3130"'); - expect(script).not.toContain("do ! command -v ss >/dev/null 2>&1 || ss -tln"); - } - }); - - it("does not relaunch the removed Hermes Discord facade during recovery", () => { - const recoveryScript = buildRecoveryScript(hermesAgent, 8642); - expect(recoveryScript).not.toBeNull(); - for (const script of [recoveryScript!, buildManualRecoveryCommand(hermesAgent, 8642)]) { - expect(script).not.toContain("discord-facade"); - expect(script).not.toContain("DISCORD_FACADE_LOG"); - } - }); - it("falls back to openclaw gateway run when gateway_command is absent", () => { const agent = makeAgent({ gateway_command: undefined }); const script = buildRecoveryScript(agent, 19000); @@ -198,17 +120,6 @@ describe("buildRecoveryScript", () => { expect(script).toContain("nohup custom-launch --mode recovery --port 19000"); }); - it("does not append the external forward port to custom Hermes launch commands (#2426)", () => { - const agent = makeAgent({ - ...hermesAgent, - gateway_command: "hermes gateway run --profile recovery", - }); - const script = buildRecoveryScript(agent, 8642); - expect(script).toContain("nohup env HERMES_HOME=/sandbox/.hermes"); - expect(script).toContain("hermes gateway run --profile recovery"); - expect(script).not.toContain("hermes gateway run --profile recovery --port 8642"); - }); - // Regression coverage for #2478. The recovery script must validate // /tmp/nemoclaw-proxy-env.sh, then source a generated recovery env carrying // the critical NODE_OPTIONS library guards. The pre-fix recovery path @@ -282,12 +193,6 @@ describe("buildRecoveryScript", () => { expect(logSelectionIdx).toBeLessThan(warnIdx); }); - it("stops recovery when hardened log setup fails", () => { - const script = buildOpenClawRecoveryScript(18789); - expect(script).toContain(" /tmp/gateway.log 'gateway' || exit 1;"); - expect(script).toContain(" /tmp/auto-pair.log 'sandbox' || exit 1;"); - }); - it("appends (not truncates) gateway.log on launch so warnings survive", () => { const script = buildRecoveryScript(minimalAgent, 19000); // Truncating with `>` wipes the [gateway-recovery] WARNING that the @@ -297,62 +202,6 @@ describe("buildRecoveryScript", () => { expect(script).not.toMatch(/[^>]> \/tmp\/gateway\.log 2>&1 &/); }); - it("preserves an existing gateway.log and has a writable fallback log", () => { - const script = buildOpenClawRecoveryScript(18789); - expect(script).not.toContain("rm -f /tmp/gateway.log"); - expect(script).toContain("_GATEWAY_LOG=/tmp/gateway.log"); - expect(script).toContain("_GATEWAY_LOG=/tmp/gateway-recovery.log"); - expect(script).toContain('_nemoclaw_recovery_log "$_W"'); - expect(script).toContain('tail -5 "$_GATEWAY_LOG"'); - expect(script).not.toContain('echo "$_W" >> /tmp/gateway.log'); - expect(script).not.toContain("cat /tmp/gateway.log"); - }); - - it("rejects a symlinked gateway.log before preparing the log", () => { - const script = buildOpenClawRecoveryScript(18789); - const noFollowIdx = script.indexOf("O_NOFOLLOW"); - const openIdx = script.indexOf("os.open(path, flags, 0o644)"); - const fchownIdx = script.indexOf("os.fchown(fd"); - expect(script).toContain("refusing to prepare symlinked /tmp/gateway.log"); - expect(script).toContain("sys.exit(1)"); - expect(script).not.toContain(": > /tmp/gateway.log"); - expect(script).not.toContain("chown 'gateway:gateway' /tmp/gateway.log"); - expect(noFollowIdx).toBeGreaterThanOrEqual(0); - expect(openIdx).toBeGreaterThanOrEqual(0); - expect(fchownIdx).toBeGreaterThanOrEqual(0); - expect(noFollowIdx).toBeLessThan(openIdx); - expect(openIdx).toBeLessThan(fchownIdx); - }); - - it("prepares gateway.log for the real gateway-owned sandbox log", () => { - const script = buildOpenClawRecoveryScript(18789); - expect(script).toContain("os.fchown(fd"); - expect(script).toContain("pw.pw_gid"); - expect(script).not.toContain("grp.getgrnam"); - expect(script).toContain("owner_mode = 0o644"); - expect(script).toContain("os.fchmod(fd, owner_mode)"); - expect(script).toContain("/tmp/gateway.log 'gateway'"); - expect(script).toContain("gosu 'gateway'"); - }); - - it("terminates the conditional launch branch before capturing the gateway pid", () => { - const script = buildOpenClawRecoveryScript(18789); - expect(script).toContain(" fi; GPID=$!"); - expect(script).not.toContain(" fi GPID=$!"); - }); - - it("prepares auto-pair.log without unlinking or following symlinks", () => { - const script = buildOpenClawRecoveryScript(18789); - expect(script).toContain("refusing to prepare symlinked /tmp/auto-pair.log"); - expect(script).toContain("/tmp/auto-pair.log 'sandbox'"); - expect(script).toContain("owner_mode = 0o600"); - expect(script).not.toContain("rm -f /tmp/auto-pair.log"); - expect(script).not.toContain(": > /tmp/auto-pair.log"); - expect(script).not.toContain("touch /tmp/auto-pair.log"); - expect(script).not.toContain("chown sandbox:sandbox /tmp/auto-pair.log"); - expect(script).not.toContain("chmod 600 /tmp/auto-pair.log"); - }); - it("does not force non-OpenClaw agents to run as the gateway user", () => { const script = buildRecoveryScript(minimalAgent, 19000); expect(script).not.toContain("chown gateway:gateway /tmp/gateway.log"); @@ -362,54 +211,3 @@ describe("buildRecoveryScript", () => { }); }); }); - -describe("buildManualRecoveryCommand (#2426)", () => { - it("backgrounds non-Hermes gateways with nohup and the requested port", () => { - const cmd = buildManualRecoveryCommand(minimalAgent, 19000); - expect(cmd).toContain("nohup test-agent gateway run --port 19000"); - expect(cmd).toContain('>> "$_GATEWAY_LOG" 2>&1 &'); - }); - - it("selects a writable gateway log before launching", () => { - const cmd = buildManualRecoveryCommand(minimalAgent, 19000); - expect(cmd).toContain("_GATEWAY_LOG=/tmp/gateway.log"); - expect(cmd).toContain("_GATEWAY_LOG=/tmp/gateway-recovery.log"); - expect(cmd).not.toContain(">/tmp/gateway.log 2>&1"); - }); - - it("uses the same preload guard before the manual nohup launch", () => { - const cmd = buildManualRecoveryCommand(minimalAgent, 19000); - const guardIndex = cmd.indexOf("_GUARDS_MISSING"); - const launchIndex = cmd.indexOf("nohup test-agent gateway run --port 19000"); - expect(cmd).toContain("nemoclaw-sandbox-safety-net"); - expect(cmd).toContain("nemoclaw-ciao-network-guard"); - expect(cmd).toContain("refusing unguarded gateway relaunch"); - expect(guardIndex).toBeGreaterThanOrEqual(0); - expect(launchIndex).toBeGreaterThan(guardIndex); - }); - - it("omits --port for Hermes and uses the current Hermes home", () => { - const cmd = buildManualRecoveryCommand(hermesAgent, 8642); - expect(cmd).toContain("HERMES_HOME=/sandbox/.hermes"); - expect(cmd).not.toContain("DISCORD_PROXY="); - expect(cmd).not.toContain("PYTHONPATH=/opt/nemoclaw-hermes-discord-preload"); - expect(cmd).not.toContain("HTTPS_PROXY=http://127.0.0.1:3129"); - expect(cmd).not.toContain("nemoclaw-decode-proxy"); - expect(cmd).not.toContain("nemoclaw-discord-facade"); - expect(cmd).not.toContain("NEMOCLAW_DISCORD_FACADE_URL"); - expect(cmd).toContain("nohup hermes gateway run"); - expect(cmd).not.toContain("--port 8642"); - expect(cmd).not.toContain("/sandbox/.hermes-data"); - }); - - it("derives the default gateway command from binary_path when gateway_command is blank", () => { - const agent = makeAgent({ gateway_command: " " }); - const cmd = buildManualRecoveryCommand(agent, 19000); - expect(cmd).toContain("nohup '/usr/local/bin/test-agent' gateway run --port 19000"); - }); - - it("falls back to openclaw gateway run for a null agent", () => { - const cmd = buildManualRecoveryCommand(null, 18789); - expect(cmd).toContain("nohup '/usr/local/bin/openclaw' gateway run --port 18789"); - }); -}); diff --git a/src/lib/agent/runtime.ts b/src/lib/agent/runtime.ts index 9f524e12c92..edf805978dd 100644 --- a/src/lib/agent/runtime.ts +++ b/src/lib/agent/runtime.ts @@ -8,25 +8,18 @@ // defaults that match the hardcoded OpenClaw values on main. import { DASHBOARD_PORT } from "../core/ports"; -import { shellQuote } from "../runner"; import * as onboardSession from "../state/onboard-session"; import * as registry from "../state/registry"; import { type AgentDefinition, isTerminalAgent, loadAgent } from "./defs"; -import { - buildHermesEnvFileBoundaryGuard, - buildHermesRuntimeEnvBoundaryGuard, -} from "./hermes-recovery-boundary"; -import { buildGatewayGuardRecoveryLines } from "./runtime-recovery-preload"; +import { getTerminalCommand } from "./gateway-restart-scripts"; -export const TERMINAL_AGENT_RECOVERY_SCRIPT = Object.freeze({ kind: "terminal" } as const); - -export type AgentRecoveryScript = string | typeof TERMINAL_AGENT_RECOVERY_SCRIPT | null; - -export function isTerminalAgentRecoveryScript( - script: AgentRecoveryScript, -): script is typeof TERMINAL_AGENT_RECOVERY_SCRIPT { - return script === TERMINAL_AGENT_RECOVERY_SCRIPT; -} +export { + type AgentRecoveryScript, + buildRecoveryScript, + getTerminalCommand, + isTerminalAgentRecoveryScript, + TERMINAL_AGENT_RECOVERY_SCRIPT, +} from "./gateway-restart-scripts"; /** * Resolve the agent for a sandbox. Checks the per-sandbox registry first @@ -74,270 +67,6 @@ export function hasGatewayRuntime( return !isTerminalAgent(agent); } -export function getTerminalCommand( - agent: AgentDefinition | null, - mode: "interactive" | "headless" = "interactive", -): string | null { - if (!agent || !isTerminalAgent(agent)) return null; - if (mode === "headless") return agent.runtime?.headless_command ?? null; - return agent.runtime?.interactive_command ?? agent.runtime?.headless_command ?? null; -} - -function escapeEre(value: string): string { - return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); -} - -function escapeCharClass(value: string): string { - return value.replace(/[\\\]\[\^\-]/g, "\\$&"); -} - -function selfSafeGatewayProcessPattern(command: string): string { - const [executable = "", ...args] = command.trim().split(/\s+/).filter(Boolean); - const [first = "", ...rest] = Array.from(executable); - if (!first) return ""; - const executablePattern = `[${escapeCharClass(first)}]${escapeEre(rest.join(""))}`; - const commandPattern = [executablePattern, ...args.map(escapeEre)].join("[[:space:]]+"); - return `${commandPattern}([[:space:]]|$)`; -} - -function buildNoFollowLogSetupCommand( - path: string, - logOwnerUser?: string, - ownerMode = "0o644", -): string { - const displayPath = path.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); - const prepareLog = [ - "import errno, os, pwd, stat, sys", - "path = sys.argv[1]", - "owner = sys.argv[2] if len(sys.argv) > 2 else ''", - `owner_mode = ${ownerMode}`, - "fallback_mode = 0o600", - "flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)", - "try:", - " fd = os.open(path, flags, 0o644)", - "except OSError as exc:", - " if exc.errno == errno.ELOOP:", - ` print('[gateway-recovery] ERROR: refusing to prepare symlinked ${displayPath}', file=sys.stderr)`, - " sys.exit(1)", - " if exc.errno in (errno.EACCES, errno.EPERM):", - ` print('[gateway-recovery] ERROR: ${displayPath} is not writable by recovery user', file=sys.stderr)`, - " sys.exit(0)", - ` print(f'[gateway-recovery] ERROR: cannot prepare ${displayPath}: {exc}', file=sys.stderr)`, - " sys.exit(1)", - "try:", - " if not stat.S_ISREG(os.fstat(fd).st_mode):", - ` print('[gateway-recovery] ERROR: ${displayPath} is not a regular file', file=sys.stderr)`, - " sys.exit(1)", - " if owner and os.geteuid() == 0:", - " try:", - " pw = pwd.getpwnam(owner)", - " except KeyError:", - " os.fchmod(fd, fallback_mode)", - " else:", - " os.fchown(fd, pw.pw_uid, pw.pw_gid)", - " os.fchmod(fd, owner_mode)", - " else:", - " os.fchmod(fd, fallback_mode)", - "finally:", - " os.close(fd)", - ].join("\n"); - return [ - "python3", - "-c", - shellQuote(prepareLog), - path, - ...(logOwnerUser ? [shellQuote(logOwnerUser)] : []), - ].join(" "); -} - -function buildGatewayLogSetup(includeAutoPairLog = false, logOwnerUser?: string): string[] { - const lines = [`${buildNoFollowLogSetupCommand("/tmp/gateway.log", logOwnerUser)} || exit 1;`]; - if (includeAutoPairLog) { - lines.push( - `${buildNoFollowLogSetupCommand("/tmp/auto-pair.log", "sandbox", "0o600")} || exit 1;`, - ); - } - return lines; -} - -function buildGatewayLogSelection(): string { - return '_GATEWAY_LOG=/tmp/gateway.log; if ! : >> "$_GATEWAY_LOG" 2>/dev/null; then _GATEWAY_LOG=/tmp/gateway-recovery.log; : >> "$_GATEWAY_LOG" 2>/dev/null || true; fi;'; -} - -function gatewayGuardRefusalCommand(): string { - return '[ "$_GUARDS_MISSING" = "1" ] && { _E="[gateway-recovery] ERROR: NODE_OPTIONS missing safety-net preload or ciao preload after trusted recovery - refusing unguarded gateway relaunch (#2478/#2701)"; echo "$_E" >&2; echo "$_E" >> "$_GATEWAY_LOG"; exit 1; };'; -} - -function gatewayLaunchCommand(command: string, runAsUser?: string): string { - const logSelection = buildGatewayLogSelection(); - const userLaunch = `nohup ${command} >> "$_GATEWAY_LOG" 2>&1 &`; - if (!runAsUser) { - return `${logSelection} ${userLaunch}`; - } - return `${logSelection} if [ "$(id -u)" = "0" ] && command -v gosu >/dev/null 2>&1 && id ${shellQuote(runAsUser)} >/dev/null 2>&1; then nohup gosu ${shellQuote(runAsUser)} ${command} >> "$_GATEWAY_LOG" 2>&1 & else ${userLaunch} fi;`; -} - -function hermesGatewayEnvPrefix(): string { - return "HERMES_HOME=/sandbox/.hermes"; -} - -function hermesDashboardEnvPrefix(): string { - return 'HERMES_HOME="$_HERMES_DASHBOARD_HOME" GATEWAY_HEALTH_URL="http://127.0.0.1:$_HERMES_DASHBOARD_GATEWAY_PORT"'; -} - -export interface HermesDashboardRecoveryConfig { - publicPort: number; - internalPort: number; - tuiEnabled?: boolean; -} - -function buildHermesDashboardRecoveryLines(config: HermesDashboardRecoveryConfig): string[] { - const tuiFlag = config.tuiEnabled ? " --tui" : ""; - const dashboardLogSelection = - '_DASHBOARD_LOG=/tmp/hermes-dashboard.log; if ! : >> "$_DASHBOARD_LOG" 2>/dev/null; then _DASHBOARD_LOG=/tmp/hermes-dashboard-recovery.log; : >> "$_DASHBOARD_LOG" 2>/dev/null || true; fi;'; - return [ - "_HERMES_DASHBOARD_HOME=/sandbox/.hermes/dashboard-home;", - `_HERMES_DASHBOARD_GATEWAY_PORT=${config.internalPort};`, - '_HERMES_PYTHON=/opt/hermes/.venv/bin/python; [ -x "$_HERMES_PYTHON" ] || _HERMES_PYTHON="$(command -v python3 || echo python3)";', - "_HERMES_DASHBOARD_CONFIG_SEEDER=/usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py;", - `_DASH_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 http://127.0.0.1:${config.internalPort}/ 2>/dev/null || echo 000); case "$_DASH_CODE" in 200|301|302|307|308) echo DASHBOARD_ALREADY_RUNNING; ;; *)`, - `${buildNoFollowLogSetupCommand("/tmp/hermes-dashboard.log")} || exit 1;`, - dashboardLogSelection, - '[ -f "$_HERMES_DASHBOARD_CONFIG_SEEDER" ] || { echo "[dashboard-recovery] ERROR: dashboard config seeder missing"; exit 1; };', - 'if [ -L "$_HERMES_DASHBOARD_HOME" ]; then echo "[dashboard-recovery] ERROR: refusing symlinked dashboard home"; exit 1; fi;', - 'mkdir -p "$_HERMES_DASHBOARD_HOME"; if [ -L "$_HERMES_DASHBOARD_HOME" ] || [ ! -d "$_HERMES_DASHBOARD_HOME" ]; then echo "[dashboard-recovery] ERROR: unsafe dashboard home"; exit 1; fi;', - 'chmod 700 "$_HERMES_DASHBOARD_HOME"; rm -f "${_HERMES_DASHBOARD_HOME}/gateway_state.json" 2>/dev/null || true;', - '"$_HERMES_PYTHON" "$_HERMES_DASHBOARD_CONFIG_SEEDER" /sandbox/.hermes/config.yaml "${_HERMES_DASHBOARD_HOME}/config.yaml" /sandbox/.hermes/.env "${_HERMES_DASHBOARD_HOME}/.env" || { echo "[dashboard-recovery] ERROR: config seed failed"; exit 1; };', - "_DASHBOARD_PROC_PATTERN='[h]ermes[[:space:]]+dashboard([[:space:]]|$)';", - 'pkill -TERM -f "$_DASHBOARD_PROC_PATTERN" 2>/dev/null || true; sleep 1; pkill -KILL -f "$_DASHBOARD_PROC_PATTERN" 2>/dev/null || true;', - `${hermesDashboardEnvPrefix()} nohup "$AGENT_BIN" dashboard --host 127.0.0.1 --port ${config.internalPort} --skip-build --no-open${tuiFlag} >> "$_DASHBOARD_LOG" 2>&1 &`, - "DPID=$!; sleep 2;", - 'if kill -0 "$DPID" 2>/dev/null; then echo "DASHBOARD_PID=$DPID"; else echo DASHBOARD_FAILED; tail -5 "$_DASHBOARD_LOG" 2>/dev/null; exit 1; fi ;; esac;', - ]; -} - -export function buildHermesDashboardProcessRecoveryScript( - config: HermesDashboardRecoveryConfig, -): string { - return [ - "export HERMES_HOME=/sandbox/.hermes;", - buildHermesEnvFileBoundaryGuard(), - ...buildGatewayGuardRecoveryLines(), - '[ "$_GUARDS_MISSING" = "1" ] && { _E="[gateway-recovery] ERROR: NODE_OPTIONS missing safety-net preload or ciao preload after trusted recovery - refusing unguarded dashboard relaunch (#2478/#2701)"; echo "$_E" >&2; exit 1; };', - "[ -f ~/.bashrc ] && . ~/.bashrc;", - buildHermesRuntimeEnvBoundaryGuard(), - 'AGENT_BIN=/usr/local/bin/hermes; if [ ! -x "$AGENT_BIN" ]; then AGENT_BIN="$(command -v hermes)"; fi;', - 'if [ -z "$AGENT_BIN" ]; then echo AGENT_MISSING; exit 1; fi;', - ...buildHermesDashboardRecoveryLines(config), - ].join(" "); -} - -/** - * Build the OpenClaw recovery shell script used by the default sandbox. - */ -export function buildOpenClawRecoveryScript(port: number): string { - const staleGatewayPattern = "[o]penclaw([ -]gateway| gateway run|$)"; - return [ - ...buildGatewayLogSetup(true, "gateway"), - buildGatewayLogSelection(), - ...buildGatewayGuardRecoveryLines(), - gatewayGuardRefusalCommand(), - "[ -f ~/.bashrc ] && . ~/.bashrc;", - `_GW_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 http://127.0.0.1:${port}/health 2>/dev/null || echo 000); case "$_GW_CODE" in 200|401) echo ALREADY_RUNNING; exit 0 ;; esac;`, - "rm -rf /tmp/openclaw-*/gateway.*.lock 2>/dev/null;", - `_GATEWAY_PROC_PATTERN=${shellQuote(staleGatewayPattern)};`, - 'if [ -n "$_GATEWAY_PROC_PATTERN" ]; then pkill -TERM -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; pkill -KILL -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; if pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1; then echo GATEWAY_STALE_PROCESSES; exit 1; fi; fi;', - 'OPENCLAW="$(command -v openclaw)";', - 'if [ -z "$OPENCLAW" ]; then echo OPENCLAW_MISSING; exit 1; fi;', - gatewayLaunchCommand('"$OPENCLAW" gateway run --port ' + port, "gateway"), - "GPID=$!; sleep 2;", - 'if kill -0 "$GPID" 2>/dev/null; then echo "GATEWAY_PID=$GPID"; else echo GATEWAY_FAILED; tail -5 "$_GATEWAY_LOG" 2>/dev/null; fi', - ].join(" "); -} - -/** - * Build the recovery shell script for a non-OpenClaw agent. - * Returns the script string, null if agent is null (use existing inline - * OpenClaw script instead), or a terminal sentinel for agents without a - * gateway process. - */ -export function buildRecoveryScript( - agent: AgentDefinition & { runtime: { kind: "terminal" } }, - port: number, - options?: { hermesDashboard?: HermesDashboardRecoveryConfig | null }, -): typeof TERMINAL_AGENT_RECOVERY_SCRIPT; -export function buildRecoveryScript( - agent: AgentDefinition | null, - port: number, - options?: { hermesDashboard?: HermesDashboardRecoveryConfig | null }, -): string | null; -export function buildRecoveryScript( - agent: AgentDefinition | null, - port: number, - options: { hermesDashboard?: HermesDashboardRecoveryConfig | null } = {}, -): AgentRecoveryScript { - if (!agent) return null; - if (isTerminalAgent(agent)) return TERMINAL_AGENT_RECOVERY_SCRIPT; - - const probeUrl = getHealthProbeUrl(agent); - const binaryPath = agent.binary_path || "/usr/local/bin/openclaw"; - const binaryName = binaryPath.split("/").pop() ?? "openclaw"; - const defaultGatewayCommand = `${binaryName} gateway run`; - const configuredGatewayCommand = agent.gateway_command?.trim() || defaultGatewayCommand; - const usesValidatedBinary = configuredGatewayCommand === defaultGatewayCommand; - const customGatewayExecutable = configuredGatewayCommand.split(/\s+/)[0] ?? binaryName; - const staleGatewayPattern = selfSafeGatewayProcessPattern(configuredGatewayCommand); - const validationSteps = usesValidatedBinary - ? [ - `AGENT_BIN=${shellQuote(binaryPath)}; if [ ! -x "$AGENT_BIN" ]; then AGENT_BIN="$(command -v ${shellQuote(binaryName)})"; fi;`, - 'if [ -z "$AGENT_BIN" ]; then echo AGENT_MISSING; exit 1; fi;', - ] - : [ - `GATEWAY_CMD_BIN=${shellQuote(customGatewayExecutable)};`, - 'case "$GATEWAY_CMD_BIN" in */*) [ -x "$GATEWAY_CMD_BIN" ] || { echo AGENT_MISSING; exit 1; } ;; *) command -v "$GATEWAY_CMD_BIN" >/dev/null 2>&1 || { echo AGENT_MISSING; exit 1; } ;; esac;', - ]; - // Append (>>) rather than truncate (>) so the [gateway-recovery] WARNING - // lines that the recovery script writes to gateway.log moments earlier - // survive past the gateway launch — otherwise the warning explaining - // *why* the gateway is about to crash gets wiped by the same launch - // that's about to crash on a missing guard. (#2478) - const isHermes = agent.name === "hermes"; - const hermesHome = isHermes ? "export HERMES_HOME=/sandbox/.hermes; " : ""; - const hermesLaunchEnv = isHermes ? `env ${hermesGatewayEnvPrefix()} ` : ""; - const launchCommand = usesValidatedBinary - ? gatewayLaunchCommand( - `${hermesLaunchEnv}"$AGENT_BIN" gateway run${isHermes ? "" : ` --port ${port}`}`, - ) - : gatewayLaunchCommand( - `${hermesLaunchEnv}${configuredGatewayCommand}${isHermes ? "" : ` --port ${port}`}`, - ); - - // Validate or rebuild /tmp/nemoclaw-proxy-env.sh before shell init and the - // health fast path so a healthy gateway cannot leave a wiped guard chain - // unrepaired. Recovery also stops stale launcher/gateway processes that may - // have respawned between the health probe and relaunch. - return [ - hermesHome, - ...(isHermes ? [buildHermesEnvFileBoundaryGuard()] : []), - ...buildGatewayLogSetup(false), - buildGatewayLogSelection(), - ...buildGatewayGuardRecoveryLines(), - gatewayGuardRefusalCommand(), - "[ -f ~/.bashrc ] && . ~/.bashrc;", - `_GW_CODE=$(curl -so /dev/null -w '%{http_code}' --max-time 3 ${shellQuote(probeUrl)} 2>/dev/null || echo 000); case "$_GW_CODE" in 200|401) echo ALREADY_RUNNING; exit 0 ;; esac;`, - `_GATEWAY_PROC_PATTERN=${shellQuote(staleGatewayPattern)};`, - 'if [ -n "$_GATEWAY_PROC_PATTERN" ]; then pkill -TERM -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; pkill -KILL -f "$_GATEWAY_PROC_PATTERN" 2>/dev/null || true; for _i in 1 2 3 4 5; do pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1 || break; sleep 1; done; if pgrep -f "$_GATEWAY_PROC_PATTERN" >/dev/null 2>&1; then echo GATEWAY_STALE_PROCESSES; exit 1; fi; fi;', - ...validationSteps, - ...(isHermes ? [buildHermesRuntimeEnvBoundaryGuard()] : []), - launchCommand, - "GPID=$!; sleep 2;", - 'if kill -0 "$GPID" 2>/dev/null; then echo "GATEWAY_PID=$GPID"; else echo GATEWAY_FAILED; tail -5 "$_GATEWAY_LOG" 2>/dev/null; exit 1; fi', - ...(isHermes && options.hermesDashboard - ? buildHermesDashboardRecoveryLines(options.hermesDashboard) - : []), - ].join(" "); -} - /** * Get the display name for the current agent. */ @@ -352,32 +81,3 @@ export function getGatewayCommand(agent: AgentDefinition | null): string { if (agent && isTerminalAgent(agent)) return getTerminalCommand(agent) ?? agent.versionCommand; return agent?.gateway_command || "openclaw gateway run"; } - -/** - * Build a single copy-pasteable command for the user to run when automatic - * gateway recovery fails. Unlike the raw gateway command, this keeps the - * process alive after disconnect and preserves the agent-specific launch shape. - */ -export function buildManualRecoveryCommand(agent: AgentDefinition | null, port: number): string { - if (agent && isTerminalAgent(agent)) return getTerminalCommand(agent) ?? agent.versionCommand; - const binaryPath = agent?.binary_path || "/usr/local/bin/openclaw"; - const defaultGatewayCommand = `${shellQuote(binaryPath)} gateway run`; - const gatewayCmd = agent?.gateway_command?.trim() || defaultGatewayCommand; - const isHermes = agent?.name === "hermes"; - const envPrefix = isHermes ? `${hermesGatewayEnvPrefix()} ` : ""; - const portFlag = isHermes ? "" : ` --port ${port}`; - const hermesHome = isHermes ? "export HERMES_HOME=/sandbox/.hermes;" : ""; - return [ - hermesHome, - ...(isHermes ? [buildHermesEnvFileBoundaryGuard()] : []), - ...buildGatewayLogSetup(false), - buildGatewayLogSelection(), - ...buildGatewayGuardRecoveryLines(), - gatewayGuardRefusalCommand(), - "[ -f ~/.bashrc ] && . ~/.bashrc;", - ...(isHermes ? [buildHermesRuntimeEnvBoundaryGuard()] : []), - `${envPrefix}nohup ${gatewayCmd}${portFlag} >> "$_GATEWAY_LOG" 2>&1 &`, - ] - .filter(Boolean) - .join(" "); -} diff --git a/src/lib/cli/public-display-defaults.ts b/src/lib/cli/public-display-defaults.ts index 131945ccddb..60df7eb90e6 100644 --- a/src/lib/cli/public-display-defaults.ts +++ b/src/lib/cli/public-display-defaults.ts @@ -280,6 +280,13 @@ const PUBLIC_DISPLAY_LAYOUT: Record = { flags: "[--quiet|-q]", }, ], + "sandbox:gateway:restart": [ + { + group: "Sandbox Management", + order: 14.1, + flags: "[--quiet|-q]", + }, + ], "sandbox:hosts:add": [ { group: "Policy Presets", diff --git a/src/lib/onboard/docker-driver-gateway-config-auth-contract.test.ts b/src/lib/onboard/docker-driver-gateway-config-auth-contract.test.ts index cc7150eedb8..8dd662e8010 100644 --- a/src/lib/onboard/docker-driver-gateway-config-auth-contract.test.ts +++ b/src/lib/onboard/docker-driver-gateway-config-auth-contract.test.ts @@ -19,37 +19,11 @@ import { } from "../../../test/support/openshell-gateway-config-helpers"; describe("docker-driver-gateway auth contract", () => { - it("keeps the OpenShell gateway auth source review aligned with the generated config", () => { + it("records the audited OpenShell 0.0.71 source revision", () => { const reviewNote = fs.readFileSync(GATEWAY_AUTH_REVIEW_NOTE, "utf-8"); expect(reviewNote).toContain("NVIDIA/OpenShell@v0.0.71"); expect(reviewNote).toContain("a242f84bb367d6df7d4d133e95a93857406c67f7"); - expect(reviewNote).toContain("openshell-gateway-auth-source-contract.test.ts"); - expect(reviewNote).toContain("openshell_server::config_file::load()"); - expect(reviewNote).toContain("allow_unauthenticated_users"); - expect(reviewNote).toContain("gateway_jwt"); - expect(reviewNote).toContain("mTLS user authentication"); - expect(reviewNote).toContain("SandboxJwtAuthenticator"); - expect(reviewNote).toContain("user principals are rejected from sandbox-only methods"); - expect(reviewNote).toContain( - "gateway_listener_addresses_include_driver_address_on_distinct_ip", - ); - expect(reviewNote).toContain("container_visible_endpoint_rewrites_loopback_hosts"); - expect(reviewNote).toContain("docker_gateway_route_uses_bridge_gateway_for_linux_docker"); - expect(reviewNote).toContain("keeps the main OpenShell listener on `127.0.0.1`"); - expect(reviewNote).toContain( - "NEMOCLAW_OPENSHELL_GATEWAY_COMPAT_BIND_ADDRESS=0.0.0.0` is rejected", - ); - expect(reviewNote).toContain("reject `NEMOCLAW_GATEWAY_BIND_ADDRESS=0.0.0.0`"); - expect(reviewNote).toContain("host-side OpenShell CLI user calls use local mTLS"); - expect(reviewNote).toContain("Source-of-Truth Boundaries"); - expect(reviewNote).toContain("OpenShell gateway auth source contract"); - expect(reviewNote).toContain("Markerless sandbox gateway recovery output"); - expect(reviewNote).toContain("Sessions admin gateway RPC helper"); - expect(reviewNote).toContain("Issue #5591 is the dependency-update umbrella"); - expect(reviewNote).toContain("this PR pins and validates OpenShell `0.0.71`"); - expect(reviewNote).toContain("Issue #2478 is not an acceptance target"); - expect(reviewNote).toContain("valid sandbox JWT access from Docker origin"); }); it("emits an OpenShell 0.0.71-compatible sandbox JWT bundle and TTL contract", () => { diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 015408ec9dc..6b52323386b 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -132,6 +132,22 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "scripts", "nemoclaw-start.sh"), path.join(stagedScriptsDir, "nemoclaw-start.sh"), ); + fs.copyFileSync( + path.join(rootDir, "scripts", "gateway-control.sh"), + path.join(stagedScriptsDir, "gateway-control.sh"), + ); + fs.copyFileSync( + path.join(rootDir, "scripts", "managed-gateway-control.py"), + path.join(stagedScriptsDir, "managed-gateway-control.py"), + ); + fs.copyFileSync( + path.join(rootDir, "scripts", "state-dir-guard.py"), + path.join(stagedScriptsDir, "state-dir-guard.py"), + ); + fs.copyFileSync( + path.join(rootDir, "scripts", "openclaw-config-guard.py"), + path.join(stagedScriptsDir, "openclaw-config-guard.py"), + ); fs.copyFileSync( path.join(rootDir, "scripts", "codex-acp-wrapper.sh"), path.join(stagedScriptsDir, "codex-acp-wrapper.sh"), @@ -146,6 +162,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", "gateway-supervisor.sh"), + path.join(stagedScriptsDir, "lib", "gateway-supervisor.sh"), + ); fs.copyFileSync( path.join(rootDir, "scripts", "lib", "sandbox-rlimits.sh"), path.join(stagedScriptsDir, "lib", "sandbox-rlimits.sh"), diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index a092b777f41..5a0beb21fa2 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -13,6 +13,7 @@ // config rotate-token: Credential rotation via stdin or env var. const readline = require("readline"); +const { createHash } = require("node:crypto"); const fs = require("fs"); const os = require("os"); const path = require("path"); @@ -20,10 +21,16 @@ const { promises: dnsPromises } = require("node:dns"); const { isIP } = require("node:net"); const { validateName } = require("../runner"); const { shellQuote } = require("../core/shell-quote"); -const { dockerExecFileSync } = require("../adapters/docker/exec"); +const { dockerExecFileSync, dockerSpawnSync } = require("../adapters/docker/exec"); const credentialFilter: typeof import("../security/credential-filter") = require("../security/credential-filter"); const { stripCredentials, isConfigObject, isConfigValue, isCredentialField } = credentialFilter; const { appendAuditEntry } = require("../shields/audit"); +const { + withTimerBoundShieldsMutationLock, +}: typeof import("../shields/timer-bound-lock") = require("../shields/timer-bound-lock"); +const { + runOpenClawConfigGuard, +}: typeof import("../shields/openclaw-config-lock") = require("../shields/openclaw-config-lock"); const { isPrivateHostname, isPrivateIp } = require("../private-networks"); const { privilegedSandboxExecArgv, @@ -78,6 +85,8 @@ interface DnsValidatedUrl { pinnedUrl: string; } +type ManagedGatewayRestart = (sandboxName: string) => { ok: boolean }; + export class SandboxConfigError extends Error { readonly lines: readonly string[]; readonly exitCode: number; @@ -95,6 +104,35 @@ function configFail(lines: string | readonly string[], exitCode = 1): never { throw new SandboxConfigError(lines, exitCode); } +function restartSandboxAgentAfterConfigSet( + sandboxName: string, + restartImpl?: ManagedGatewayRestart, +): void { + const restart = + restartImpl ?? + (require("../actions/sandbox/process-recovery").restartSandboxGateway as ManagedGatewayRestart); + const result = restart(sandboxName); + if (!result.ok) { + configFail( + ` Config was updated, but the managed gateway restart failed for '${sandboxName}'.`, + ); + } +} + +function buildConfigSetRestartGuidance(sandboxName: string, agentName: string): string[] { + if (agentName === "openclaw" || agentName === "hermes") { + return [ + " Note: Some config changes require a sandbox restart to take effect.", + ` Re-run with --restart or run: nemoclaw ${shellQuote(sandboxName)} gateway restart`, + ]; + } + + return [ + " Note: Some config changes require restarting the agent runtime to take effect.", + ` Follow the restart procedure for '${agentName}'; NemoClaw does not manage restarts for this agent.`, + ]; +} + class ConfigUrlValidationError extends Error { constructor( readonly urlValue: string, @@ -115,6 +153,14 @@ const DEFAULT_AGENT_CONFIG: AgentConfigTarget = { }; const HERMES_STRICT_HASH_FILE = "/etc/nemoclaw/hermes.config-hash"; +const HERMES_RUNTIME_CONFIG_GUARD = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"; +const HERMES_PYTHON = "/opt/hermes/.venv/bin/python"; +const HERMES_RESTART_SEAL_STATE = "/run/nemoclaw/hermes-restart-seal.json"; +const MAX_OPENCLAW_CONFIG_BYTES = 16 * 1024 * 1024; +const CONFIG_CAPTURE_MAX_BUFFER = MAX_OPENCLAW_CONFIG_BYTES + 1024 * 1024; +const OPENCLAW_CONFIG_GUARD_TIMEOUT_MS = 6 * 60 * 1000; +const HERMES_CONFIG_GUARD_TIMEOUT_MS = 150_000; +const CONFIG_SOURCE_SHA256: unique symbol = Symbol("nemoclaw.configSourceSha256"); function privilegedSandboxExec( sandboxName: string, @@ -122,13 +168,36 @@ function privilegedSandboxExec( opts: { input?: string | Buffer; timeout?: number } = {}, ): string { const hasInput = opts.input !== undefined; - return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, hasInput), { + return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, hasInput, true), { input: opts.input, stdio: hasInput ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"], timeout: opts.timeout ?? 30000, }); } +function openClawConfigGuardExec(sandboxName: string) { + return { + run: (cmd: string[], input?: string) => { + const result = dockerSpawnSync( + privilegedSandboxExecArgv(sandboxName, cmd, input !== undefined, true), + { + encoding: "utf-8", + input, + timeout: OPENCLAW_CONFIG_GUARD_TIMEOUT_MS, + maxBuffer: 2 * 1024 * 1024, + }, + ); + return { + status: result.status, + signal: result.signal, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error.message } : {}), + }; + }, + }; +} + function resolveAgentConfig(sandboxName: string): AgentConfigTarget { try { const registry = require("../state/registry"); @@ -388,9 +457,23 @@ function readSandboxConfig(sandboxName: string, target: AgentConfigTarget): Conf const result = captureOpenshellCommand( binary, ["sandbox", "exec", "--name", sandboxName, "--", "cat", target.configPath], - { ignoreError: true, errorLine: console.error, exit: (code: number) => process.exit(code) }, + { + ignoreError: true, + includeStreams: true, + maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, + errorLine: console.error, + exit: (code: number) => process.exit(code), + }, ); - raw = result.output || ""; + if (result.error || result.signal || result.status !== 0) { + const detail = result.error?.message || result.stderr?.trim() || result.output; + configFail( + ` Cannot read ${target.agentName} config (${target.configPath})${detail ? `: ${detail}` : "."}`, + ); + } + // `output` is display-normalized with trim(); the transaction digest must + // bind the exact bytes returned by `cat`, including its final newline. + raw = result.stdout ?? result.output ?? ""; } catch { raw = ""; } @@ -403,7 +486,14 @@ function readSandboxConfig(sandboxName: string, target: AgentConfigTarget): Conf } try { - return parseConfig(raw, target.format); + const config = parseConfig(raw, target.format); + Object.defineProperty(config, CONFIG_SOURCE_SHA256, { + configurable: false, + enumerable: false, + value: createHash("sha256").update(raw).digest("hex"), + writable: false, + }); + return config; } catch (err) { const message = err instanceof Error ? err.message : String(err); configFail(` Failed to parse ${target.agentName} config: ${message}`); @@ -415,14 +505,73 @@ function writeSandboxConfig( target: AgentConfigTarget, config: ConfigObject, ): void { + const content = composeSandboxConfigBody(config, target); + if (target.agentName === "hermes") { + const expectedConfigSha256 = (config as ConfigObject & { [CONFIG_SOURCE_SHA256]?: string })[ + CONFIG_SOURCE_SHA256 + ]; + if (!expectedConfigSha256) { + throw new Error( + "Refusing Hermes config write without the digest from the matching sandbox read.", + ); + } + privilegedSandboxExec( + sandboxName, + [ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "2m", + HERMES_PYTHON, + "-I", + HERMES_RUNTIME_CONFIG_GUARD, + "write-config", + "--hermes-dir", + target.configDir, + "--hash-file", + HERMES_STRICT_HASH_FILE, + "--state-file", + HERMES_RESTART_SEAL_STATE, + "--expected-config-sha256", + expectedConfigSha256, + ], + { input: content, timeout: HERMES_CONFIG_GUARD_TIMEOUT_MS }, + ); + return; + } + if (target.agentName === "openclaw") { + const expectedConfigSha256 = (config as ConfigObject & { [CONFIG_SOURCE_SHA256]?: string })[ + CONFIG_SOURCE_SHA256 + ]; + if (!expectedConfigSha256) { + throw new Error( + "Refusing OpenClaw config write without the digest from the matching sandbox read.", + ); + } + const result = runOpenClawConfigGuard(openClawConfigGuardExec(sandboxName), "write-config", { + expectedConfigSha256, + input: content, + }); + if (result.issues.length > 0) { + throw new Error(`OpenClaw config write refused: ${result.issues.join(", ")}`); + } + const expectedNewDigest = createHash("sha256").update(content).digest("hex"); + if (result.configSha256 !== expectedNewDigest) { + throw new Error( + `OpenClaw config guard committed digest ${String(result.configSha256)} (expected ${expectedNewDigest})`, + ); + } + return; + } + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-config-")); const tmpFile = path.join(tmpDir, target.configFile); try { - fs.writeFileSync(tmpFile, composeSandboxConfigBody(config, target), { mode: 0o600 }); + fs.writeFileSync(tmpFile, content, { mode: 0o600 }); - const content = fs.readFileSync(tmpFile, "utf-8"); + const stagedContent = fs.readFileSync(tmpFile, "utf-8"); privilegedSandboxExec(sandboxName, ["sh", "-c", `cat > ${shellQuote(target.configPath)}`], { - input: content, + input: stagedContent, }); try { @@ -441,29 +590,10 @@ function writeSandboxConfig( } function buildRecomputeSandboxConfigHashScript(target: AgentConfigTarget): string | null { - if (target.agentName === "hermes") { - const envFile = `${target.configDir}/.env`; - const compatibilityHash = `${target.configDir}/.config-hash`; - const strictHash = shellQuote(HERMES_STRICT_HASH_FILE); - const compatibilityHashQuoted = shellQuote(compatibilityHash); - return [ - `mkdir -p ${shellQuote("/etc/nemoclaw")}`, - `strict_hash=${strictHash}`, - `strict_tmp="\${strict_hash}.tmp.$$"`, - `compat_hash=${compatibilityHashQuoted}`, - `compat_tmp="\${compat_hash}.tmp.$$"`, - `trap 'rm -f "$strict_tmp" "$compat_tmp"' EXIT HUP INT TERM`, - `sha256sum ${shellQuote(target.configPath)} ${shellQuote(envFile)} > "$strict_tmp"`, - `chown root:root "$strict_tmp"`, - `chmod 444 "$strict_tmp"`, - `mv -f "$strict_tmp" "$strict_hash"`, - `cp "$strict_hash" "$compat_tmp"`, - `chown sandbox:sandbox "$compat_tmp"`, - `chmod 600 "$compat_tmp"`, - `mv -f "$compat_tmp" "$compat_hash"`, - "trap - EXIT HUP INT TERM", - ].join(" && "); - } + // OpenClaw and Hermes write and refresh both hashes inside one fd-pinned sealed + // transaction. A second pathname-based hash pass would reopen the race that + // transaction is designed to close. + if (target.agentName === "openclaw" || target.agentName === "hermes") return null; if (!target.sensitiveFiles?.includes(`${target.configDir}/.config-hash`)) return null; return [ `cd ${shellQuote(target.configDir)}`, @@ -764,10 +894,29 @@ async function configSet(sandboxName: string, opts: ConfigSetOpts = {}): Promise } const target = resolveAgentConfig(sandboxName); + if (opts.restart && target.agentName !== "openclaw" && target.agentName !== "hermes") { + configFail( + ` --restart is supported only for OpenClaw and Hermes; '${target.agentName}' config was not changed.`, + ); + } + if (target.agentName === "openclaw" || target.agentName === "hermes") { + const { isShieldsDown }: typeof import("../shields") = require("../shields"); + if (!isShieldsDown(sandboxName, false)) { + configFail( + ` ${target.agentName} config changes are unavailable while shields are up for '${sandboxName}'. Run 'nemoclaw ${sandboxName} shields down' first.`, + ); + } + } // Read current config console.log(` Reading ${target.agentName} config...`); const config = readSandboxConfig(sandboxName, target); + const initialConfigSha256 = (config as ConfigObject & { [CONFIG_SOURCE_SHA256]?: string })[ + CONFIG_SOURCE_SHA256 + ]; + if (!initialConfigSha256) { + configFail(` Cannot bind the ${target.agentName} config read to a safe write transaction.`); + } // Parse and validate value const parsedValue = parseCliConfigValue(opts.value); @@ -836,43 +985,53 @@ async function configSet(sandboxName: string, opts: ConfigSetOpts = {}): Promise configFail(` URL validation failed${suffix}: ${message}`); } - // Apply change - setDotpath(config, opts.key, safeValue); + // Serialize only the authoritative re-read/CAS write. Interactive approval + // and DNS validation above must not hold the shields transition lock across + // the auto-restore deadline. If anything changed while the user was + // deciding, fail closed and ask them to retry against the new baseline. + withTimerBoundShieldsMutationLock(sandboxName, "config set write", () => { + const { isShieldsDown }: typeof import("../shields") = require("../shields"); + if ( + (target.agentName === "openclaw" || target.agentName === "hermes") && + !isShieldsDown(sandboxName, true) + ) { + configFail( + ` ${target.agentName} config changes are unavailable while shields are up for '${sandboxName}'. Run 'nemoclaw ${sandboxName} shields down' first.`, + ); + } + const currentConfig = readSandboxConfig(sandboxName, target); + const currentConfigSha256 = ( + currentConfig as ConfigObject & { [CONFIG_SOURCE_SHA256]?: string } + )[CONFIG_SOURCE_SHA256]; + if (currentConfigSha256 !== initialConfigSha256) { + configFail( + ` ${target.agentName} config changed while this update was being validated. Re-run config set against the current value.`, + ); + } + setDotpath(currentConfig, opts.key!, safeValue); - console.log(` Writing config to sandbox (${target.configPath})...`); - writeSandboxConfig(sandboxName, target, config); - recomputeSandboxConfigHash(sandboxName, target); + console.log(` Writing config to sandbox (${target.configPath})...`); + writeSandboxConfig(sandboxName, target, currentConfig); + recomputeSandboxConfigHash(sandboxName, target); - // Audit log - appendAuditEntry({ - action: "config_set", - sandbox: sandboxName, - timestamp: new Date().toISOString(), - reason: `config set ${target.agentName}:${opts.key}`, + appendAuditEntry({ + action: "config_set", + sandbox: sandboxName, + timestamp: new Date().toISOString(), + reason: `config set ${target.agentName}:${opts.key}`, + }); }); console.log(` ${target.agentName} config updated.`); // Restart if requested if (opts.restart) { - console.log(" Restarting sandbox agent process..."); - const restartBinary = getOpenshellBinary(); - const result = captureOpenshellCommand( - restartBinary, - ["sandbox", "exec", "--name", sandboxName, "--", "kill", "-HUP", "1"], - { ignoreError: true, errorLine: console.error, exit: (code: number) => process.exit(code) }, - ); - - if (result.status !== 0) { - console.error(" Could not signal the sandbox process to reload."); - console.error(" You may need to recreate the sandbox for this change to take effect."); - } else { - console.log(" Reload signal sent."); - } + restartSandboxAgentAfterConfigSet(sandboxName); } else { console.log(""); - console.log(" Note: Some config changes require a sandbox restart to take effect."); - console.log(` Re-run with --restart or recreate with: nemoclaw onboard --recreate-sandbox`); + for (const line of buildConfigSetRestartGuidance(sandboxName, target.agentName)) { + console.log(line); + } } } @@ -1040,6 +1199,7 @@ function confirmYesNo(prompt: string): Promise { // --------------------------------------------------------------------------- export { + buildConfigSetRestartGuidance, buildRecomputeSandboxConfigHashScript, classifyNewKeyGate, composeSandboxConfigBody, @@ -1057,6 +1217,7 @@ export { readStdin, recomputeSandboxConfigHash, resolveAgentConfig, + restartSandboxAgentAfterConfigSet, rewriteConfigUrlsWithDnsPinning, setDotpath, validateConfigDotpath, diff --git a/src/lib/sandbox/privileged-exec.test.ts b/src/lib/sandbox/privileged-exec.test.ts index 2be299d5f08..e225ce318e9 100644 --- a/src/lib/sandbox/privileged-exec.test.ts +++ b/src/lib/sandbox/privileged-exec.test.ts @@ -14,7 +14,7 @@ const { containerNameMatchesSandbox, selectDirectSandboxContainer } = require(he function withPrivilegedExecMocks( deps: { - dockerCapture: (args: readonly string[]) => string; + dockerCapture: (args: readonly string[], options?: { timeout?: number }) => string; getSandbox: (name: string) => { name?: string; openshellDriver?: string | null } | null; listSandboxes: () => { sandboxes?: Array<{ name?: string | null }>; @@ -86,6 +86,12 @@ describe("privileged sandbox exec routing", () => { expect(selected).toBe("openshell-demo-abc123"); }); + it("fails closed when multiple suffix containers match without an exact identity", () => { + expect(() => + selectDirectSandboxContainer("demo", "openshell-demo-old\nopenshell-demo-new\n", ["demo"]), + ).toThrow(/Multiple running direct OpenShell containers.*demo.*old.*new/); + }); + it("uses the longest registered sandbox-name match to avoid prefix collisions", () => { const containerNames = [ "openshell-alpha-child", @@ -133,6 +139,62 @@ describe("privileged sandbox exec routing", () => { ); }); + it("bounds direct sandbox container discovery", () => { + const discoveryCalls: Array<{ + args: readonly string[]; + timeout: number | undefined; + }> = []; + + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "docker" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: (args, options) => { + discoveryCalls.push({ args, timeout: options?.timeout }); + return "openshell-alpha\n"; + }, + }, + ({ privilegedSandboxExecArgv }) => { + expect(privilegedSandboxExecArgv("alpha", ["id"])).toEqual([ + "exec", + "--user", + "root", + "openshell-alpha", + "id", + ]); + }, + ); + + expect(discoveryCalls).toEqual([ + { + args: ["ps", "--format", "{{.Names}}"], + timeout: 5000, + }, + ]); + }); + + it("clears interpreter and dynamic-loader injection variables for root control", () => { + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "docker" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: () => "openshell-alpha\n", + }, + ({ privilegedSandboxExecArgv }) => { + const argv = privilegedSandboxExecArgv("alpha", ["/trusted/control"], false, true); + expect(argv.slice(0, 1)).toEqual(["exec"]); + expect(argv).toContain("LD_PRELOAD="); + expect(argv).toContain("LD_LIBRARY_PATH="); + expect(argv).toContain("LD_AUDIT="); + expect(argv).toContain("PYTHONPATH="); + expect(argv).toContain("PYTHONUSERBASE="); + expect(argv).toContain("PYTHONNOUSERSITE=1"); + expect(argv).toContain("BASH_ENV="); + expect(argv.slice(-4)).toEqual(["--user", "root", "openshell-alpha", "/trusted/control"]); + }, + ); + }); + it("fails before docker discovery when the sandbox registry entry is unavailable", () => { let dockerPsCalls = 0; withPrivilegedExecMocks( @@ -153,6 +215,26 @@ describe("privileged sandbox exec routing", () => { expect(dockerPsCalls).toBe(0); }); + it("rejects a Kubernetes registry owner before stale local-container discovery", () => { + let dockerPsCalls = 0; + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "kubernetes" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: () => { + dockerPsCalls += 1; + return "openshell-alpha-stale\n"; + }, + }, + ({ privilegedSandboxExecArgv }) => { + expect(() => privilegedSandboxExecArgv("alpha", ["id"])).toThrow( + /driver: kubernetes.*refusing local Docker discovery/i, + ); + }, + ); + expect(dockerPsCalls).toBe(0); + }); + it("fails before docker discovery when registry disambiguation is unavailable", () => { let dockerPsCalls = 0; withPrivilegedExecMocks( @@ -202,10 +284,18 @@ describe("privileged sandbox exec routing", () => { }), dockerCapture: () => "openshell-alpha-child\n", }, - ({ privilegedSandboxExecArgv }) => { - expect(() => privilegedSandboxExecArgv("alpha", ["id"])).toThrow( + ({ isDirectSandboxFallbackUnavailableError, privilegedSandboxExecArgv }) => { + let refusal: unknown; + try { + privilegedSandboxExecArgv("alpha", ["id"]); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(Error); + expect(String(refusal)).toMatch( /No running direct OpenShell sandbox container found for 'alpha'/, ); + expect(isDirectSandboxFallbackUnavailableError(refusal)).toBe(true); }, ); }); diff --git a/src/lib/sandbox/privileged-exec.ts b/src/lib/sandbox/privileged-exec.ts index 8e087b53251..9003bd644a1 100644 --- a/src/lib/sandbox/privileged-exec.ts +++ b/src/lib/sandbox/privileged-exec.ts @@ -1,24 +1,42 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -const { dockerCapture } = require("../adapters/docker/run"); -const registry = require("../state/registry") as { - getSandbox?: (name: string) => { name?: string; openshellDriver?: string | null } | null; - listSandboxes?: () => { - sandboxes?: Array<{ name?: string | null }>; - defaultSandbox?: string | null; - }; - load?: () => { - sandboxes?: Record; - defaultSandbox?: string | null; - }; -}; +import { dockerCapture } from "../adapters/docker/run"; +import * as registry from "../state/registry"; type SandboxEntry = { name?: string; openshellDriver?: string | null; }; +const DIRECT_SANDBOX_DISCOVERY_TIMEOUT_MS = 5000; +const SANITIZED_PRIVILEGED_ENV = [ + "BASH_ENV=", + "ENV=", + "GCONV_PATH=", + "GLIBC_TUNABLES=", + "LD_AUDIT=", + "LD_LIBRARY_PATH=", + "LD_PRELOAD=", + "LOCPATH=", + "NODE_OPTIONS=", + "PERL5OPT=", + "PYTHONHOME=", + "PYTHONINSPECT=", + "PYTHONNOUSERSITE=1", + "PYTHONPATH=", + "PYTHONSTARTUP=", + "PYTHONUSERBASE=", + "RUBYOPT=", +] as const; + +class DirectSandboxFallbackUnavailableError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "DirectSandboxFallbackUnavailableError"; + } +} + function normalizeDriver(driver: unknown): string | null { return typeof driver === "string" && driver.trim() ? driver.trim().toLowerCase() : null; } @@ -71,20 +89,30 @@ function selectDirectSandboxContainer( const names = Array.from(new Set([...registeredNames, sandboxName])).sort( (a, b) => b.length - a.length || a.localeCompare(b), ); - const candidates = containerNames - .split("\n") - .map((line: string) => line.trim()) - .filter(Boolean) - .filter((containerName: string) => { - if (!containerNameMatchesSandbox(containerName, sandboxName)) return false; - return owningRegisteredSandboxName(containerName, names) === sandboxName; - }); + const candidates = Array.from( + new Set( + containerNames + .split("\n") + .map((line: string) => line.trim()) + .filter(Boolean) + .filter((containerName: string) => { + if (!containerNameMatchesSandbox(containerName, sandboxName)) return false; + return owningRegisteredSandboxName(containerName, names) === sandboxName; + }), + ), + ); - return ( - candidates.find((containerName: string) => containerName === `openshell-${sandboxName}`) ?? - candidates[0] ?? - null + const exact = candidates.find( + (containerName: string) => containerName === `openshell-${sandboxName}`, ); + if (exact) return exact; + if (candidates.length === 1) return candidates[0]; + if (candidates.length > 1) { + throw new Error( + `Multiple running direct OpenShell containers match registered sandbox '${sandboxName}': ${candidates.join(", ")}. Refusing privileged exec without an exact container identity.`, + ); + } + return null; } function expectedDirectContainerPattern(sandboxName: string): string { @@ -93,19 +121,36 @@ function expectedDirectContainerPattern(sandboxName: string): string { function findDirectSandboxContainer(sandboxName: string): string | null { const names = registeredSandboxNames(sandboxName); - const output = dockerCapture(["ps", "--format", "{{.Names}}"]); + let output: string; + try { + output = dockerCapture(["ps", "--format", "{{.Names}}"], { + timeout: DIRECT_SANDBOX_DISCOVERY_TIMEOUT_MS, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new DirectSandboxFallbackUnavailableError( + `Direct sandbox container discovery failed for '${sandboxName}': ${detail}`, + { cause: error }, + ); + } return selectDirectSandboxContainer(sandboxName, output, names); } function missingDirectContainerError(sandboxName: string, driver: string | null): Error { const driverLabel = driver ?? "unspecified"; - return new Error( + return new DirectSandboxFallbackUnavailableError( `No running direct OpenShell sandbox container found for '${sandboxName}' ` + `(driver: ${driverLabel}). Expected a running container named ` + `${expectedDirectContainerPattern(sandboxName)}. Is the sandbox running?`, ); } +function isDirectSandboxFallbackUnavailableError( + error: unknown, +): error is DirectSandboxFallbackUnavailableError { + return error instanceof DirectSandboxFallbackUnavailableError; +} + function missingRegistryEntryError(sandboxName: string): Error { return new Error( `No NemoClaw registry entry found for '${sandboxName}'; ` + @@ -113,23 +158,49 @@ function missingRegistryEntryError(sandboxName: string): Error { ); } +function unsupportedDirectDriverError(sandboxName: string, driver: string): Error { + return new Error( + `Privileged direct-container control is unavailable for sandbox '${sandboxName}' ` + + `(driver: ${driver}); refusing local Docker discovery for a non-direct driver.`, + ); +} + function resolveDirectSandboxContainer(sandboxName: string, driver: string | null): string { const selected = findDirectSandboxContainer(sandboxName); if (selected) return selected; throw missingDirectContainerError(sandboxName, driver); } -function privilegedSandboxExecArgv(sandboxName: string, cmd: string[], stdin = false): string[] { +function privilegedSandboxExecArgv( + sandboxName: string, + cmd: string[], + stdin = false, + sanitizeEnvironment = false, +): string[] { const entry = readSandboxEntry(sandboxName); if (!entry) throw missingRegistryEntryError(sandboxName); const driver = normalizeDriver(entry?.openshellDriver); + if (driver !== null && driver !== "docker" && driver !== "vm") { + throw unsupportedDirectDriverError(sandboxName, driver); + } // Docker/direct-container is the only supported privileged mutation path. // Try it even when older registry entries do not record a driver, then fail // clearly if no matching sandbox container is running. const container = findDirectSandboxContainer(sandboxName); if (container) { - return ["exec", ...(stdin ? ["-i"] : []), "--user", "root", container, ...cmd]; + const sanitizedEnvArgs = sanitizeEnvironment + ? SANITIZED_PRIVILEGED_ENV.flatMap((value) => ["--env", value]) + : []; + return [ + "exec", + ...(stdin ? ["-i"] : []), + ...sanitizedEnvArgs, + "--user", + "root", + container, + ...cmd, + ]; } throw missingDirectContainerError(sandboxName, driver); @@ -137,7 +208,8 @@ function privilegedSandboxExecArgv(sandboxName: string, cmd: string[], stdin = f export { containerNameMatchesSandbox, - selectDirectSandboxContainer, - resolveDirectSandboxContainer, + isDirectSandboxFallbackUnavailableError, privilegedSandboxExecArgv, + resolveDirectSandboxContainer, + selectDirectSandboxContainer, }; diff --git a/src/lib/shields/flow.test.ts b/src/lib/shields/flow.test.ts index c0200ebbcdf..66fd3c60a2b 100644 --- a/src/lib/shields/flow.test.ts +++ b/src/lib/shields/flow.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawn } from "node:child_process"; import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; @@ -10,24 +11,49 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } fr const requireDist = createRequire(import.meta.url); const shieldsModulePath = "./index.js"; +const HUNG_FORWARD_OWNER_SOURCE = ` +const { spawn } = require("node:child_process"); +const childScriptPath = process.argv[2]; +const sentinelPath = process.argv[3]; +spawn(process.execPath, [childScriptPath, sentinelPath], { stdio: "ignore" }); +setTimeout(() => {}, 5000); +`; +const LATE_WEAKENING_CHILD_SOURCE = ` +const fs = require("node:fs"); +const sentinelPath = process.argv[2]; +setTimeout(() => fs.writeFileSync(sentinelPath, "ran"), 1200); +setTimeout(() => {}, 5000); +`; type ShieldsHarness = { auditSpy: MockInstance; logSpy: MockInstance; + runSpy: MockInstance; shieldsDown: typeof import("./index.js").shieldsDown; shieldsStatus: typeof import("./index.js").shieldsStatus; shieldsUp: typeof import("./index.js").shieldsUp; isShieldsDown: typeof import("./index.js").isShieldsDown; + synchronizeAutoRestoreWithShieldsDown: typeof import("./index.js").synchronizeAutoRestoreWithShieldsDown; }; let tmpDir: string; type HarnessOptions = { dockerExecFileSync?: (argv: unknown) => string; + fork?: () => { + pid: number; + disconnect: () => void; + unref: () => void; + send: () => boolean; + kill: () => boolean; + }; + run?: (cmd: unknown) => { status: number }; }; function createHarness(options: HarnessOptions = {}): ShieldsHarness { delete require.cache[requireDist.resolve(shieldsModulePath)]; + delete require.cache[requireDist.resolve("./timer-bound-lock.js")]; + delete require.cache[requireDist.resolve("./transition-lock.js")]; delete require.cache[requireDist.resolve("../sandbox/privileged-exec.js")]; const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); @@ -40,10 +66,15 @@ function createHarness(options: HarnessOptions = {}): ShieldsHarness { const privilegedExec = requireDist("../sandbox/privileged-exec.js"); const dockerExec = requireDist("../adapters/docker/exec.js"); const audit = requireDist("./audit.js"); + const childProcess = requireDist("node:child_process"); + let openClawPosture: "locked" | "mutable" = "mutable"; vi.spyOn(runner, "validateName").mockImplementation((name: unknown) => String(name)); vi.spyOn(runner, "runCapture").mockReturnValue("version: 1\nnetwork_policies:\n test: {}\n"); - vi.spyOn(runner, "run").mockReturnValue({ status: 0 }); + const runSpy = vi.spyOn(runner, "run").mockImplementation((cmd: unknown) => { + return options.run ? options.run(cmd) : { status: 0 }; + }); + options.fork && vi.spyOn(childProcess, "fork").mockImplementation(options.fork); vi.spyOn(policy, "buildPolicyGetCommand").mockReturnValue(["openshell", "policy", "get"]); vi.spyOn(policy, "buildPolicySetCommand").mockReturnValue(["openshell", "policy", "set"]); vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)); @@ -69,16 +100,57 @@ function createHarness(options: HarnessOptions = {}): ShieldsHarness { ...(Array.isArray(cmd) ? cmd.map(String) : []), ], ); + vi.spyOn(dockerExec, "dockerSpawnSync").mockImplementation((argv: unknown) => { + const args = Array.isArray(argv) ? argv.map(String) : []; + const action = ["preflight", "lock", "unlock"].find((candidate) => args.includes(candidate)); + const openClawGuard = args.some((arg) => arg.endsWith("openclaw-config-guard.py")); + openClawPosture = + openClawGuard && action === "lock" + ? "locked" + : openClawGuard && action === "unlock" + ? "mutable" + : openClawPosture; + return { + status: 0, + signal: null, + stdout: action + ? `${JSON.stringify({ + type: "result", + action, + status: "ok", + ...(openClawGuard + ? { + configDir: "/sandbox/.openclaw", + files: ["openclaw.json", ".config-hash"], + chattrApplied: action === "lock", + } + : { issueCount: 0 }), + })}\n` + : "", + stderr: "", + pid: 0, + output: [], + } as never; + }); vi.spyOn(dockerExec, "dockerExecFileSync").mockImplementation((argv: unknown) => { - if (options.dockerExecFileSync) return options.dockerExecFileSync(argv); const args = Array.isArray(argv) ? argv.map(String) : []; - return args.includes("sha256sum") - ? "a".repeat(64) + " /sandbox/.openclaw/openclaw.json\n" - : args.includes("stat") - ? args.at(-1) === "/sandbox/.openclaw" - ? "2770 sandbox:sandbox\n" - : "660 sandbox:sandbox\n" - : ""; + return options.dockerExecFileSync + ? options.dockerExecFileSync(argv) + : args.includes("sha256sum") + ? "a".repeat(64) + " /sandbox/.openclaw/openclaw.json\n" + : args.includes("stat") + ? args.at(-1) === "/sandbox" + ? openClawPosture === "locked" + ? "1775 root:sandbox\n" + : "755 sandbox:sandbox\n" + : args.at(-1) === "/sandbox/.openclaw" + ? openClawPosture === "locked" + ? "755 root:root\n" + : "2770 sandbox:sandbox\n" + : openClawPosture === "locked" + ? "444 root:root\n" + : "660 sandbox:sandbox\n" + : ""; }); const auditSpy = vi.spyOn(audit, "appendAuditEntry").mockImplementation(() => undefined); @@ -88,10 +160,12 @@ function createHarness(options: HarnessOptions = {}): ShieldsHarness { return { auditSpy, logSpy, + runSpy, shieldsDown: shields.shieldsDown, shieldsStatus: shields.shieldsStatus, shieldsUp: shields.shieldsUp, isShieldsDown: shields.isShieldsDown, + synchronizeAutoRestoreWithShieldsDown: shields.synchronizeAutoRestoreWithShieldsDown, }; } @@ -106,6 +180,8 @@ describe("shields command flow", () => { vi.unstubAllEnvs(); fs.rmSync(tmpDir, { recursive: true, force: true }); delete require.cache[requireDist.resolve(shieldsModulePath)]; + delete require.cache[requireDist.resolve("./timer-bound-lock.js")]; + delete require.cache[requireDist.resolve("./transition-lock.js")]; }); it("shieldsDown captures policy, unlocks config, saves state, and skips timer on request", () => { @@ -133,6 +209,353 @@ describe("shields command flow", () => { ); }); + it("binds manual shields-up to the active auto-restore timer generation", () => { + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const sandboxName = "openclaw"; + const processToken = "9".repeat(32); + const snapshotPath = path.join(stateDir, "policy-snapshot-manual-up.yaml"); + const lockPath = path.join(stateDir, `shields-transition-lock-${sandboxName}.json`); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); + fs.writeFileSync( + path.join(stateDir, `shields-${sandboxName}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date().toISOString(), + shieldsDownTimeout: 300, + shieldsDownReason: "manual-up-token-test", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + fs.writeFileSync( + path.join(stateDir, `shields-timer-${sandboxName}.json`), + JSON.stringify({ + pid: 999_999, + sandboxName, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + }), + ); + + let observedOwner: Record | null = null; + const harness = createHarness({ + run: () => { + observedOwner = JSON.parse(fs.readFileSync(lockPath, "utf-8")); + return { status: 0 }; + }, + dockerExecFileSync: (argv: unknown) => { + const args = Array.isArray(argv) ? argv.map(String) : []; + switch (true) { + case args.includes("sha256sum"): + return `${"a".repeat(64)} ${String(args.at(-1))}\n`; + case args.includes("lsattr"): + return `----i---------e----- ${String(args.at(-1))}\n`; + case args.includes("stat"): + return args.at(-1) === "/sandbox" + ? "1775 root:sandbox\n" + : args.at(-1) === "/sandbox/.openclaw" + ? "755 root:root\n" + : "444 root:root\n"; + default: + return ""; + } + }, + }); + harness.shieldsUp(sandboxName, { throwOnError: true }); + + expect(observedOwner).toMatchObject({ + sandboxName, + command: "shields up", + takeoverToken: processToken, + }); + }); + + it("never selects the detached recovery timer or its children for owner-tree takeover", () => { + const shields = requireDist(shieldsModulePath) as { + excludeRecoveryProcessTree: ( + descendants: Array<{ pid: number; startIdentity: string; depth: number }>, + recoveryPid: number, + recoveryDescendants: Array<{ pid: number; startIdentity: string; depth: number }>, + ) => Array<{ pid: number; startIdentity: string; depth: number }>; + }; + const recovery = { pid: 200, startIdentity: "timer", depth: 1 }; + const recoveryChild = { pid: 201, startIdentity: "timer-child", depth: 2 }; + const weakeningChild = { pid: 300, startIdentity: "policy-set", depth: 1 }; + + expect( + shields.excludeRecoveryProcessTree([recovery, recoveryChild, weakeningChild], recovery.pid, [ + recoveryChild, + ]), + ).toEqual([weakeningChild]); + }); + + it("auto-restore waits for the forward shields-down commit before reclaiming policy", () => { + const harness = createHarness(); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + + const sandboxName = "openclaw"; + const processToken = "a".repeat(32); + const snapshotPath = path.join(stateDir, "policy-snapshot-race.yaml"); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandboxName}-${processToken}.json`, + ); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); + fs.writeFileSync( + path.join(stateDir, `shields-timer-${sandboxName}.json`), + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: new Date(Date.now() - 1_000).toISOString(), + processToken, + }), + ); + + const owner = spawn( + process.execPath, + [ + "-e", + [ + "const fs=require('fs')", + "const p=process.argv[1]", + "setTimeout(()=>{", + " const v=JSON.parse(fs.readFileSync(p,'utf8'))", + " const t=p+'.child.tmp'", + " fs.writeFileSync(t,JSON.stringify({...v,phase:'active'}),{mode:0o600})", + " fs.renameSync(t,p)", + "},150)", + "setTimeout(()=>{},1000)", + ].join(";"), + transitionPath, + ], + { stdio: "ignore" }, + ); + expect(owner.pid).toBeTypeOf("number"); + const timerControl = requireDist("./timer-control.js"); + const ownerStartIdentity = timerControl.readProcessStartIdentity(owner.pid); + expect(ownerStartIdentity).toBeTypeOf("string"); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "preparing", + ownerPid: owner.pid, + ownerStartIdentity, + processToken, + sandboxName, + snapshotPath, + }), + { mode: 0o600 }, + ); + + const startedAt = Date.now(); + try { + harness.synchronizeAutoRestoreWithShieldsDown(sandboxName); + } finally { + owner.kill("SIGTERM"); + } + + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); + expect(fs.existsSync(transitionPath)).toBe(false); + expect(harness.runSpy).toHaveBeenCalledWith( + ["openshell", "policy", "set"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("preempts a hung forward owner and its weakening subprocess before restoring", async () => { + const harness = createHarness(); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + const sandboxName = "openclaw"; + const processToken = "b".repeat(32); + const snapshotPath = path.join(stateDir, "policy-snapshot-hung.yaml"); + const sentinelPath = path.join(stateDir, "late-weakening-child-ran"); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandboxName}-${processToken}.json`, + ); + const ownerScriptPath = path.join(stateDir, "hung-forward-owner.cjs"); + const childScriptPath = path.join(stateDir, "late-weakening-child.cjs"); + fs.writeFileSync(ownerScriptPath, HUNG_FORWARD_OWNER_SOURCE, { mode: 0o600 }); + fs.writeFileSync(childScriptPath, LATE_WEAKENING_CHILD_SOURCE, { mode: 0o600 }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); + fs.writeFileSync( + path.join(stateDir, `shields-timer-${sandboxName}.json`), + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: new Date(Date.now() - 1_000).toISOString(), + processToken, + }), + ); + + const owner = spawn(process.execPath, [ownerScriptPath, childScriptPath, sentinelPath], { + stdio: "ignore", + }); + expect(owner.pid).toBeTypeOf("number"); + const timerControl = requireDist("./timer-control.js"); + const ownerStartIdentity = timerControl.readProcessStartIdentity(owner.pid); + expect(ownerStartIdentity).toBeTypeOf("string"); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "preparing", + ownerPid: owner.pid, + ownerStartIdentity, + processToken, + sandboxName, + snapshotPath, + }), + { mode: 0o600 }, + ); + + try { + harness.synchronizeAutoRestoreWithShieldsDown(sandboxName); + await new Promise((resolve) => setTimeout(resolve, 1400)); + } finally { + owner.kill("SIGKILL"); + } + + expect(fs.existsSync(sentinelPath)).toBe(false); + expect(fs.existsSync(transitionPath)).toBe(false); + expect(harness.runSpy).toHaveBeenCalledWith( + ["openshell", "policy", "set"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("preempts timer-token config and inference mutations at the restore deadline", async () => { + const shields = requireDist(shieldsModulePath) as { + prepareAutoRestoreTransitionTakeover: ( + sandboxName: string, + processToken: string, + snapshotPath: string, + ) => void; + }; + const transitionLockPath = path.join(import.meta.dirname, "transition-lock.ts"); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + + for (const [index, command] of ["config set write", "inference set"].entries()) { + const sandboxName = `deadline-${String(index)}`; + const processToken = String(index + 1).repeat(32); + const readyPath = path.join(stateDir, `${sandboxName}.ready`); + const lockPath = path.join(stateDir, `shields-transition-lock-${sandboxName}.json`); + const owner = spawn( + process.execPath, + [ + "--import", + "tsx", + "-e", + [ + `const {withShieldsTransitionLock}=require(${JSON.stringify(transitionLockPath)})`, + "const fs=require('fs')", + "const [name,command,token,ready]=process.argv.slice(1)", + "withShieldsTransitionLock(name,command,()=>{fs.writeFileSync(ready,'ready');Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10000)},{takeoverToken:token})", + ].join(";"), + sandboxName, + command, + processToken, + readyPath, + ], + { env: { ...process.env, HOME: tmpDir }, stdio: "ignore" }, + ); + + try { + const deadline = Date.now() + 5_000; + while ((!fs.existsSync(readyPath) || !fs.existsSync(lockPath)) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(fs.existsSync(readyPath)).toBe(true); + expect(fs.existsSync(lockPath)).toBe(true); + + shields.prepareAutoRestoreTransitionTakeover( + sandboxName, + processToken, + path.join(stateDir, `${sandboxName}.snapshot.yaml`), + ); + + expect(fs.existsSync(lockPath)).toBe(false); + } finally { + owner.kill("SIGKILL"); + } + } + }); + + it("publishes preparing recovery ownership before weakening and active only after unlock", () => { + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + let observedPreparingDuringPolicy = false; + let observedPreparingDuringUnlock = false; + let authorizationSawMarker = false; + const readOnlyTransition = () => { + const transitionName = fs + .readdirSync(stateDir) + .find((name) => name.startsWith("shields-transition-openclaw-")); + expect(transitionName).toBeDefined(); + return JSON.parse(fs.readFileSync(path.join(stateDir, transitionName!), "utf-8")); + }; + const harness = createHarness({ + fork: () => ({ + pid: 4242, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => { + authorizationSawMarker = fs.existsSync( + path.join(stateDir, "shields-timer-openclaw.json"), + ); + return true; + }), + kill: vi.fn(() => true), + }), + run: () => { + observedPreparingDuringPolicy = readOnlyTransition().phase === "preparing"; + return { status: 0 }; + }, + dockerExecFileSync: (argv: unknown) => { + const args = Array.isArray(argv) ? argv.map(String) : []; + observedPreparingDuringUnlock ||= readOnlyTransition().phase === "preparing"; + switch (true) { + case args.includes("sha256sum"): + return `${"a".repeat(64)} /sandbox/.openclaw/openclaw.json\n`; + case args.includes("stat"): + return args.at(-1) === "/sandbox" + ? "755 sandbox:sandbox\n" + : args.at(-1) === "/sandbox/.openclaw" + ? "2770 sandbox:sandbox\n" + : "660 sandbox:sandbox\n"; + default: + return ""; + } + }, + }); + + harness.shieldsDown("openclaw", { + timeout: "5m", + reason: "race coverage", + throwOnError: true, + }); + + const transition = readOnlyTransition(); + expect(observedPreparingDuringPolicy).toBe(true); + expect(observedPreparingDuringUnlock).toBe(true); + expect(authorizationSawMarker).toBe(true); + expect(transition).toMatchObject({ + version: 1, + phase: "active", + ownerPid: process.pid, + sandboxName: "openclaw", + snapshotPath: expect.stringContaining("policy-snapshot-"), + }); + expect(fs.existsSync(path.join(stateDir, "shields-timer-openclaw.json"))).toBe(true); + }); + it("shieldsUp refuses to mark lockdown active when the saved restrictive policy snapshot is missing", () => { const harness = createHarness(); const stateDir = path.join(tmpDir, ".nemoclaw", "state"); @@ -154,17 +577,62 @@ describe("shields command flow", () => { ); }); + it("retains the bounded auto-restore owner when manual shields-up fails", () => { + const harness = createHarness(); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, "policy-snapshot-relock-failure.yaml"); + const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync( + path.join(stateDir, "shields-openclaw.json"), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date().toISOString(), + shieldsDownTimeout: 1800, + shieldsDownReason: "rebuild", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: 4242, + sandboxName: "openclaw", + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken: "timer-token", + allowLegacyHermesProtocol: false, + }), + ); + const killSpy = vi.spyOn(process, "kill").mockReturnValue(true); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /Config not locked/, + ); + + expect(fs.existsSync(markerPath)).toBe(true); + expect(killSpy).not.toHaveBeenCalled(); + expect( + JSON.parse(fs.readFileSync(path.join(stateDir, "shields-openclaw.json"), "utf-8")) + .shieldsDown, + ).toBe(true); + }); + it("shieldsStatus restores an expired dead timer through the same lock path as shields up", () => { const configPath = "/sandbox/.openclaw/openclaw.json"; const configDir = "/sandbox/.openclaw"; const hashPath = `${configDir}/.config-hash`; const configHash = "a".repeat(64); const hashHash = "b".repeat(64); + const processToken = "7".repeat(32); const execCalls: string[] = []; const execResponses = new Map([ [` stat -c %a %U:%G ${hashPath}`, "444 root:root\n"], [` stat -c %a %U:%G ${configPath}`, "444 root:root\n"], [` stat -c %a %U:%G ${configDir}`, "755 root:root\n"], + [" stat -c %a %U:%G /sandbox", "1775 root:sandbox\n"], [` lsattr -d ${hashPath}`, `----i---------e----- ${hashPath}\n`], [` lsattr -d ${configPath}`, `----i---------e----- ${configPath}\n`], [` sha256sum ${hashPath}`, `${hashHash} ${hashPath}\n`], @@ -179,6 +647,7 @@ describe("shields command flow", () => { }, }); const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const lockPath = path.join(stateDir, "shields-transition-lock-openclaw.json"); fs.mkdirSync(stateDir, { recursive: true }); const snapshotPath = path.join(stateDir, "policy-snapshot-expired.yaml"); fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); @@ -200,7 +669,19 @@ describe("shields command flow", () => { sandboxName: "openclaw", snapshotPath, restoreAt: new Date(Date.now() - 30_000).toISOString(), - processToken: "timer-token", + processToken, + }), + ); + fs.writeFileSync( + lockPath, + JSON.stringify({ + version: 1, + sandboxName: "openclaw", + pid: 4242, + processStartIdentity: "dead-timer", + command: "shields auto-restore", + acquiredAtMs: Date.now() - 60_000, + takeoverToken: processToken, }), ); vi.spyOn(process, "kill").mockImplementation((pid: number, signal?: string | number) => { @@ -226,6 +707,7 @@ describe("shields command flow", () => { [hashPath]: hashHash, }); expect(fs.existsSync(path.join(stateDir, "shields-timer-openclaw.json"))).toBe(false); + expect(fs.existsSync(lockPath)).toBe(false); expect(harness.auditSpy).toHaveBeenCalledWith( expect.objectContaining({ action: "shields_auto_restore", @@ -234,7 +716,6 @@ describe("shields command flow", () => { sandbox: "openclaw", }), ); - expect(execCalls.some((cmd) => cmd.includes(` chmod 444 ${hashPath}`))).toBe(true); - expect(execCalls.some((cmd) => cmd.includes(` chown root:root ${hashPath}`))).toBe(true); + expect(execCalls.some((cmd) => cmd.includes(` sha256sum ${hashPath}`))).toBe(true); }); }); diff --git a/src/lib/shields/index.test.ts b/src/lib/shields/index.test.ts index 95f7f499c84..6b80bff4a17 100644 --- a/src/lib/shields/index.test.ts +++ b/src/lib/shields/index.test.ts @@ -54,7 +54,13 @@ vi.mock("./audit", () => ({ })); vi.mock("child_process", () => ({ - fork: vi.fn(() => ({ pid: 12345, disconnect: vi.fn(), unref: vi.fn() })), + fork: vi.fn(() => ({ + pid: 12345, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => true), + kill: vi.fn(() => true), + })), execFileSync: vi.fn(), spawnSync: vi.fn(() => ({ status: 0, diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index ca30933db4c..064eed913c1 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -9,13 +9,25 @@ // Time-bounded shields-down has automatic restore via a detached timer. // The sandbox cannot lower or raise its own shields — all mutations are // host-initiated (security invariant). +// +// This module intentionally remains the host-side transaction coordinator for +// policy snapshots, config posture, timer authority, state commits, rollback, +// and audit ordering. Leaf authority and validation live in the focused lock, +// timer, seal, and config-guard modules imported below; splitting the coordinator +// before one typed transaction can own the complete cross-resource rollback +// would duplicate or weaken the reviewed ordering. New leaf mechanisms belong +// in those modules, and a later decomposition must preserve the transition and +// timer-bound lock tests before this facade can shrink safely. const fs = require("fs"); const path = require("path"); const { fork } = require("child_process"); const { randomBytes } = require("crypto"); const { run, runCapture, validateName } = require("../runner"); -const { dockerExecFileSync } = require("../adapters/docker/exec"); +const { + dockerExecFileSync, + dockerSpawnSync, +}: typeof import("../adapters/docker/exec") = require("../adapters/docker/exec"); const { privilegedSandboxExecArgv, }: typeof import("../sandbox/privileged-exec") = require("../sandbox/privileged-exec"); @@ -31,6 +43,8 @@ const { readTimerMarker, clearTimerMarker, isProcessAlive, + readProcessStartIdentity, + listDescendantProcessIdentities, verifyTimerMarkerIdentity, killTimer, } = require("./timer-control"); @@ -43,6 +57,14 @@ const { const { cleanupTempDir } = require("../onboard/temp-files"); const { verifyShieldsLockState }: typeof import("./verify-lock") = require("./verify-lock"); const { relockAndReconfirm }: typeof import("./relock-reconfirm") = require("./relock-reconfirm"); +const { + inspectShieldsTransitionLockOwner, + takeoverShieldsTransitionLock, + withShieldsTransitionLock, +}: typeof import("./transition-lock") = require("./transition-lock"); +const { + withTimerBoundShieldsMutationLock, +}: typeof import("./timer-bound-lock") = require("./timer-bound-lock"); const { parseSha256Output, isHashVerificationIssue, @@ -51,15 +73,230 @@ const { const { applyStateDirLockMode, preflightStateDirLock, + restoreStateDirLockPosture, }: typeof import("./state-dir-lock") = require("./state-dir-lock"); +const { + OPENCLAW_CONFIG_DIR, + OPENCLAW_CONFIG_HASH_PATH, + OPENCLAW_CONFIG_PATH, + runOpenClawConfigGuard, +}: typeof import("./openclaw-config-lock") = require("./openclaw-config-lock"); const { inspectMutableConfigPerms: inspectMutableConfigPermsCore, repairMutableConfigPerms: repairMutableConfigPermsCore, }: typeof import("./mutable-config-perms") = require("./mutable-config-perms"); type MutableConfigPermsInspection = import("./mutable-config-perms").MutableConfigPermsInspection; type MutableConfigRepairResult = import("./mutable-config-perms").MutableConfigRepairResult; +type ProcessIdentity = import("./timer-control").ProcessIdentity; const STATE_DIR = resolveNemoclawStateDir(); +const SHIELDS_TRANSITION_POLL_MS = 50; +const SHIELDS_TRANSITION_HANDOFF_GRACE_MS = 500; +const SHIELDS_TRANSITION_TERMINATE_GRACE_MS = 1000; +const AUTO_RESTORE_COMPLETION_GRACE_MS = 30_000; +const HERMES_RUNTIME_CONFIG_GUARD = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"; +const HERMES_PYTHON = "/opt/hermes/.venv/bin/python"; +const HERMES_RESTART_SEAL_STATE = "/run/nemoclaw/hermes-restart-seal.json"; +const HERMES_CONFIG_HASH = "/etc/nemoclaw/hermes.config-hash"; +const STATE_DIR_GUARD_TIMEOUT_MS = 15 * 60 * 1000; +const OPENCLAW_CONFIG_GUARD_TIMEOUT_MS = 6 * 60 * 1000; +const HERMES_CONFIG_GUARD_TIMEOUT_MS = 11 * 60 * 1000; + +type ShieldsDownTransition = { + version: 1; + phase: "preparing" | "active"; + ownerPid: number; + ownerStartIdentity: string; + processToken: string; + sandboxName: string; + snapshotPath: string; +}; + +const transitionPollBuffer = new Int32Array(new SharedArrayBuffer(4)); + +function shieldsDownTransitionPath(sandboxName: string, processToken: string): string { + return path.join(STATE_DIR, `shields-transition-${sandboxName}-${processToken}.json`); +} + +function isShieldsDownTransition(value: unknown): value is ShieldsDownTransition { + if (!isObjectRecord(value)) return false; + return ( + value.version === 1 && + (value.phase === "preparing" || value.phase === "active") && + typeof value.ownerPid === "number" && + Number.isInteger(value.ownerPid) && + value.ownerPid > 0 && + typeof value.ownerStartIdentity === "string" && + value.ownerStartIdentity.length > 0 && + typeof value.processToken === "string" && + /^[0-9a-f]{32}$/.test(value.processToken) && + typeof value.sandboxName === "string" && + typeof value.snapshotPath === "string" + ); +} + +function readShieldsDownTransition( + sandboxName: string, + processToken: string, +): ShieldsDownTransition | null { + const transitionPath = shieldsDownTransitionPath(sandboxName, processToken); + try { + const value = JSON.parse(fs.readFileSync(transitionPath, "utf-8")); + if (!isShieldsDownTransition(value)) return null; + if (value.sandboxName !== sandboxName || value.processToken !== processToken) return null; + return value; + } catch { + return null; + } +} + +function writeShieldsDownTransition( + transition: ShieldsDownTransition, + expectedPhase: ShieldsDownTransition["phase"] | null, +): void { + fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 }); + const transitionPath = shieldsDownTransitionPath(transition.sandboxName, transition.processToken); + if (expectedPhase !== null) { + const current = readShieldsDownTransition(transition.sandboxName, transition.processToken); + if ( + !current || + current.phase !== expectedPhase || + current.ownerPid !== transition.ownerPid || + current.snapshotPath !== transition.snapshotPath + ) { + throw new Error("Shields-down recovery ownership changed during the transition"); + } + } + + const tempPath = `${transitionPath}.${String(process.pid)}.${randomBytes(8).toString("hex")}.tmp`; + try { + fs.writeFileSync(tempPath, JSON.stringify(transition), { flag: "wx", mode: 0o600 }); + fs.renameSync(tempPath, transitionPath); + } finally { + try { + fs.rmSync(tempPath, { force: true }); + } catch { + // Best effort. The authoritative path was either atomically replaced or unchanged. + } + } +} + +function clearShieldsDownTransition(sandboxName: string, processToken: string): void { + try { + fs.rmSync(shieldsDownTransitionPath(sandboxName, processToken), { force: true }); + } catch { + // Best effort. A stale transition marker never grants mutation authority. + } +} + +function waitForShieldsDownForwardCommit( + sandboxName: string, + processToken: string, +): ShieldsDownTransition | null { + let observed = readShieldsDownTransition(sandboxName, processToken); + if (!observed) return null; + + const ownerIsCurrent = () => + isProcessAlive(observed!.ownerPid) && + readProcessStartIdentity(observed!.ownerPid) === observed!.ownerStartIdentity; + const handoffDeadline = Date.now() + SHIELDS_TRANSITION_HANDOFF_GRACE_MS; + while (observed.phase === "preparing" && ownerIsCurrent() && Date.now() < handoffDeadline) { + Atomics.wait(transitionPollBuffer, 0, 0, SHIELDS_TRANSITION_POLL_MS); + const next = readShieldsDownTransition(sandboxName, processToken); + if (!next) return null; + if ( + next.ownerPid !== observed.ownerPid || + next.ownerStartIdentity !== observed.ownerStartIdentity || + next.snapshotPath !== observed.snapshotPath || + next.processToken !== observed.processToken + ) { + throw new Error("Shields-down recovery ownership changed while waiting for forward commit"); + } + observed = next; + } + + if (observed.phase === "preparing" && ownerIsCurrent()) { + // The absolute shields-down deadline has expired while the forward owner + // is still able to weaken policy/config. Preempt that exact process + // instance, then restore from the captured snapshot. Waiting forever would + // turn the requested timeout into an unbounded mutable window. + stopTimedOutShieldsDownTree(observed.ownerPid, observed.ownerStartIdentity); + } + return observed; +} + +function excludeRecoveryProcessTree( + descendants: ProcessIdentity[], + recoveryPid: number, + recoveryDescendants: ProcessIdentity[], +): ProcessIdentity[] { + const excludedPids = new Set([recoveryPid, ...recoveryDescendants.map(({ pid }) => pid)]); + return descendants.filter(({ pid }) => !excludedPids.has(pid)); +} + +function stopTimedOutShieldsDownTree(ownerPid: number, ownerStartIdentity: string): void { + const identityIsCurrent = (pid: number, startIdentity: string) => + isProcessAlive(pid) && readProcessStartIdentity(pid) === startIdentity; + const signalExact = (pid: number, startIdentity: string, signal: NodeJS.Signals): void => { + if (!identityIsCurrent(pid, startIdentity)) return; + try { + process.kill(pid, signal); + } catch (error) { + const errno = error as NodeJS.ErrnoException; + if (errno.code !== "ESRCH") throw error; + } + }; + if (!identityIsCurrent(ownerPid, ownerStartIdentity)) return; + + const recoveryTree = listDescendantProcessIdentities(process.pid); + if (recoveryTree === null) { + throw new Error("Cannot identify the auto-restore recovery process tree safely"); + } + // Stop the exact owner before enumerating its descendants so it cannot launch + // another weakening subprocess while takeover is being established. + signalExact(ownerPid, ownerStartIdentity, "SIGSTOP"); + const tracked = new Map(); + for (let pass = 0; pass < 8; pass += 1) { + const descendants = listDescendantProcessIdentities(ownerPid); + if (descendants === null) { + throw new Error("Cannot enumerate timed-out shields-down subprocesses safely"); + } + let added = false; + const recoveryIsInsideOwnerTree = descendants.some( + ({ pid }: { pid: number }) => pid === process.pid, + ); + for (const descendant of excludeRecoveryProcessTree( + descendants, + process.pid, + recoveryIsInsideOwnerTree ? recoveryTree : [], + )) { + if (!tracked.has(descendant.pid)) added = true; + tracked.set(descendant.pid, { + startIdentity: descendant.startIdentity, + depth: descendant.depth, + }); + signalExact(descendant.pid, descendant.startIdentity, "SIGSTOP"); + } + if (!added) break; + Atomics.wait(transitionPollBuffer, 0, 0, SHIELDS_TRANSITION_POLL_MS); + } + + const deepestFirst = [...tracked.entries()].sort((a, b) => b[1].depth - a[1].depth); + for (const [pid, identity] of deepestFirst) { + signalExact(pid, identity.startIdentity, "SIGKILL"); + } + signalExact(ownerPid, ownerStartIdentity, "SIGKILL"); + + const killDeadline = Date.now() + SHIELDS_TRANSITION_TERMINATE_GRACE_MS; + while (Date.now() < killDeadline) { + const survivor = deepestFirst.some(([pid, identity]) => + identityIsCurrent(pid, identity.startIdentity), + ); + if (!survivor && !identityIsCurrent(ownerPid, ownerStartIdentity)) return; + Atomics.wait(transitionPollBuffer, 0, 0, SHIELDS_TRANSITION_POLL_MS); + } + throw new Error("Timed-out shields-down process tree could not be stopped safely"); +} // --------------------------------------------------------------------------- // privileged sandbox exec — bypasses the sandbox's Landlock context @@ -71,20 +308,245 @@ const STATE_DIR = resolveNemoclawStateDir(); // sandbox container is running. // --------------------------------------------------------------------------- -function privilegedSandboxExec(sandboxName: string, cmd: string[]): void { - dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd), { +function privilegedSandboxExec(sandboxName: string, cmd: string[], timeout = 15000): void { + dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { stdio: ["ignore", "pipe", "pipe"], - timeout: 15000, + timeout, }); } -function privilegedSandboxExecCapture(sandboxName: string, cmd: string[]): string { - return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd), { +function privilegedSandboxExecCapture(sandboxName: string, cmd: string[], timeout = 15000): string { + return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { stdio: ["ignore", "pipe", "pipe"], - timeout: 15000, + timeout, }).trim(); } +function hermesShieldsGuardArgs( + action: string, + target: AgentConfigTarget, + extra: string[] = [], + timeout = "10m", +): string[] { + return [ + "timeout", + "--signal=TERM", + "--kill-after=5s", + timeout, + HERMES_PYTHON, + "-I", + HERMES_RUNTIME_CONFIG_GUARD, + action, + "--hermes-dir", + target.configDir, + "--state-file", + HERMES_RESTART_SEAL_STATE, + ...extra, + ]; +} + +type HermesShieldsProtocol = "sealed" | "legacy"; + +const HERMES_SEALED_SHIELDS_CONTRACT = [ + "begin-shields-transition", + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "--rollback-shields-mode", +] as const; +const HERMES_LEGACY_GUARD_CONTRACT = [ + "ensure-api-key", + "refresh-hashes", + "provider-placeholders", +] as const; + +function inspectHermesShieldsProtocol( + sandboxName: string, + target: AgentConfigTarget, +): HermesShieldsProtocol { + if (target.agentName !== "hermes") return "sealed"; + const help = privilegedSandboxExecCapture( + sandboxName, + [ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "10m", + HERMES_PYTHON, + "-I", + HERMES_RUNTIME_CONFIG_GUARD, + "--help", + ], + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); + if (HERMES_SEALED_SHIELDS_CONTRACT.every((entry) => help.includes(entry))) { + return "sealed"; + } + if (HERMES_LEGACY_GUARD_CONTRACT.every((entry) => help.includes(entry))) { + return "legacy"; + } + throw new Error( + "Hermes runtime guard exposes an incomplete shields transition contract; rebuild the sandbox", + ); +} + +function requireHermesShieldsProtocol( + sandboxName: string, + target: AgentConfigTarget, + allowLegacyHermesProtocol: boolean, +): HermesShieldsProtocol { + const protocol = inspectHermesShieldsProtocol(sandboxName, target); + if (protocol === "legacy" && !allowLegacyHermesProtocol) { + throw new Error( + "This Hermes sandbox image predates sealed shields transitions; rebuild the sandbox before changing shields", + ); + } + return protocol; +} + +function resolveHermesShieldsProtocol( + sandboxName: string, + target: AgentConfigTarget, + allowLegacyHermesProtocol: boolean, + cachedProtocol?: HermesShieldsProtocol, +): HermesShieldsProtocol { + const protocol = + cachedProtocol ?? requireHermesShieldsProtocol(sandboxName, target, allowLegacyHermesProtocol); + if (target.agentName === "hermes" && protocol === "legacy" && !allowLegacyHermesProtocol) { + throw new Error( + "This Hermes sandbox image predates sealed shields transitions; rebuild the sandbox before changing shields", + ); + } + return protocol; +} + +function supportsHermesSealedShieldsTransactions(sandboxName: string): boolean { + validateName(sandboxName, "sandbox name"); + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + return inspectHermesShieldsProtocol(sandboxName, target) === "sealed"; +} + +function beginHermesConfigShields( + sandboxName: string, + target: AgentConfigTarget, + mode: "locked" | "mutable", + rollbackMode: "locked" | "mutable", +): { token: string; originalLocked: boolean; rollbackLocked: boolean } { + const output = privilegedSandboxExecCapture( + sandboxName, + hermesShieldsGuardArgs("begin-shields-transition", target, [ + "--hash-file", + HERMES_CONFIG_HASH, + "--shields-mode", + mode, + "--rollback-shields-mode", + rollbackMode, + ]), + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); + const match = /^lock_token=([0-9a-f]{64}) original_locked=([01])$/.exec(output); + if (!match) { + // A successful guard invocation has already created the root-owned seal. + // If a future output-contract drift still exposes the token, release that + // transaction before surfacing the parser error instead of leaking a live + // mutation lock merely because the host/client versions disagree. + const recoverableToken = /(?:^|\s)lock_token=([0-9a-f]{64})(?:\s|$)/.exec(output)?.[1]; + if (recoverableToken) { + try { + prepareHermesConfigShieldsAbort(sandboxName, target, recoverableToken); + abortHermesConfigShields(sandboxName, target, recoverableToken); + } catch (abortError) { + const message = abortError instanceof Error ? abortError.message : String(abortError); + throw new Error( + `Unexpected Hermes shields transaction response: ${output}; rollback failed: ${message}`, + ); + } + } + throw new Error(`Unexpected Hermes shields transaction response: ${output}`); + } + return { + token: match[1], + originalLocked: match[2] === "1", + rollbackLocked: rollbackMode === "locked", + }; +} + +function applyHermesConfigShields( + sandboxName: string, + target: AgentConfigTarget, + token: string, +): boolean { + const output = privilegedSandboxExecCapture( + sandboxName, + hermesShieldsGuardArgs("apply-shields-transition", target, ["--lock-token", token]), + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); + const match = /^shields_mode=(?:locked|mutable) chattr_applied=([01])$/.exec(output); + if (!match) throw new Error(`Unexpected Hermes shields apply response: ${output}`); + return match[1] === "1"; +} + +function finishHermesConfigShields( + sandboxName: string, + target: AgentConfigTarget, + token: string, +): void { + privilegedSandboxExec( + sandboxName, + hermesShieldsGuardArgs("finish-shields-transition", target, [ + "--hash-file", + HERMES_CONFIG_HASH, + "--lock-token", + token, + ]), + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); +} + +function abortHermesConfigShields( + sandboxName: string, + target: AgentConfigTarget, + token: string, +): void { + privilegedSandboxExec( + sandboxName, + hermesShieldsGuardArgs("abort-shields-transition", target, ["--lock-token", token]), + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); +} + +function prepareHermesConfigShieldsAbort( + sandboxName: string, + target: AgentConfigTarget, + token: string, +): void { + privilegedSandboxExec( + sandboxName, + hermesShieldsGuardArgs("prepare-shields-abort", target, ["--lock-token", token]), + HERMES_CONFIG_GUARD_TIMEOUT_MS, + ); +} + +function runHermesStateDirTransition( + sandboxName: string, + target: AgentConfigTarget, + token: string, + action: "lock" | "unlock", +): void { + privilegedSandboxExec( + sandboxName, + hermesShieldsGuardArgs( + "run-state-dir-transition", + target, + ["--state-action", action, "--lock-token", token], + "13m", + ), + STATE_DIR_GUARD_TIMEOUT_MS, + ); +} + // Re-export for tests and external consumers const MAX_TIMEOUT_SECONDS = MAX_SECONDS; const DEFAULT_TIMEOUT_SECONDS = DEFAULT_SECONDS; @@ -159,9 +621,28 @@ function ensureConfigHashSensitiveFile(target: T): return { ...target, sensitiveFiles: [...sensitiveFiles, hashPath] } as T; } -function failShieldsCommand(message: string, shouldThrow?: boolean): never { - if (shouldThrow) throw new Error(message); - process.exit(1); +class DeferredShieldsExit extends Error { + readonly exitCode: number; + + constructor(message: string, exitCode: number) { + super(message); + this.name = "DeferredShieldsExit"; + this.exitCode = exitCode; + } +} + +function failShieldsCommand(message: string, _shouldThrow?: boolean): never { + // Never terminate while a transition-lock callback is active: process.exit + // skips finally blocks and would strand the canonical lock. Public command + // wrappers translate this sentinel only after the lock has been released. + throw new DeferredShieldsExit(message, 1); +} + +function completeDeferredShieldsExit(error: unknown, shouldThrow = false): never { + if (error instanceof DeferredShieldsExit && !shouldThrow) { + process.exit(error.exitCode); + } + throw error; } /** @@ -241,12 +722,42 @@ function loadShieldsState(sandboxName: string): LoadedShieldsState { } } -function getShieldsPosture(sandboxName: string, allowInlineRecovery = false): ShieldsPosture { +function getShieldsPostureWithoutHostLock( + sandboxName: string, + allowInlineRecovery = false, +): ShieldsPosture { const state = recoverExpiredAutoRestoreGate(sandboxName, allowInlineRecovery); const mode = state._isCorrupt ? "error" : deriveShieldsMode(state, state._hasStateFile); return { ...describeShieldsMode(mode), state }; } +function prepareExpiredAutoRestoreHostLockTakeover(sandboxName: string): void { + const state = loadShieldsState(sandboxName); + if (state._isCorrupt || state.shieldsDown !== true) return; + const marker = readTimerMarker(sandboxName); + if (!marker?.processToken || !/^[0-9a-f]{32}$/.test(marker.processToken)) return; + const restoreAtMs = new Date(marker.restoreAt).getTime(); + const now = Date.now(); + if (!Number.isFinite(restoreAtMs) || restoreAtMs > now) return; + if ( + isProcessAlive(marker.pid) && + verifyTimerMarkerIdentity(marker).verified && + now <= restoreAtMs + AUTO_RESTORE_COMPLETION_GRACE_MS + ) { + return; + } + prepareAutoRestoreTransitionTakeover(sandboxName, marker.processToken, marker.snapshotPath); +} + +function getShieldsPosture(sandboxName: string, allowInlineRecovery = false): ShieldsPosture { + if (!allowInlineRecovery) return getShieldsPostureWithoutHostLock(sandboxName, false); + validateName(sandboxName, "sandbox name"); + prepareExpiredAutoRestoreHostLockTakeover(sandboxName); + return withTimerBoundShieldsMutationLock(sandboxName, "recover expired shields posture", () => + getShieldsPostureWithoutHostLock(sandboxName, true), + ); +} + function saveShieldsState(sandboxName: string, patch: ShieldsState): ShieldsState { const current = loadShieldsState(sandboxName); // Strip runtime-only markers before persisting. @@ -330,11 +841,81 @@ function isShieldsState(value: unknown): value is ShieldsState { function stateDirLockExec(sandboxName: string) { return { - exec: (cmd: string[]) => privilegedSandboxExec(sandboxName, cmd), - capture: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), + run: (cmd: string[], input?: string) => { + const result = dockerSpawnSync( + privilegedSandboxExecArgv(sandboxName, cmd, input !== undefined, true), + { + encoding: "utf-8", + input, + timeout: STATE_DIR_GUARD_TIMEOUT_MS, + maxBuffer: 16 * 1024 * 1024, + }, + ); + return { + status: result.status, + signal: result.signal, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error.message } : {}), + }; + }, }; } +function openClawConfigGuardExec(sandboxName: string) { + return { + run: (cmd: string[], input?: string) => { + const result = dockerSpawnSync( + privilegedSandboxExecArgv(sandboxName, cmd, input !== undefined, true), + { + encoding: "utf-8", + input, + timeout: OPENCLAW_CONFIG_GUARD_TIMEOUT_MS, + maxBuffer: 2 * 1024 * 1024, + }, + ); + return { + status: result.status, + signal: result.signal, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error.message } : {}), + }; + }, + }; +} + +function assertCanonicalOpenClawConfigTarget(target: AgentConfigTarget): void { + if (target.agentName !== "openclaw") return; + const files = [target.configPath, ...(target.sensitiveFiles || [])]; + if ( + target.configDir !== OPENCLAW_CONFIG_DIR || + target.configPath !== OPENCLAW_CONFIG_PATH || + files.length !== 2 || + files[0] !== OPENCLAW_CONFIG_PATH || + files[1] !== OPENCLAW_CONFIG_HASH_PATH + ) { + throw new Error( + `OpenClaw shields require the canonical protected-file set under ${OPENCLAW_CONFIG_DIR}`, + ); + } +} + +function transitionOpenClawTopConfig( + sandboxName: string, + target: AgentConfigTarget, + action: "preflight" | "lock" | "unlock", +): boolean { + assertCanonicalOpenClawConfigTarget(target); + const result = runOpenClawConfigGuard(openClawConfigGuardExec(sandboxName), action); + if (result.issues.length > 0) { + throw new Error( + `Config not ${action === "unlock" ? "unlocked" : "locked"}: ${result.issues.join(", ")}`, + ); + } + return result.chattrApplied; +} + const CONFIG_UNLOCK_NOFOLLOW_SCRIPT = String.raw` import errno import fcntl @@ -482,6 +1063,368 @@ if body_error is not None: raise body_error `; +// Compatibility transition for a running Hermes image that predates the +// root-owned transaction helper. This path is reachable only from rebuild. +// It freezes `/sandbox` and `.hermes` through already-open directory FDs, +// validates the root-owned strict hash and in-tree compatibility hash, then +// publishes fresh inodes. Fresh replacement revokes any writable descriptors +// retained by the old gateway before a failed rebuild attempts to re-lock it. +const LEGACY_HERMES_CONFIG_TRANSITION_SCRIPT = String.raw` +import fcntl +import grp +import hashlib +import os +import pwd +import secrets +import stat +import struct +import sys + +FS_IMMUTABLE_FL = 0x00000010 +FS_APPEND_FL = 0x00000020 +FS_IOC_GETFLAGS = 0x80086601 +FS_IOC_SETFLAGS = 0x40086602 +MAX_CONFIG_BYTES = 16 * 1024 * 1024 +MAX_HASH_BYTES = 64 * 1024 + +def die(message): + raise RuntimeError(message) + +def inode_flags(fd): + try: + buf = bytearray(4) + fcntl.ioctl(fd, FS_IOC_GETFLAGS, buf, True) + return struct.unpack("I", buf)[0] + except OSError: + return 0 + +def set_inode_flags(fd, flags): + try: + fcntl.ioctl(fd, FS_IOC_SETFLAGS, struct.pack("I", flags)) + except OSError: + if flags: + raise + +def clear_immutable(fd): + flags = inode_flags(fd) + mutable = flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL) + if mutable != flags: + set_inode_flags(fd, mutable) + return flags + +def open_directory(path, dir_fd=None): + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + flags |= getattr(os, "O_DIRECTORY", 0) + fd = os.open(path, flags, dir_fd=dir_fd) + if not stat.S_ISDIR(os.fstat(fd).st_mode): + os.close(fd) + die("not a directory: " + path) + return fd + +def open_child_regular(dir_fd, name, label): + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(name, flags, dir_fd=dir_fd) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: + os.close(fd) + die("refusing unsafe legacy Hermes path: " + label) + return fd, st + +def read_fd(fd, limit, label): + os.lseek(fd, 0, os.SEEK_SET) + chunks = [] + total = 0 + while True: + chunk = os.read(fd, min(1024 * 1024, limit + 1 - total)) + if not chunk: + return b"".join(chunks) + total += len(chunk) + if total > limit: + die("legacy Hermes file exceeds size limit: " + label) + chunks.append(chunk) + +def read_strict_hash(path): + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(path, flags) + try: + st = os.fstat(fd) + if ( + not stat.S_ISREG(st.st_mode) + or st.st_nlink != 1 + or st.st_uid != 0 + or stat.S_IMODE(st.st_mode) & 0o222 + ): + die("refusing unsafe strict Hermes hash anchor") + return read_fd(fd, MAX_HASH_BYTES, path) + finally: + os.close(fd) + +def metadata(st): + return { + "dev": st.st_dev, + "ino": st.st_ino, + "uid": st.st_uid, + "gid": st.st_gid, + "mode": stat.S_IMODE(st.st_mode), + } + +def same_inode(st, saved): + return st.st_dev == saved["dev"] and st.st_ino == saved["ino"] + +def stage_file(dir_fd, name, data, uid, gid, mode): + temp = ".%s.nemoclaw.%d.%s" % (name, os.getpid(), secrets.token_hex(8)) + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NOFOLLOW", 0) + ) + fd = os.open(temp, flags, 0o600, dir_fd=dir_fd) + try: + os.fchown(fd, uid, gid) + os.fchmod(fd, mode) + view = memoryview(data) + while view: + written = os.write(fd, view) + if written <= 0: + die("short write while staging " + name) + view = view[written:] + os.fsync(fd) + except Exception: + os.close(fd) + try: + os.unlink(temp, dir_fd=dir_fd) + except OSError: + pass + raise + os.close(fd) + return temp + +def replace_with_bytes(dir_fd, name, data, uid, gid, mode, flags=0): + current_fd, _current_st = open_child_regular(dir_fd, name, name) + try: + clear_immutable(current_fd) + finally: + os.close(current_fd) + temp = stage_file(dir_fd, name, data, uid, gid, mode) + try: + os.replace(temp, name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) + finally: + try: + os.unlink(temp, dir_fd=dir_fd) + except FileNotFoundError: + pass + replacement_fd, replacement_st = open_child_regular(dir_fd, name, name) + try: + if ( + replacement_st.st_uid != uid + or replacement_st.st_gid != gid + or stat.S_IMODE(replacement_st.st_mode) != mode + ): + die("replacement metadata mismatch for " + name) + if flags: + set_inode_flags(replacement_fd, flags) + finally: + os.close(replacement_fd) + +action = sys.argv[1] +config_dir = os.path.normpath(sys.argv[2]) +strict_hash_path = os.path.normpath(sys.argv[3]) +file_paths = [os.path.normpath(value) for value in sys.argv[4:]] +if action not in ("lock", "unlock"): + die("unsupported legacy Hermes transition: " + action) +parent_dir = os.path.dirname(config_dir) +config_name = os.path.basename(config_dir) +if not parent_dir or config_name in ("", ".", ".."): + die("invalid legacy Hermes config directory") + +names = [] +for file_path in file_paths: + if os.path.dirname(file_path) != config_dir: + die("legacy Hermes file escapes config directory: " + file_path) + names.append(os.path.basename(file_path)) +if set(names) != {"config.yaml", ".env", ".config-hash"} or len(names) != 3: + die("legacy Hermes transition requires config.yaml, .env, and .config-hash") + +sandbox_uid = pwd.getpwnam("sandbox").pw_uid +sandbox_gid = grp.getgrnam("sandbox").gr_gid +parent_fd = open_directory(parent_dir) +parent_initial_st = os.fstat(parent_fd) +parent_initial = metadata(parent_initial_st) +parent_initial_flags = inode_flags(parent_fd) +config_fd = None +config_initial = None +config_initial_flags = 0 +opened = {} +staged = {} +file_mutation_started = False +body_error = None +rollback_errors = [] +try: + clear_immutable(parent_fd) + os.fchown(parent_fd, 0, 0) + os.fchmod(parent_fd, 0o755) + + config_fd = open_directory(config_name, dir_fd=parent_fd) + config_initial_st = os.fstat(config_fd) + config_initial = metadata(config_initial_st) + config_initial_flags = clear_immutable(config_fd) + os.fchown(config_fd, 0, 0) + os.fchmod(config_fd, 0o700) + + for name, file_path in zip(names, file_paths): + fd, st = open_child_regular(config_fd, name, file_path) + opened[name] = { + "fd": fd, + "meta": metadata(st), + "flags": inode_flags(fd), + "data": read_fd( + fd, + MAX_HASH_BYTES if name == ".config-hash" else MAX_CONFIG_BYTES, + file_path, + ), + } + + strict_hash = read_strict_hash(strict_hash_path) + expected_hash = ( + hashlib.sha256(opened["config.yaml"]["data"]).hexdigest() + + " " + os.path.join(config_dir, "config.yaml") + "\n" + + hashlib.sha256(opened[".env"]["data"]).hexdigest() + + " " + os.path.join(config_dir, ".env") + "\n" + ).encode("utf-8") + if strict_hash != expected_hash: + die("strict hash verification failed for legacy Hermes shields transition") + if opened[".config-hash"]["data"] != strict_hash: + die("compat hash verification failed for legacy Hermes shields transition") + + desired_uid = 0 if action == "lock" else sandbox_uid + desired_gid = 0 if action == "lock" else sandbox_gid + desired_mode = 0o444 if action == "lock" else 0o640 + for name in names: + trusted = strict_hash if name == ".config-hash" else opened[name]["data"] + staged[name] = stage_file( + config_fd, name, trusted, desired_uid, desired_gid, desired_mode + ) + + for name in names: + current = os.stat(name, dir_fd=config_fd, follow_symlinks=False) + if not same_inode(current, opened[name]["meta"]): + die("legacy Hermes path changed during transition: " + name) + file_mutation_started = True + clear_immutable(opened[name]["fd"]) + os.replace(staged[name], name, src_dir_fd=config_fd, dst_dir_fd=config_fd) + staged.pop(name, None) + for temp in staged.values(): + try: + os.unlink(temp, dir_fd=config_fd) + except FileNotFoundError: + pass + + for name in names: + fd, st = open_child_regular(config_fd, name, name) + try: + trusted = strict_hash if name == ".config-hash" else opened[name]["data"] + if read_fd( + fd, + MAX_HASH_BYTES if name == ".config-hash" else MAX_CONFIG_BYTES, + name, + ) != trusted: + die("legacy Hermes replacement content mismatch for " + name) + if ( + st.st_uid != desired_uid + or st.st_gid != desired_gid + or stat.S_IMODE(st.st_mode) != desired_mode + ): + die("legacy Hermes replacement metadata mismatch for " + name) + finally: + os.close(fd) + + if action == "lock": + os.fchown(config_fd, 0, 0) + os.fchmod(config_fd, 0o755) + os.fchown(parent_fd, 0, sandbox_gid) + os.fchmod(parent_fd, 0o1775) + else: + os.fchown(config_fd, sandbox_uid, sandbox_gid) + os.fchmod(config_fd, 0o3770) + os.fchown(parent_fd, sandbox_uid, sandbox_gid) + os.fchmod(parent_fd, 0o755) + try: + os.fsync(config_fd) + except OSError: + pass +except BaseException as exc: + body_error = exc + if config_fd is not None and file_mutation_started: + for name, original in opened.items(): + try: + replace_with_bytes( + config_fd, + name, + original["data"], + original["meta"]["uid"], + original["meta"]["gid"], + original["meta"]["mode"], + original["flags"], + ) + except BaseException as rollback_error: + rollback_errors.append("%s: %s" % (name, rollback_error)) +finally: + if config_fd is not None: + for temp in staged.values(): + try: + os.unlink(temp, dir_fd=config_fd) + except OSError: + pass + for original in opened.values(): + try: + os.close(original["fd"]) + except OSError: + pass + if body_error is not None: + if config_fd is not None and config_initial is not None: + try: + os.fchown(config_fd, config_initial["uid"], config_initial["gid"]) + os.fchmod(config_fd, config_initial["mode"]) + set_inode_flags(config_fd, config_initial_flags) + except BaseException as rollback_error: + rollback_errors.append("config dir: %s" % rollback_error) + try: + os.fchown(parent_fd, parent_initial["uid"], parent_initial["gid"]) + os.fchmod(parent_fd, parent_initial["mode"]) + set_inode_flags(parent_fd, parent_initial_flags) + except BaseException as rollback_error: + rollback_errors.append("parent dir: %s" % rollback_error) + if config_fd is not None: + os.close(config_fd) + os.close(parent_fd) + +if body_error is not None: + message = str(body_error) + if rollback_errors: + message += "; rollback failed: " + "; ".join(rollback_errors) + raise RuntimeError(message) +`; + +function transitionLegacyHermesConfig( + sandboxName: string, + target: AgentConfigTarget, + action: "lock" | "unlock", + files: string[], +): void { + privilegedSandboxExec(sandboxName, [ + "python3", + "-I", + "-c", + LEGACY_HERMES_CONFIG_TRANSITION_SCRIPT, + action, + target.configDir, + HERMES_CONFIG_HASH, + ...files, + ]); +} + function unlockConfigPathsNoSymlinkFollow( sandboxName: string, target: AgentConfigTarget, @@ -491,6 +1434,7 @@ function unlockConfigPathsNoSymlinkFollow( ): void { privilegedSandboxExec(sandboxName, [ "python3", + "-I", "-c", CONFIG_UNLOCK_NOFOLLOW_SCRIPT, fileMode, @@ -539,7 +1483,12 @@ function assertNoLegacyStateLayout(sandboxName: string, configDir: string): void // read_only) + chown/chmod below. // --------------------------------------------------------------------------- -function unlockAgentConfig(sandboxName: string, rawTarget: AgentConfigTarget): void { +function unlockAgentConfigUnderMutationLock( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked: boolean, + protocol: HermesShieldsProtocol, +): void { const target = ensureConfigHashSensitiveFile(rawTarget); const errors: string[] = []; const filesToUnlock = [target.configPath, ...(target.sensitiveFiles || [])]; @@ -555,70 +1504,251 @@ function unlockAgentConfig(sandboxName: string, rawTarget: AgentConfigTarget): v // the gateway UID cannot remove sandbox-owned config files. const fileMode = target.agentName === "hermes" ? "640" : "660"; const dirMode = target.agentName === "hermes" ? "3770" : "2770"; - unlockConfigPathsNoSymlinkFollow(sandboxName, target, fileMode, dirMode, filesToUnlock); - - // NC-2227-05: Restore sandbox ownership on locked state directories. - // Use chown -R to restore the full tree (files within may have been - // locked to root:root by a prior shields-up). Surface fan-out issues - // so `shields down` cannot report success while a state dir is still - // root-owned or read-only. - const stateDirUnlockIssues = applyStateDirLockMode( - stateDirLockExec(sandboxName), - target.configDir, - "sandbox:sandbox", - false, - ); - for (const issue of stateDirUnlockIssues) { - errors.push(`state dir unlock: ${issue}`); - } + let transaction: { + token: string; + originalLocked: boolean; + rollbackLocked: boolean; + } | null = null; + const legacyHermesProtocol = target.agentName === "hermes" && protocol === "legacy"; + const openClawProtocol = target.agentName === "openclaw"; + let openClawMutationStarted = false; + try { + if (openClawProtocol) { + transitionOpenClawTopConfig(sandboxName, target, "preflight"); + } + if (target.agentName === "hermes" && !legacyHermesProtocol) { + transaction = beginHermesConfigShields( + sandboxName, + target, + "mutable", + rollbackLocked ? "locked" : "mutable", + ); + } + if (legacyHermesProtocol) { + transitionLegacyHermesConfig(sandboxName, target, "unlock", filesToUnlock); + } else if (target.agentName !== "hermes" && !openClawProtocol) { + unlockConfigPathsNoSymlinkFollow(sandboxName, target, fileMode, dirMode, filesToUnlock); + } - if (errors.length > 0) { - console.error( - ` Warning: Some unlock operations failed: ${errors.join(", ")}. Config may remain read-only.`, - ); - } + // Restore sandbox ownership while Hermes remains sealed and its top-level + // config directory is root-only. The final mutable inode transition is + // applied only after the recursive fan-out succeeds. + if (openClawProtocol) openClawMutationStarted = true; + if (transaction) { + // Keep the recursive worker under the same in-container token owner as + // the fresh-inode Hermes transaction. If the host Docker client dies, + // a later locked takeover can observe and wait for the exact worker + // identity instead of racing an orphaned unlock pass. + runHermesStateDirTransition(sandboxName, target, transaction.token, "unlock"); + } else { + const stateDirUnlockIssues = applyStateDirLockMode( + stateDirLockExec(sandboxName), + target.configDir, + "sandbox:sandbox", + false, + ); + for (const issue of stateDirUnlockIssues) errors.push(`state dir unlock: ${issue}`); + } + if (errors.length > 0) { + throw new Error(`Config not unlocked: ${errors.join(", ")}`); + } + + if (transaction) { + applyHermesConfigShields(sandboxName, target, transaction.token); + } else if (openClawProtocol) { + // Commit the top-level ownership handoff last. Until this succeeds the + // root-owned config directory and sticky root-owned /sandbox parent keep + // the canonical OpenClaw path bound while recursive state is prepared. + transitionOpenClawTopConfig(sandboxName, target, "unlock"); + } + + const issues: string[] = []; + for (const f of filesToUnlock) { + try { + const perms = privilegedSandboxExecCapture(sandboxName, ["stat", "-c", "%a %U:%G", f]); + const [mode, owner] = perms.split(" "); + if (mode !== fileMode) issues.push(`${f} mode=${mode} (expected ${fileMode})`); + if (owner !== "sandbox:sandbox") + issues.push(`${f} owner=${owner} (expected sandbox:sandbox)`); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + issues.push(`${f} stat failed: ${msg}`); + } + try { + const attrs = privilegedSandboxExecCapture(sandboxName, ["lsattr", "-d", f]); + const [flags] = attrs.trim().split(/\s+/, 1); + if (flags.includes("i")) issues.push(`${f} immutable bit still set`); + } catch { + // lsattr may not be available on all images — skip + } + } - const issues: string[] = []; - for (const f of filesToUnlock) { try { - const perms = privilegedSandboxExecCapture(sandboxName, ["stat", "-c", "%a %U:%G", f]); - const [mode, owner] = perms.split(" "); - if (mode !== fileMode) issues.push(`${f} mode=${mode} (expected ${fileMode})`); - if (owner !== "sandbox:sandbox") - issues.push(`${f} owner=${owner} (expected sandbox:sandbox)`); + const dirPerms = privilegedSandboxExecCapture(sandboxName, [ + "stat", + "-c", + "%a %U:%G", + target.configDir, + ]); + const [mode, owner] = dirPerms.split(" "); + if (mode !== dirMode) issues.push(`config dir mode=${mode} (expected ${dirMode})`); + if (owner !== "sandbox:sandbox") { + issues.push(`config dir owner=${owner} (expected sandbox:sandbox)`); + } } catch (err) { const msg = err instanceof Error ? err.message : String(err); - issues.push(`${f} stat failed: ${msg}`); + issues.push(`config dir stat failed: ${msg}`); } - try { - const attrs = privilegedSandboxExecCapture(sandboxName, ["lsattr", "-d", f]); - const [flags] = attrs.trim().split(/\s+/, 1); - if (flags.includes("i")) issues.push(`${f} immutable bit still set`); - } catch { - // lsattr may not be available on all images — skip + + if (openClawProtocol) { + try { + const parentPerms = privilegedSandboxExecCapture(sandboxName, [ + "stat", + "-c", + "%a %U:%G", + "/sandbox", + ]); + const [mode, owner] = parentPerms.split(" "); + if (mode !== "755") issues.push(`parent dir mode=${mode} (expected 755)`); + if (owner !== "sandbox:sandbox") { + issues.push(`parent dir owner=${owner} (expected sandbox:sandbox)`); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + issues.push(`parent dir stat failed: ${msg}`); + } } - } - try { - const dirPerms = privilegedSandboxExecCapture(sandboxName, [ - "stat", - "-c", - "%a %U:%G", - target.configDir, - ]); - const [mode, owner] = dirPerms.split(" "); - if (mode !== dirMode) issues.push(`config dir mode=${mode} (expected ${dirMode})`); - if (owner !== "sandbox:sandbox") { - issues.push(`config dir owner=${owner} (expected sandbox:sandbox)`); + if (issues.length > 0) throw new Error(`Config not unlocked: ${issues.join(", ")}`); + if (transaction) { + finishHermesConfigShields(sandboxName, target, transaction.token); } - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - issues.push(`config dir stat failed: ${msg}`); + } catch (error) { + if (transaction) { + try { + prepareHermesConfigShieldsAbort(sandboxName, target, transaction.token); + runHermesStateDirTransition( + sandboxName, + target, + transaction.token, + transaction.rollbackLocked ? "lock" : "unlock", + ); + abortHermesConfigShields(sandboxName, target, transaction.token); + } catch (abortError) { + const message = abortError instanceof Error ? abortError.message : String(abortError); + console.error( + ` CRITICAL: Hermes shields rollback preparation failed; the root transaction remains sealed. Restore from a trusted backup and recreate the sandbox. ${message}`, + ); + } + } else if (legacyHermesProtocol) { + const rollbackIssues: string[] = []; + try { + transitionLegacyHermesConfig( + sandboxName, + target, + rollbackLocked ? "lock" : "unlock", + filesToUnlock, + ); + } catch (rollbackError) { + rollbackIssues.push( + `top-level config rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + try { + rollbackIssues.push( + ...restoreStateDirLockPosture( + stateDirLockExec(sandboxName), + target.configDir, + rollbackLocked, + ), + ); + } catch (rollbackError) { + rollbackIssues.push( + `state-directory rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + if (rollbackIssues.length > 0) { + console.error( + ` CRITICAL: Legacy Hermes unlock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox. ${rollbackIssues.join(", ")}`, + ); + } + } else if (openClawProtocol && openClawMutationStarted) { + const rollbackIssues: string[] = []; + const restoreTop = (action: "lock" | "unlock") => { + try { + transitionOpenClawTopConfig(sandboxName, target, action); + } catch (rollbackError) { + rollbackIssues.push( + `top-level config rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + }; + const restoreState = () => { + try { + rollbackIssues.push( + ...restoreStateDirLockPosture( + stateDirLockExec(sandboxName), + target.configDir, + rollbackLocked, + ), + ); + } catch (rollbackError) { + rollbackIssues.push( + `state-directory rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + }; + if (rollbackLocked) { + restoreTop("lock"); + restoreState(); + } else { + restoreState(); + restoreTop("unlock"); + } + if (rollbackIssues.length > 0) { + console.error( + ` CRITICAL: OpenClaw unlock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox. ${rollbackIssues.join(", ")}`, + ); + } + } + throw error; } +} - if (issues.length > 0) { - throw new Error(`Config not unlocked: ${issues.join(", ")}`); - } +function unlockAgentConfigWithoutHostLock( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked = getShieldsPosture(sandboxName, false).locked, + allowLegacyHermesProtocol = false, + cachedProtocol?: HermesShieldsProtocol, +): void { + const target = ensureConfigHashSensitiveFile(rawTarget); + const protocol = resolveHermesShieldsProtocol( + sandboxName, + target, + allowLegacyHermesProtocol, + cachedProtocol, + ); + return unlockAgentConfigUnderMutationLock(sandboxName, target, rollbackLocked, protocol); +} + +function unlockAgentConfig( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked?: boolean, + allowLegacyHermesProtocol = false, + cachedProtocol?: HermesShieldsProtocol, +): void { + return withShieldsTransitionLock(sandboxName, "unlock agent config", () => { + const effectiveRollbackLocked = rollbackLocked ?? getShieldsPosture(sandboxName, false).locked; + return unlockAgentConfigWithoutHostLock( + sandboxName, + rawTarget, + effectiveRollbackLocked, + allowLegacyHermesProtocol, + cachedProtocol, + ); + }); } // --------------------------------------------------------------------------- @@ -634,18 +1764,32 @@ function unlockAgentConfig(sandboxName: string, rawTarget: AgentConfigTarget): v function inspectMutableConfigPerms(sandboxName: string): MutableConfigPermsInspection { validateName(sandboxName, "sandbox name"); - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); - return inspectMutableConfigPermsCore(target, getShieldsPosture(sandboxName, true).mode, (p) => - privilegedSandboxExecCapture(sandboxName, ["stat", "-c", "%a %U:%G", p]), + prepareExpiredAutoRestoreHostLockTakeover(sandboxName); + return withTimerBoundShieldsMutationLock( + sandboxName, + "inspect mutable config permissions", + () => { + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + return inspectMutableConfigPermsCore( + target, + getShieldsPostureWithoutHostLock(sandboxName, true).mode, + (p) => privilegedSandboxExecCapture(sandboxName, ["stat", "-c", "%a %U:%G", p]), + ); + }, ); } function repairMutableConfigPerms(sandboxName: string): MutableConfigRepairResult { validateName(sandboxName, "sandbox name"); - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); - return repairMutableConfigPermsCore(target, getShieldsPosture(sandboxName, true).mode, () => - unlockAgentConfig(sandboxName, target), - ); + prepareExpiredAutoRestoreHostLockTakeover(sandboxName); + return withTimerBoundShieldsMutationLock(sandboxName, "repair mutable config permissions", () => { + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + return repairMutableConfigPermsCore( + target, + getShieldsPostureWithoutHostLock(sandboxName, true).mode, + () => unlockAgentConfig(sandboxName, target), + ); + }); } // --------------------------------------------------------------------------- @@ -676,130 +1820,355 @@ function captureSealHashes(sandboxName: string, filesToHash: string[]): { [path: const msg = err instanceof Error ? err.message : String(err); throw new Error(`sha256sum ${f} failed: ${msg}`); } - const hex = parseSha256Output(raw); - if (!hex) { - throw new Error(`sha256sum ${f} returned unparsable output: ${raw}`); + const hex = parseSha256Output(raw); + if (!hex) { + throw new Error(`sha256sum ${f} returned unparsable output: ${raw}`); + } + hashes[f] = hex; + } + return hashes; +} + +function lockAgentConfigUnderMutationLock( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked: boolean, + protocol: HermesShieldsProtocol, +): { chattrApplied: boolean; fileHashes: { [path: string]: string } } { + const target = ensureConfigHashSensitiveFile(rawTarget); + const errors: string[] = []; + const filesToLock = [target.configPath, ...(target.sensitiveFiles || [])]; + const openClawProtocol = target.agentName === "openclaw"; + let transaction: { + token: string; + originalLocked: boolean; + rollbackLocked: boolean; + } | null = null; + const legacyHermesProtocol = target.agentName === "hermes" && protocol === "legacy"; + let openClawMutationStarted = false; + let chattrSucceeded = target.agentName === "hermes" && !legacyHermesProtocol ? false : true; + + // Agents without a descriptor-sealed top-level transaction retain the + // historical validate-before-mutate ordering. OpenClaw and current Hermes + // must revoke writes to their canonical config first: otherwise an agent can + // plant one invalid nested entry and veto the auto-restore deadline forever. + if (!openClawProtocol && (target.agentName !== "hermes" || legacyHermesProtocol)) { + const preflightIssues = preflightStateDirLock(stateDirLockExec(sandboxName), target.configDir); + if (preflightIssues.length > 0) { + throw new Error(`Config not locked: ${preflightIssues.join(", ")}`); + } + } + + try { + if (target.agentName === "hermes" && !legacyHermesProtocol) { + transaction = beginHermesConfigShields( + sandboxName, + target, + "locked", + rollbackLocked ? "locked" : "mutable", + ); + } + if (openClawProtocol) { + openClawMutationStarted = true; + // This is the containment boundary: freeze and fresh-seal the canonical + // pair before inspecting attacker-writable descendant state. + chattrSucceeded = transitionOpenClawTopConfig(sandboxName, target, "lock"); + } else if (legacyHermesProtocol) { + transitionLegacyHermesConfig(sandboxName, target, "lock", filesToLock); + } else if (target.agentName !== "hermes") { + for (const f of filesToLock) { + try { + privilegedSandboxExec(sandboxName, ["chmod", "444", f]); + } catch { + errors.push(`chmod 444 ${f}`); + } + try { + privilegedSandboxExec(sandboxName, ["chown", "root:root", f]); + } catch { + errors.push(`chown root:root ${f}`); + } + } + try { + privilegedSandboxExec(sandboxName, ["chmod", "755", target.configDir]); + } catch { + errors.push("chmod 755 config dir"); + } + try { + privilegedSandboxExec(sandboxName, ["chown", "root:root", target.configDir]); + } catch { + errors.push("chown root:root config dir"); + } + } + + // For Hermes, the guard applies immutable flags to the fresh sealed + // inodes. Other agents keep the existing best-effort host path. + if (!openClawProtocol && (target.agentName !== "hermes" || legacyHermesProtocol)) { + for (const f of filesToLock) { + try { + privilegedSandboxExec(sandboxName, ["chattr", "+i", f]); + } catch { + chattrSucceeded = false; + } + } + } + + if (transaction) { + runHermesStateDirTransition(sandboxName, target, transaction.token, "lock"); + } else { + const stateDirLockIssues = applyStateDirLockMode( + stateDirLockExec(sandboxName), + target.configDir, + "root:sandbox", + true, + ); + if (stateDirLockIssues.length > 0) { + throw new Error(`Config not locked: ${stateDirLockIssues.join(", ")}`); + } + } + + if (!openClawProtocol) { + try { + privilegedSandboxExec(sandboxName, ["chmod", "g-s", target.configDir]); + } catch { + errors.push("chmod g-s config dir"); + } + try { + privilegedSandboxExec(sandboxName, ["chmod", "755", target.configDir]); + } catch { + errors.push("chmod 755 config dir"); + } + } + if (errors.length > 0) { + console.error(` Some lock operations failed: ${errors.join(", ")}`); } - hashes[f] = hex; - } - return hashes; -} -function lockAgentConfig( - sandboxName: string, - rawTarget: AgentConfigTarget, -): { chattrApplied: boolean; fileHashes: { [path: string]: string } } { - const target = ensureConfigHashSensitiveFile(rawTarget); - const errors: string[] = []; - const filesToLock = [target.configPath, ...(target.sensitiveFiles || [])]; + if (transaction) { + chattrSucceeded = applyHermesConfigShields(sandboxName, target, transaction.token); + } - // Symlink preflight runs before any file or directory mutation: if a - // pre-lockdown agent swapped e.g. `extensions/` for a symlink to /etc, - // we abort before the privileged chmod/chown touches anything, so the - // tree is never half-mutated against an attacker-controlled host path. - const preflightIssues = preflightStateDirLock(stateDirLockExec(sandboxName), target.configDir); - if (preflightIssues.length > 0) { - throw new Error(`Config not locked: ${preflightIssues.join(", ")}`); - } + const { issues } = verifyShieldsLockState(sandboxName, target, { + verifyChattr: chattrSucceeded, + verifyParentProtection: target.agentName === "hermes" || openClawProtocol, + exec: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), + assertLegacyLayout: assertNoLegacyStateLayout, + }); + if (issues.length > 0) throw new Error(`Config not locked: ${issues.join(", ")}`); - for (const f of filesToLock) { - try { - privilegedSandboxExec(sandboxName, ["chmod", "444", f]); - } catch { - errors.push(`chmod 444 ${f}`); + const fileHashes = captureSealHashes(sandboxName, filesToLock); + if (transaction) { + finishHermesConfigShields(sandboxName, target, transaction.token); } - try { - privilegedSandboxExec(sandboxName, ["chown", "root:root", f]); - } catch { - errors.push(`chown root:root ${f}`); + return { chattrApplied: chattrSucceeded, fileHashes }; + } catch (error) { + if (transaction && !transaction.rollbackLocked) { + // The requested direction is hardening from a mutable posture. Once the + // root guard has frozen the canonical Hermes config, a nested-state + // finding must not hand mutation authority back to the sandbox. Commit + // the top-level locked posture and leave shields state DOWN so the timer + // retains authority and retries the remaining recursive work. + try { + applyHermesConfigShields(sandboxName, target, transaction.token); + finishHermesConfigShields(sandboxName, target, transaction.token); + } catch (containmentError) { + const message = + containmentError instanceof Error ? containmentError.message : String(containmentError); + console.error( + ` CRITICAL: Hermes lock failed after containment began; the root transaction remains sealed. Restore from a trusted backup and recreate the sandbox. ${message}`, + ); + } + } else if (transaction) { + try { + prepareHermesConfigShieldsAbort(sandboxName, target, transaction.token); + runHermesStateDirTransition( + sandboxName, + target, + transaction.token, + transaction.rollbackLocked ? "lock" : "unlock", + ); + abortHermesConfigShields(sandboxName, target, transaction.token); + } catch (abortError) { + const message = abortError instanceof Error ? abortError.message : String(abortError); + console.error( + ` CRITICAL: Hermes shields rollback preparation failed; the root transaction remains sealed. Restore from a trusted backup and recreate the sandbox. ${message}`, + ); + } + } else if (openClawProtocol && openClawMutationStarted) { + const rollbackIssues: string[] = []; + const restoreTop = (action: "lock" | "unlock") => { + try { + transitionOpenClawTopConfig(sandboxName, target, action); + } catch (rollbackError) { + rollbackIssues.push( + `top-level config rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + }; + const restoreState = () => { + try { + rollbackIssues.push( + ...restoreStateDirLockPosture( + stateDirLockExec(sandboxName), + target.configDir, + rollbackLocked, + ), + ); + } catch (rollbackError) { + rollbackIssues.push( + `state-directory rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, + ); + } + }; + if (rollbackLocked) { + restoreTop("lock"); + restoreState(); + } else { + // Preserve the canonical config seal. The caller records shields as + // still DOWN and the timer retries recursive containment; reopening + // the top-level pair here would make one planted nested entry an + // attacker-controlled veto over the restore deadline. + restoreTop("lock"); + } + if (rollbackIssues.length > 0) { + console.error( + ` CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox. ${rollbackIssues.join(", ")}`, + ); + } } + throw error; } +} - try { - privilegedSandboxExec(sandboxName, ["chmod", "755", target.configDir]); - } catch { - errors.push("chmod 755 config dir"); - } - - try { - privilegedSandboxExec(sandboxName, ["chown", "root:root", target.configDir]); - } catch { - errors.push("chown root:root config dir"); +function synchronizeAutoRestoreTransition( + sandboxName: string, + processToken: string, + snapshotPath: string, +): void { + const transition = waitForShieldsDownForwardCommit(sandboxName, processToken); + if (!transition) return; + if (transition.snapshotPath !== snapshotPath) { + throw new Error("Auto-restore snapshot does not match shields-down transition ownership"); } - // Best-effort: kubectl exec may lack CAP_LINUX_IMMUTABLE. Track the - // result so verification doesn't require something that was never there. - let chattrSucceeded = true; - for (const f of filesToLock) { - try { - privilegedSandboxExec(sandboxName, ["chattr", "+i", f]); - } catch { - chattrSucceeded = false; - } + // The timer restores policy before calling lockAgentConfig. If it expired + // while shieldsDown was still applying the permissive policy or unlocking + // config, that first restore may have been overwritten. The phase handshake + // above waits until the forward path has either committed its last weakening + // mutation or its owner has died; restore the restrictive snapshot again at + // that stable boundary before locking config. + const restoreResult = run(buildPolicySetCommand(transition.snapshotPath, sandboxName), { + ignoreError: true, + }); + const status = typeof restoreResult.status === "number" ? restoreResult.status : 1; + if (status !== 0) { + throw new Error( + `Policy restore after shields-down handoff exited with status ${String(status)}`, + ); } + clearShieldsDownTransition(sandboxName, processToken); +} - // Lock state directories. High-risk dirs use `root:sandbox` ownership so - // the gateway (in the sandbox group) can still read plugin/agent code while - // the sandbox user is denied write through `chmod -R go-w`. Secret-bearing - // dirs (CONFIDENTIALITY_STATE_DIRS in ./state-dir-lock) go to `root:root` - // 700/go-rwX so neither the sandbox user nor the gateway can read them - // while shields are up. Top-level configDir stays root:root. - const stateDirLockIssues = applyStateDirLockMode( - stateDirLockExec(sandboxName), - target.configDir, - "root:sandbox", - true, - ); - if (stateDirLockIssues.length > 0) { - // Symlinked state-dir roots are a security-relevant violation: - // continuing would let shields-up report "locked" while a state - // dir still points at a writable host path. Refuse the lock. - throw new Error(`Config not locked: ${stateDirLockIssues.join(", ")}`); +function prepareAutoRestoreTransitionTakeover( + sandboxName: string, + processToken: string, + snapshotPath: string, +): void { + if (!/^[0-9a-f]{32}$/.test(processToken)) { + throw new Error("Invalid auto-restore transition takeover token"); } - // OpenClaw's mutable-default config root is setgid (#2681). Clear setgid - // after descendant locking so shields-up verifies the root config dir as - // plain 755, not 2755. - try { - privilegedSandboxExec(sandboxName, ["chmod", "g-s", target.configDir]); - } catch { - errors.push("chmod g-s config dir"); + const transition = readShieldsDownTransition(sandboxName, processToken); + if (transition && transition.snapshotPath !== snapshotPath) { + throw new Error("Auto-restore snapshot does not match shields-down transition ownership"); } - try { - privilegedSandboxExec(sandboxName, ["chmod", "755", target.configDir]); - } catch { - errors.push("chmod 755 config dir"); + if (transition) { + // This waits briefly for the forward commit and stops its exact process + // tree if the deadline fired while it was still weakening the sandbox. + waitForShieldsDownForwardCommit(sandboxName, processToken); } - if (errors.length > 0) { - console.error(` Some lock operations failed: ${errors.join(", ")}`); + const owner = inspectShieldsTransitionLockOwner(sandboxName, processToken); + if (!owner) return; + if ( + isProcessAlive(owner.pid) && + readProcessStartIdentity(owner.pid) === owner.processStartIdentity + ) { + // The same timer token is also propagated to config/inference/restart + // mutations made during the mutable window. At expiry those operations + // are weaker than restoring lockdown and may be preempted safely. + stopTimedOutShieldsDownTree(owner.pid, owner.processStartIdentity); } + const takeover = takeoverShieldsTransitionLock( + sandboxName, + owner.pid, + owner.processStartIdentity, + processToken, + ); + if ( + !takeover.removed && + takeover.reason !== "missing" && + takeover.reason !== "path-changed" && + takeover.reason !== "owner-mismatch" + ) { + throw new Error(`Cannot take over expired shields transition lock: ${takeover.reason}`); + } +} - // Verify the lock actually took effect. - // Mode + ownership are mandatory (layers 1+2 depend on them). - // Immutable bit is only verified if chattr succeeded above. - const { issues } = verifyShieldsLockState(sandboxName, target, { - verifyChattr: chattrSucceeded, - exec: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), - assertLegacyLayout: assertNoLegacyStateLayout, - }); - - if (issues.length > 0) { - throw new Error(`Config not locked: ${issues.join(", ")}`); +function synchronizeAutoRestoreWithShieldsDown(sandboxName: string): void { + const timerMarker = readTimerMarker(sandboxName); + if ( + !timerMarker || + timerMarker.pid !== process.pid || + !timerMarker.processToken || + !/^[0-9a-f]{32}$/.test(timerMarker.processToken) + ) { + return; } + synchronizeAutoRestoreTransition(sandboxName, timerMarker.processToken, timerMarker.snapshotPath); +} - // Mode + ownership are clean; capture the SHA-256 seal of each locked - // file so `shields status` can detect content drift even when an - // attacker restores the mode/owner after writing. - const fileHashes = captureSealHashes(sandboxName, filesToLock); +function lockAgentConfigWithoutHostLock( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked = getShieldsPosture(sandboxName, false).locked, + allowLegacyHermesProtocol = false, + cachedProtocol?: HermesShieldsProtocol, +): { chattrApplied: boolean; fileHashes: { [path: string]: string } } { + const target = ensureConfigHashSensitiveFile(rawTarget); + const protocol = resolveHermesShieldsProtocol( + sandboxName, + target, + allowLegacyHermesProtocol, + cachedProtocol, + ); + synchronizeAutoRestoreWithShieldsDown(sandboxName); + return lockAgentConfigUnderMutationLock(sandboxName, target, rollbackLocked, protocol); +} - return { chattrApplied: chattrSucceeded, fileHashes }; +function lockAgentConfig( + sandboxName: string, + rawTarget: AgentConfigTarget, + rollbackLocked?: boolean, + allowLegacyHermesProtocol = false, + cachedProtocol?: HermesShieldsProtocol, +): { chattrApplied: boolean; fileHashes: { [path: string]: string } } { + return withShieldsTransitionLock(sandboxName, "lock agent config", () => { + const effectiveRollbackLocked = rollbackLocked ?? getShieldsPosture(sandboxName, false).locked; + return lockAgentConfigWithoutHostLock( + sandboxName, + rawTarget, + effectiveRollbackLocked, + allowLegacyHermesProtocol, + cachedProtocol, + ); + }); } function rollbackShieldsDown( sandboxName: string, target: AgentConfigTarget, snapshotPath: string, + allowLegacyHermesProtocol = false, + cachedProtocol?: HermesShieldsProtocol, ): void { console.error(" Rolling back — restoring policy from snapshot..."); const rollbackResult = run(buildPolicySetCommand(snapshotPath, sandboxName), { @@ -812,7 +2181,9 @@ function rollbackShieldsDown( // the rolled-back config DRIFTED — same fail-closed treatment as the // auto-restore path. Leaves the hashes null (→ "manual intervention" // below) when the lock will not re-confirm. - const relock = relockAndReconfirm(() => lockAgentConfig(sandboxName, target)); + const relock = relockAndReconfirm(() => + lockAgentConfig(sandboxName, target, true, allowLegacyHermesProtocol, cachedProtocol), + ); if (relock.ok && relock.lastResult) { rollbackChattrApplied = relock.lastResult.chattrApplied; rollbackFileHashes = relock.lastResult.fileHashes; @@ -853,6 +2224,9 @@ interface LockdownActivationResult { function activateLockdownFromSnapshot( sandboxName: string, snapshotPath: string, + allowLegacyHermesProtocol = false, + cachedTarget?: AgentConfigTarget, + cachedProtocol?: HermesShieldsProtocol, ): LockdownActivationResult { if (!snapshotPath || !fs.existsSync(snapshotPath)) { return { ok: false, error: "saved snapshot is missing" }; @@ -869,13 +2243,29 @@ function activateLockdownFromSnapshot( }; } - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const target = ensureConfigHashSensitiveFile(cachedTarget ?? resolveAgentConfig(sandboxName)); + let protocol: HermesShieldsProtocol; + try { + protocol = resolveHermesShieldsProtocol( + sandboxName, + target, + allowLegacyHermesProtocol, + cachedProtocol, + ); + } catch (error) { + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } // Re-confirm the lock after a settle window. This restore feeds the // auto-restore inline recovery and the `shields up` snapshot path, both of // which mark shields UP on this result — so a reconciler revert here would // otherwise leave the same DRIFTED state #4663 is about. relockAndReconfirm // fails closed (ok:false) when the lock will not hold past the settle window. - const relock = relockAndReconfirm(() => lockAgentConfig(sandboxName, target)); + const relock = relockAndReconfirm(() => + lockAgentConfig(sandboxName, target, false, allowLegacyHermesProtocol, protocol), + ); if (!relock.ok || !relock.lastResult) { return { ok: false, @@ -909,14 +2299,52 @@ function recoverExpiredAutoRestoreInline( // recovery forever and reproduce the #3112 fail-open. Treat a live PID as // "our timer" only if cmdline + sandbox + processToken match. if (isProcessAlive(marker.pid) && verifyTimerMarkerIdentity(marker).verified) { - return { attempted: false, restored: false }; + if (Date.now() <= restoreAtMs + AUTO_RESTORE_COMPLETION_GRACE_MS) { + return { attempted: false, restored: false }; + } + const timerStartIdentity = readProcessStartIdentity(marker.pid); + if (!timerStartIdentity) { + console.error( + " Recovery warning: expired auto-restore timer identity cannot be pinned safely.", + ); + return { attempted: true, restored: false }; + } + try { + stopTimedOutShieldsDownTree(marker.pid, timerStartIdentity); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(` Recovery warning: ${message}`); + return { attempted: true, restored: false }; + } } console.error( " Warning: auto-restore timer marker is expired and the timer process is not the recorded shields timer; attempting inline restore.", ); - const activation = activateLockdownFromSnapshot(sandboxName, marker.snapshotPath); + if (marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { + try { + synchronizeAutoRestoreTransition(sandboxName, marker.processToken, marker.snapshotPath); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + appendAuditEntry({ + action: "shields_up_failed", + sandbox: sandboxName, + timestamp: new Date().toISOString(), + restored_by: "auto_timer", + policy_snapshot: marker.snapshotPath, + error: `Inline auto-restore handoff failed: ${message}`, + }); + console.error(` Recovery warning: ${message}`); + return { attempted: true, restored: false }; + } + } + + const activation = activateLockdownFromSnapshot( + sandboxName, + marker.snapshotPath, + marker.allowLegacyHermesProtocol === true, + ); const nowIso = new Date().toISOString(); if (!activation.ok) { appendAuditEntry({ @@ -945,6 +2373,9 @@ function recoverExpiredAutoRestoreInline( } : {}), }); + if (marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { + clearShieldsDownTransition(sandboxName, marker.processToken); + } clearTimerMarker(sandboxName); appendAuditEntry({ action: "shields_auto_restore", @@ -985,9 +2416,15 @@ interface ShieldsDownOpts { policy?: string; skipTimer?: boolean; throwOnError?: boolean; + allowLegacyHermesProtocol?: boolean; + // Internal rebuild lease: once the deadline expires, the detached recovery + // owner defers while this exact process is alive and retries transient + // restore failures after owner death. Interactive shields-down never sets it. + deferAutoRestoreWhileOwnerAlive?: boolean; + processToken?: string; } -function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { +function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = {}): void { validateName(sandboxName, "sandbox name"); const state = loadShieldsState(sandboxName); @@ -999,6 +2436,18 @@ function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { return failShieldsCommand(`Config is already unlocked for ${sandboxName}`, opts.throwOnError); } + // Resolve the old-image compatibility contract before touching timers, + // host state, policy, or sandbox files. A transport failure or an + // unsupported/incomplete guard must leave an ordinary shields command with + // no partial mutation. The result is pinned for the complete transition so + // a later probe failure cannot silently switch a sealed path to legacy. + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const protocol = requireHermesShieldsProtocol( + sandboxName, + target, + opts.allowLegacyHermesProtocol === true, + ); + // Kill stale auto-restore markers only when this command will actually // transition into shields-down. A repeated shields-down must not cancel the // active timer and leave the sandbox unlocked indefinitely. @@ -1055,59 +2504,48 @@ function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { return failShieldsCommand(`Unknown policy "${policyName}"`, opts.throwOnError); } - console.log(` Applying ${policyName} policy...`); - try { - run(buildPolicySetCommand(policyFile, sandboxName)); - } finally { - if (policyFileIsTemp) { - cleanupTempDir(policyFile, "nemoclaw-permissive-runtime"); - } - } - - // 2b. Return config to default mutable state. - // OpenClaw uses sandbox:sandbox 0660/2770 here so the gateway UID, which - // is a member of the sandbox group, can mutate runtime config. - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); - console.log(` Unlocking ${target.agentName} config (${target.configPath})...`); - try { - unlockAgentConfig(sandboxName, target); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - rollbackShieldsDown(sandboxName, target, snapshotPath); - console.error(` ERROR: ${message}`); - console.error( - " Config did not reach the mutable-default state; refusing to save shields-down state.", - ); - console.error( - ` Re-run \`nemoclaw ${sandboxName} shields down\` after correcting file ownership.`, - ); - return failShieldsCommand(message, opts.throwOnError); - } - - // 3. Update state const now = new Date().toISOString(); - saveShieldsState(sandboxName, { - shieldsDown: true, - shieldsDownAt: now, - shieldsDownTimeout: timeoutSeconds, - shieldsDownReason: reason, - shieldsDownPolicy: policyName, - shieldsPolicySnapshotPath: snapshotPath, - }); + let transition: ShieldsDownTransition | null = null; - // 4. Start auto-restore timer (detached child process), unless skipped. - // Pass the absolute restore time, not a relative timeout. Steps 1-2b - // can take minutes (policy apply + kubectl chmod), so a relative timeout - // passed at fork time would fire too early. + // Commit the host-side recovery authority before weakening policy or file + // permissions. If this process is killed later, the detached timer and its + // marker already exist and the persisted state honestly reports shields + // down. A crash can therefore never leave an untracked mutable window. if (!opts.skipTimer) { const restoreAt = new Date(Date.now() + timeoutSeconds * 1000); - const processToken = randomBytes(16).toString("hex"); + const processToken = opts.processToken ?? randomBytes(16).toString("hex"); + if (!/^[0-9a-f]{32}$/.test(processToken)) { + throw new Error("Invalid shields-down recovery process token"); + } const timerScript = path.join(__dirname, "timer.ts"); const timerScriptJs = timerScript.replace(/\.ts$/, ".js"); const actualScript = fs.existsSync(timerScriptJs) ? timerScriptJs : timerScript; + transition = { + version: 1, + phase: "preparing", + ownerPid: process.pid, + ownerStartIdentity: + readProcessStartIdentity(process.pid) ?? + (() => { + throw new Error("Cannot identify shields-down owner process"); + })(), + processToken, + sandboxName, + snapshotPath, + }; + const leaseOwnerPid = opts.deferAutoRestoreWhileOwnerAlive ? transition.ownerPid : null; + const leaseOwnerStartIdentity = opts.deferAutoRestoreWhileOwnerAlive + ? transition.ownerStartIdentity + : null; + let timerChild: ReturnType | null = null; try { - const child = fork( + // Publish the forward-transition ownership marker before authorizing the + // timer. If the timeout expires while this command is still weakening + // policy/config, the timer waits for phase=active or owner death instead + // of racing the forward mutations. + writeShieldsDownTransition(transition, null); + timerChild = fork( actualScript, [ sandboxName, @@ -1116,36 +2554,128 @@ function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { target.configPath, target.configDir, processToken, + opts.allowLegacyHermesProtocol === true ? "1" : "0", + leaseOwnerPid === null ? "" : String(leaseOwnerPid), + leaseOwnerStartIdentity ?? "", ], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], }, ); - child.disconnect(); - child.unref(); - - // Write timer marker - const markerPath = timerMarkerPath(sandboxName); + if (!timerChild.pid) throw new Error("auto-restore timer did not report a process id"); fs.writeFileSync( - markerPath, + timerMarkerPath(sandboxName), JSON.stringify({ - pid: child.pid, + pid: timerChild.pid, sandboxName, snapshotPath, restoreAt: restoreAt.toISOString(), processToken, + allowLegacyHermesProtocol: opts.allowLegacyHermesProtocol === true, + ...(leaseOwnerPid !== null && leaseOwnerStartIdentity + ? { leaseOwnerPid, leaseOwnerStartIdentity } + : {}), }), { mode: 0o600 }, ); + if (!timerChild.send({ type: "authorize", processToken })) { + throw new Error("auto-restore timer authorization channel closed early"); + } + timerChild.disconnect(); + timerChild.unref(); } catch (err) { + try { + timerChild?.kill("SIGTERM"); + } catch { + // Best effort; without a matching marker the child has no authority. + } + clearTimerMarker(sandboxName); + clearShieldsDownTransition(sandboxName, processToken); const message = err instanceof Error ? err.message : String(err); console.error(` Cannot start auto-restore timer: ${message}`); - rollbackShieldsDown(sandboxName, target, snapshotPath); return failShieldsCommand(`Cannot start auto-restore timer: ${message}`, opts.throwOnError); } } + try { + saveShieldsState(sandboxName, { + shieldsDown: true, + shieldsDownAt: now, + shieldsDownTimeout: timeoutSeconds, + shieldsDownReason: reason, + shieldsDownPolicy: policyName, + shieldsPolicySnapshotPath: snapshotPath, + }); + } catch (error) { + if (transition) { + clearShieldsDownTransition(sandboxName, transition.processToken); + killTimer(sandboxName); + } + throw error; + } + + console.log(` Applying ${policyName} policy...`); + try { + run(buildPolicySetCommand(policyFile, sandboxName)); + } finally { + if (policyFileIsTemp) { + cleanupTempDir(policyFile, "nemoclaw-permissive-runtime"); + } + } + + // 2b. Return config to default mutable state. + // OpenClaw uses sandbox:sandbox 0660/2770 here so the gateway UID, which + // is a member of the sandbox group, can mutate runtime config. + console.log(` Unlocking ${target.agentName} config (${target.configPath})...`); + try { + unlockAgentConfig( + sandboxName, + target, + deriveShieldsMode(state, state._hasStateFile) === "locked", + opts.allowLegacyHermesProtocol === true, + protocol, + ); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + rollbackShieldsDown( + sandboxName, + target, + snapshotPath, + opts.allowLegacyHermesProtocol === true, + protocol, + ); + if (transition) clearShieldsDownTransition(sandboxName, transition.processToken); + console.error(` ERROR: ${message}`); + console.error( + " Config did not reach the mutable-default state; the scheduled auto-restore remains authoritative.", + ); + console.error( + ` Re-run \`nemoclaw ${sandboxName} shields down\` after correcting file ownership.`, + ); + return failShieldsCommand(message, opts.throwOnError); + } + + if (transition) { + try { + transition = { ...transition, phase: "active" }; + writeShieldsDownTransition(transition, "preparing"); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + rollbackShieldsDown( + sandboxName, + target, + snapshotPath, + opts.allowLegacyHermesProtocol === true, + protocol, + ); + clearShieldsDownTransition(sandboxName, transition.processToken); + console.error(` ERROR: ${message}`); + console.error(" Auto-restore handoff failed; lockdown was restored."); + return failShieldsCommand(message, opts.throwOnError); + } + } + // 5. Audit log appendAuditEntry({ action: "shields_down", @@ -1174,6 +2704,24 @@ function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { } } +function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { + validateName(sandboxName, "sandbox name"); + const processToken = opts.skipTimer + ? undefined + : (opts.processToken ?? randomBytes(16).toString("hex")); + const effectiveOpts = processToken ? { ...opts, processToken } : opts; + try { + return withShieldsTransitionLock( + sandboxName, + "shields down", + () => shieldsDownWithoutHostLock(sandboxName, effectiveOpts), + processToken ? { takeoverToken: processToken } : {}, + ); + } catch (error) { + return completeDeferredShieldsExit(error, opts.throwOnError === true); + } +} + // --------------------------------------------------------------------------- // shields up — opt into lockdown // @@ -1181,7 +2729,10 @@ function shieldsDown(sandboxName: string, opts: ShieldsDownOpts = {}): void { // hardening step that restricts the sandbox beyond its default state. // --------------------------------------------------------------------------- -function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): void { +function shieldsUpWithoutHostLock( + sandboxName: string, + opts: { throwOnError?: boolean; allowLegacyHermesProtocol?: boolean } = {}, +): void { validateName(sandboxName, "sandbox name"); const state = loadShieldsState(sandboxName); @@ -1195,6 +2746,7 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); const { issues } = verifyShieldsLockState(sandboxName, target, { verifyChattr: state.chattrApplied === true, + verifyParentProtection: target.agentName === "openclaw" || target.agentName === "hermes", exec: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), assertLegacyLayout: assertNoLegacyStateLayout, expectedHashes: state.fileHashes, @@ -1281,13 +2833,20 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): // missing-seal entries that the operator has just opted in to. In // both cases re-applying the lock rewrites perms and captures a // fresh, complete seal. + const protocol = requireHermesShieldsProtocol( + sandboxName, + target, + opts.allowLegacyHermesProtocol === true, + ); console.log(` Lockdown drifted — re-applying lock for ${sandboxName}...`); // #4663: re-confirm the lock held after the in-sandbox reconciler settles, // re-applying if it reverts perms. A single re-apply here was also being // reverted on DGX Station / DGX Spark, leaving the sandbox DRIFTED. This // narrows (does not close) the revert window; the chattr +i immutable bit // applied inside lockAgentConfig is the only fully durable defense. - const relock = relockAndReconfirm(() => lockAgentConfig(sandboxName, target)); + const relock = relockAndReconfirm(() => + lockAgentConfig(sandboxName, target, true, opts.allowLegacyHermesProtocol === true, protocol), + ); if (!relock.ok || !relock.lastResult) { const message = relock.error ?? "Config re-lock did not re-confirm after settle window"; console.error(` ERROR: ${message}`); @@ -1313,10 +2872,9 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): return; } - // 1. Kill auto-restore timer if running - killTimer(sandboxName); - - // 2. If coming from shields-down, restore the saved policy snapshot. + // If coming from shields-down, validate the saved policy snapshot before + // any mutation. A fresh sandbox has no prior snapshot and is already on its + // restrictive baseline. // If first shields-up on a fresh sandbox (no prior shields-down), // the current policy is already the restrictive baseline — skip restore. const snapshotPath = state.shieldsDown ? state.shieldsPolicySnapshotPath : undefined; @@ -1327,13 +2885,32 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): ); return failShieldsCommand("Saved policy snapshot is missing", opts.throwOnError); } + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const protocol = requireHermesShieldsProtocol( + sandboxName, + target, + opts.allowLegacyHermesProtocol === true, + ); + + // Keep the auto-restore owner alive through policy restore, config locking, + // and the final UP state commit. Manual shields-up and the timer are both + // monotonic hardening paths; revoking the timer earlier would turn a failed + // manual/rebuild relock into an unbounded mutable window. + const timerMarker = readTimerMarker(sandboxName); + let snapshotLockResult: { chattrApplied: boolean; fileHashes: { [path: string]: string }; } | null = null; if (snapshotPath) { console.log(" Restoring restrictive policy from snapshot..."); - const activation = activateLockdownFromSnapshot(sandboxName, snapshotPath); + const activation = activateLockdownFromSnapshot( + sandboxName, + snapshotPath, + opts.allowLegacyHermesProtocol === true, + target, + protocol, + ); if (!activation.ok) { console.error(` ERROR: ${activation.error ?? "unknown restore error"}`); console.error(" Config remains unlocked — manual intervention required."); @@ -1353,11 +2930,16 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): // Uses kubectl exec to bypass Landlock (same as shields down). // Each operation runs independently and the result is verified. // If verification fails, config remains unlocked — we do not lie about state. - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); console.log(` Locking ${target.agentName} config (${target.configPath})...`); let lockResult: { chattrApplied: boolean; fileHashes: { [path: string]: string } }; try { - lockResult = lockAgentConfig(sandboxName, target); + lockResult = lockAgentConfig( + sandboxName, + target, + false, + opts.allowLegacyHermesProtocol === true, + protocol, + ); } catch (err) { const message = err instanceof Error ? err.message : String(err); console.error(` ERROR: ${message}`); @@ -1395,7 +2977,10 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): } : {}), }); - clearTimerMarker(sandboxName); + killTimer(sandboxName); + if (timerMarker?.processToken && /^[0-9a-f]{32}$/.test(timerMarker.processToken)) { + clearShieldsDownTransition(sandboxName, timerMarker.processToken); + } // 5. Audit log appendAuditEntry({ @@ -1417,6 +3002,20 @@ function shieldsUp(sandboxName: string, opts: { throwOnError?: boolean } = {}): ); } +function shieldsUp( + sandboxName: string, + opts: { throwOnError?: boolean; allowLegacyHermesProtocol?: boolean } = {}, +): void { + validateName(sandboxName, "sandbox name"); + try { + return withTimerBoundShieldsMutationLock(sandboxName, "shields up", () => + shieldsUpWithoutHostLock(sandboxName, opts), + ); + } catch (error) { + return completeDeferredShieldsExit(error, opts.throwOnError === true); + } +} + // --------------------------------------------------------------------------- // shields status // --------------------------------------------------------------------------- @@ -1426,7 +3025,7 @@ type ShieldsStatusDeps = { resolveConfig?: typeof resolveAgentConfig; }; -function shieldsStatus( +function shieldsStatusWithoutHostLock( sandboxName: string, allowInlineRecovery = true, deps: ShieldsStatusDeps = {}, @@ -1436,7 +3035,7 @@ function shieldsStatus( const verify = deps.verifyLockState ?? verifyShieldsLockState; const resolveConfig = deps.resolveConfig ?? resolveAgentConfig; - const posture = getShieldsPosture(sandboxName, allowInlineRecovery); + const posture = getShieldsPostureWithoutHostLock(sandboxName, allowInlineRecovery); const { state } = posture; if (state._isCorrupt) { console.error(" Shields: ERROR (state file is corrupt)"); @@ -1446,7 +3045,7 @@ function shieldsStatus( console.error( ` Recovery warning: run \`nemoclaw ${sandboxName} shields up\` to restore a known-good state.`, ); - process.exit(1); + throw new DeferredShieldsExit("Shields state is corrupt", 1); } switch (posture.mode) { @@ -1465,6 +3064,7 @@ function shieldsStatus( const target = ensureConfigHashSensitiveFile(resolveConfig(sandboxName)); driftIssues = verify(sandboxName, target, { verifyChattr: state.chattrApplied === true, + verifyParentProtection: target.agentName === "openclaw" || target.agentName === "hermes", exec: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), assertLegacyLayout: assertNoLegacyStateLayout, expectedHashes: state.fileHashes, @@ -1505,7 +3105,7 @@ function shieldsStatus( for (const line of recoveryLines) { console.error(line); } - process.exit(2); + throw new DeferredShieldsExit("Locked shields state has filesystem drift", 2); } if (!state.fileHashes) { // Legacy state file pre-dates the content seal. Perm-only @@ -1523,7 +3123,7 @@ function shieldsStatus( console.error( ` or set NEMOCLAW_SHIELDS_ACCEPT_LEGACY_BASELINE=1 and re-run \`nemoclaw ${sandboxName} shields up\` to seal the current bytes.`, ); - process.exit(2); + throw new DeferredShieldsExit("Locked shields state has no content seal", 2); } console.log(` Shields: ${posture.statusText}`); console.log(policyLine); @@ -1553,6 +3153,27 @@ function shieldsStatus( } } +function shieldsStatus( + sandboxName: string, + allowInlineRecovery = true, + deps: ShieldsStatusDeps = {}, +): void { + validateName(sandboxName, "sandbox name"); + try { + if (!allowInlineRecovery) { + return withShieldsTransitionLock(sandboxName, "shields status", () => + shieldsStatusWithoutHostLock(sandboxName, false, deps), + ); + } + prepareExpiredAutoRestoreHostLockTakeover(sandboxName); + return withTimerBoundShieldsMutationLock(sandboxName, "shields status", () => + shieldsStatusWithoutHostLock(sandboxName, true, deps), + ); + } catch (error) { + return completeDeferredShieldsExit(error); + } +} + // --------------------------------------------------------------------------- // Query — check whether shields are currently down // --------------------------------------------------------------------------- @@ -1564,7 +3185,9 @@ function shieldsStatus( * "not configured" instead of "down". */ function isShieldsDown(sandboxName: string, allowInlineRecovery = false): boolean { - const state = recoverExpiredAutoRestoreGate(sandboxName, allowInlineRecovery); + const state = allowInlineRecovery + ? getShieldsPosture(sandboxName, true).state + : recoverExpiredAutoRestoreGate(sandboxName, false); if (state._isCorrupt) return false; const mode = deriveShieldsMode(state, state._hasStateFile); return mode !== "locked"; @@ -1578,9 +3201,13 @@ function isShieldsDown(sandboxName: string, allowInlineRecovery = false): boolea * blocking a fresh `shields up` and stops a freshly recreated (mutable) sandbox * from being reported as locked. Best-effort: a missing state file is fine. */ -function clearShieldsState(sandboxName: string): void { +function clearShieldsStateWithoutHostLock(sandboxName: string): void { validateName(sandboxName, "sandbox name"); + const timerMarker = readTimerMarker(sandboxName); killTimer(sandboxName); + if (timerMarker?.processToken && /^[0-9a-f]{32}$/.test(timerMarker.processToken)) { + clearShieldsDownTransition(sandboxName, timerMarker.processToken); + } try { fs.rmSync(stateFilePath(sandboxName), { force: true }); } catch { @@ -1588,6 +3215,13 @@ function clearShieldsState(sandboxName: string): void { } } +function clearShieldsState(sandboxName: string): void { + validateName(sandboxName, "sandbox name"); + return withShieldsTransitionLock(sandboxName, "clear shields state", () => + clearShieldsStateWithoutHostLock(sandboxName), + ); +} + // --------------------------------------------------------------------------- // Exports // --------------------------------------------------------------------------- @@ -1596,6 +3230,7 @@ export { clearShieldsState, DEFAULT_TIMEOUT_SECONDS, deriveShieldsMode, + excludeRecoveryProcessTree, getShieldsPosture, inspectMutableConfigPerms, isShieldsDown, @@ -1603,9 +3238,12 @@ export { lockAgentConfig, MAX_TIMEOUT_SECONDS, parseDuration, + prepareAutoRestoreTransitionTakeover, repairMutableConfigPerms, shieldsDown, shieldsStatus, shieldsUp, + supportsHermesSealedShieldsTransactions, + synchronizeAutoRestoreWithShieldsDown, unlockAgentConfig, }; diff --git a/src/lib/shields/legacy-hermes-compat.test.ts b/src/lib/shields/legacy-hermes-compat.test.ts new file mode 100644 index 00000000000..3181d920a6f --- /dev/null +++ b/src/lib/shields/legacy-hermes-compat.test.ts @@ -0,0 +1,390 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const INDEX_MODULE = "./index.js"; +const HERMES_PYTHON = "/opt/hermes/.venv/bin/python"; +const HERMES_GUARD = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"; +const LOCK_TOKEN = "a".repeat(64); +const OLD_GUARD_HELP = "usage: guard {ensure-api-key,refresh-hashes,provider-placeholders}"; +const PARTIAL_GUARD_HELP = "begin-shields-transition --rollback-shields-mode"; +const CURRENT_GUARD_HELP = [ + "begin-shields-transition", + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "--rollback-shields-mode", +].join(" "); + +type ShieldsModule = typeof import("./index"); + +function hermesTarget() { + return { + agentName: "hermes", + configPath: "/sandbox/.hermes/config.yaml", + configDir: "/sandbox/.hermes", + format: "yaml", + configFile: "config.yaml", + sensitiveFiles: ["/sandbox/.hermes/.env", "/sandbox/.hermes/.config-hash"], + }; +} + +function commandFromCall(call: unknown[]): string[] { + return call[0] as string[]; +} + +function isGuardAction(cmd: string[], action: string): boolean { + const guardIndex = cmd.indexOf(HERMES_GUARD); + return guardIndex >= 0 && cmd[guardIndex + 1] === action; +} + +function isInlinePython(cmd: string[]): boolean { + return cmd[0] === "python3" && cmd.includes("-c"); +} + +function isIsolatedInlinePython(cmd: string[]): boolean { + return isInlinePython(cmd) && cmd[1] === "-I" && cmd[2] === "-c"; +} + +describe("legacy Hermes shields compatibility", () => { + let homeDir: string; + let shields: ShieldsModule; + let spies: MockInstance[]; + let runSpy: MockInstance; + let dockerExecSpy: MockInstance; + let privilegedExecArgvSpy: MockInstance; + let applyStateDirLockModeSpy: MockInstance; + + beforeEach(() => { + homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-legacy-hermes-")); + vi.stubEnv("HOME", homeDir); + spies = []; + delete require.cache[requireSource.resolve(INDEX_MODULE)]; + + const runner = requireSource("../runner.js"); + const policy = requireSource("../policy/index.js"); + const config = requireSource("../sandbox/config.js"); + const privilegedExec = requireSource("../sandbox/privileged-exec.js"); + const dockerExec = requireSource("../adapters/docker/exec.js"); + const stateDirLock = requireSource("./state-dir-lock.js"); + const audit = requireSource("./audit.js"); + const permissiveRuntime = requireSource("./permissive-runtime.js"); + const tempFiles = requireSource("../onboard/temp-files.js"); + + runSpy = vi.spyOn(runner, "run").mockReturnValue({ status: 0 }); + dockerExecSpy = vi.spyOn(dockerExec, "dockerExecFileSync"); + applyStateDirLockModeSpy = vi.spyOn(stateDirLock, "applyStateDirLockMode").mockReturnValue([]); + privilegedExecArgvSpy = vi + .spyOn(privilegedExec, "privilegedSandboxExecArgv") + .mockImplementation((_sandboxName: unknown, cmd: unknown) => cmd as string[]); + spies.push( + runSpy, + vi.spyOn(runner, "runCapture").mockReturnValue("version: 1\nnetwork_policies:\n test: {}\n"), + vi + .spyOn(policy, "buildPolicyGetCommand") + .mockImplementation((name: unknown) => ["policy", "get", String(name)]), + vi + .spyOn(policy, "buildPolicySetCommand") + .mockImplementation((file: unknown, name: unknown) => [ + "policy", + "set", + String(file), + String(name), + ]), + vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)), + vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue("/mock/permissive.yaml"), + vi.spyOn(config, "resolveAgentConfig").mockImplementation(() => hermesTarget()), + privilegedExecArgvSpy, + dockerExecSpy, + applyStateDirLockModeSpy, + vi.spyOn(stateDirLock, "preflightStateDirLock").mockReturnValue([]), + vi.spyOn(stateDirLock, "restoreStateDirLockPosture").mockReturnValue([]), + vi.spyOn(audit, "appendAuditEntry").mockImplementation(() => undefined), + vi + .spyOn(permissiveRuntime, "buildRuntimePermissivePolicy") + .mockImplementation((basePath: unknown) => String(basePath)), + vi.spyOn(tempFiles, "cleanupTempDir").mockImplementation(() => undefined), + vi.spyOn(console, "log").mockImplementation(() => undefined), + vi.spyOn(console, "warn").mockImplementation(() => undefined), + vi.spyOn(console, "error").mockImplementation(() => undefined), + ); + + shields = requireSource(INDEX_MODULE); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + vi.unstubAllEnvs(); + delete require.cache[requireSource.resolve(INDEX_MODULE)]; + fs.rmSync(homeDir, { recursive: true, force: true }); + }); + + function installExecResponses(help: string): void { + dockerExecSpy.mockImplementation((cmd: string[]) => { + switch (true) { + case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): + return help; + case isGuardAction(cmd, "begin-shields-transition"): + return `lock_token=${LOCK_TOKEN} original_locked=1`; + case isGuardAction(cmd, "apply-shields-transition"): + return "shields_mode=mutable chattr_applied=0"; + case cmd[0] === "stat": + return cmd.at(-1) === "/sandbox/.hermes" ? "3770 sandbox:sandbox" : "640 sandbox:sandbox"; + case cmd[0] === "lsattr": + return `---------------- ${cmd.at(-1)}`; + default: + return ""; + } + }); + } + + it("rejects ordinary shields-down against an old guard before policy or state mutation", () => { + installExecResponses(OLD_GUARD_HELP); + + expect(() => + shields.shieldsDown("legacy-hermes", { + skipTimer: true, + throwOnError: true, + }), + ).toThrow(/predates sealed shields transitions|rebuild/i); + + expect(runSpy).not.toHaveBeenCalled(); + expect( + fs.existsSync(path.join(homeDir, ".nemoclaw", "state", "shields-legacy-hermes.json")), + ).toBe(false); + expect(dockerExecSpy.mock.calls.some((call) => commandFromCall(call)[0] === "python3")).toBe( + false, + ); + }); + + it("rejects ordinary shields-up against an old guard before restoring policy", () => { + installExecResponses(OLD_GUARD_HELP); + const stateDir = path.join(homeDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, "policy-snapshot.yaml"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync( + path.join(stateDir, "shields-legacy-hermes.json"), + JSON.stringify({ + shieldsDown: true, + shieldsPolicySnapshotPath: snapshotPath, + updatedAt: "2026-06-27T00:00:00.000Z", + }), + ); + const originalState = fs.readFileSync( + path.join(stateDir, "shields-legacy-hermes.json"), + "utf-8", + ); + + expect(() => shields.shieldsUp("legacy-hermes", { throwOnError: true })).toThrow( + /predates sealed shields transitions|rebuild/i, + ); + + expect(runSpy).not.toHaveBeenCalled(); + expect(fs.readFileSync(path.join(stateDir, "shields-legacy-hermes.json"), "utf-8")).toBe( + originalState, + ); + }); + + it("requires the complete sealed transaction contract before selecting it", () => { + installExecResponses(PARTIAL_GUARD_HELP); + + expect(() => + shields.shieldsDown("partial-hermes", { + skipTimer: true, + throwOnError: true, + }), + ).toThrow(/predates sealed shields transitions|incomplete|rebuild/i); + + expect(runSpy).not.toHaveBeenCalled(); + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + expect(commands.some((cmd) => isGuardAction(cmd, "begin-shields-transition"))).toBe(false); + }); + + it("permits only an explicitly authorized legacy path to use the descriptor-safe top-level unlock", () => { + installExecResponses(OLD_GUARD_HELP); + + expect(() => + shields.unlockAgentConfig("legacy-hermes", hermesTarget(), true, true), + ).not.toThrow(); + + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + const descriptorUnlock = commands.find(isIsolatedInlinePython); + expect(descriptorUnlock?.join(" ")).toContain("O_NOFOLLOW"); + expect(descriptorUnlock?.[3]).toContain("strict hash verification failed"); + expect(descriptorUnlock?.[3]).toContain("compat hash verification failed"); + expect(descriptorUnlock?.[3]).toMatch(/os\.(?:replace|rename)\(/); + expect(commands.some((cmd) => isGuardAction(cmd, "begin-shields-transition"))).toBe(false); + }); + + it("fails a partial recursive unlock and restores the trusted legacy posture", () => { + installExecResponses(OLD_GUARD_HELP); + applyStateDirLockModeSpy.mockReturnValueOnce(["recursive unlock failed"]); + + expect(() => shields.unlockAgentConfig("legacy-hermes", hermesTarget(), true, true)).toThrow( + /recursive unlock failed/, + ); + + const legacyTransitions = dockerExecSpy.mock.calls + .map(commandFromCall) + .filter(isIsolatedInlinePython) + .map((cmd) => cmd[4]); + expect(legacyTransitions).toEqual(["unlock", "lock"]); + }); + + it("uses the sealed transaction when the installed guard supports the complete contract", () => { + installExecResponses(CURRENT_GUARD_HELP); + + expect(() => + shields.unlockAgentConfig("current-hermes", hermesTarget(), true, true), + ).not.toThrow(); + + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + expect(commands.some((cmd) => isGuardAction(cmd, "begin-shields-transition"))).toBe(true); + expect( + commands.some( + (cmd) => + isGuardAction(cmd, "run-state-dir-transition") && + cmd.includes("--state-action") && + cmd.includes("unlock") && + cmd.includes(LOCK_TOKEN), + ), + ).toBe(true); + expect(commands.some((cmd) => isGuardAction(cmd, "apply-shields-transition"))).toBe(true); + expect(commands.some((cmd) => isGuardAction(cmd, "finish-shields-transition"))).toBe(true); + expect(commands.some(isInlinePython)).toBe(false); + }); + + it("isolates Hermes guard Python and scrubs every privileged shields exec", () => { + installExecResponses(CURRENT_GUARD_HELP); + + expect(() => + shields.unlockAgentConfig("current-hermes", hermesTarget(), true, true), + ).not.toThrow(); + + const guardCommands = dockerExecSpy.mock.calls + .map(commandFromCall) + .filter((cmd) => cmd.includes(HERMES_GUARD)); + expect(guardCommands.length).toBeGreaterThan(0); + for (const command of guardCommands) { + const pythonIndex = command.indexOf(HERMES_PYTHON); + expect(pythonIndex).toBeGreaterThanOrEqual(0); + expect(command[pythonIndex + 1]).toBe("-I"); + expect(command[pythonIndex + 2]).toBe(HERMES_GUARD); + } + expect(privilegedExecArgvSpy).toHaveBeenCalled(); + for (const call of privilegedExecArgvSpy.mock.calls) { + expect(call[3]).toBe(true); + } + }); + + it("pins one capability decision across policy and config mutation", () => { + installExecResponses(CURRENT_GUARD_HELP); + + expect(() => + shields.shieldsDown("current-hermes", { + skipTimer: true, + throwOnError: true, + }), + ).not.toThrow(); + + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + expect( + commands.filter((cmd) => cmd.includes(HERMES_GUARD) && cmd.includes("--help")), + ).toHaveLength(1); + expect(commands.some((cmd) => isGuardAction(cmd, "begin-shields-transition"))).toBe(true); + }); + + it("descriptor-safely protects and verifies the sandbox parent when a failed rebuild relocks an old image", () => { + dockerExecSpy.mockImplementation((cmd: string[]) => { + switch (true) { + case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): + return OLD_GUARD_HELP; + case cmd[0] === "stat": + return cmd.at(-1) === "/sandbox" + ? "1775 root:sandbox" + : cmd.at(-1) === "/sandbox/.hermes" + ? "755 root:root" + : "444 root:root"; + case cmd[0] === "lsattr": + return `----i----------- ${cmd.at(-1)}`; + case cmd[0] === "sha256sum": + return `${"b".repeat(64)} ${cmd.at(-1)}`; + default: + return ""; + } + }); + + expect(() => + shields.lockAgentConfig("legacy-hermes", hermesTarget(), false, true), + ).not.toThrow(); + + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + const descriptorLock = commands.find( + (cmd) => + cmd[0] === "python3" && + cmd[1] === "-I" && + cmd[2] === "-c" && + cmd[3]?.includes("O_NOFOLLOW") && + cmd[3]?.includes("0o1775"), + ); + expect(descriptorLock).toBeDefined(); + expect(descriptorLock?.[3]).toContain("strict hash verification failed"); + expect(descriptorLock?.[3]).toContain("compat hash verification failed"); + expect(descriptorLock?.[3]).toMatch(/os\.(?:replace|rename)\(/); + expect(commands.some((cmd) => cmd[0] === "stat" && cmd.at(-1) === "/sandbox")).toBe(true); + }); + + it("refuses to report a legacy relock when sandbox parent protection did not hold", () => { + dockerExecSpy.mockImplementation((cmd: string[]) => { + switch (true) { + case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): + return OLD_GUARD_HELP; + case cmd[0] === "stat": + return cmd.at(-1) === "/sandbox" + ? "755 sandbox:sandbox" + : cmd.at(-1) === "/sandbox/.hermes" + ? "755 root:root" + : "444 root:root"; + case cmd[0] === "lsattr": + return `----i----------- ${cmd.at(-1)}`; + case cmd[0] === "sha256sum": + return `${"b".repeat(64)} ${cmd.at(-1)}`; + default: + return ""; + } + }); + + expect(() => shields.lockAgentConfig("legacy-hermes", hermesTarget(), false, true)).toThrow( + /parent dir|1775|root:sandbox/i, + ); + }); + + it("does not reinterpret a failed capability probe as permission to use the legacy path", () => { + dockerExecSpy.mockImplementation((cmd: string[]) => { + switch (cmd.includes(HERMES_GUARD) && cmd.includes("--help")) { + case true: + throw new Error("temporary Docker exec failure"); + default: + return ""; + } + }); + + expect(() => + shields.unlockAgentConfig("unreachable-hermes", hermesTarget(), true, true), + ).toThrow(/temporary Docker exec failure|capability/i); + + const commands = dockerExecSpy.mock.calls.map(commandFromCall); + expect(commands.some(isInlinePython)).toBe(false); + expect(applyStateDirLockModeSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/shields/legacy-hermes-transition.test.ts b/src/lib/shields/legacy-hermes-transition.test.ts new file mode 100644 index 00000000000..ad068e3d1a7 --- /dev/null +++ b/src/lib/shields/legacy-hermes-transition.test.ts @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +const SOURCE_PATH = path.join(import.meta.dirname, "index.ts"); +const SCRIPT_MARKER = "const LEGACY_HERMES_CONFIG_TRANSITION_SCRIPT = String.raw`"; +const fixtures: string[] = []; + +function legacyTransitionScriptForCurrentUser(): string { + const source = fs.readFileSync(SOURCE_PATH, "utf-8"); + const start = source.indexOf(SCRIPT_MARKER); + expect(start, "legacy Hermes transition script marker is missing").toBeGreaterThanOrEqual(0); + const bodyStart = start + SCRIPT_MARKER.length; + const bodyEnd = source.indexOf("`;", bodyStart); + expect(bodyEnd, "legacy Hermes transition script terminator is missing").toBeGreaterThanOrEqual( + 0, + ); + + // Production deliberately resolves the in-container sandbox identity and + // root. The behavioral fixture runs unprivileged on the host, so substitute + // only those identities while preserving the exact traversal, hash, + // replacement, rollback, and mode logic under test. + return source + .slice(bodyStart, bodyEnd) + .replace("or st.st_uid != 0", "or st.st_uid != os.geteuid()") + .replace( + 'sandbox_uid = pwd.getpwnam("sandbox").pw_uid\nsandbox_gid = grp.getgrnam("sandbox").gr_gid', + "sandbox_uid = os.geteuid()\nsandbox_gid = os.getegid()", + ) + .replace('desired_uid = 0 if action == "lock" else sandbox_uid', "desired_uid = os.geteuid()") + .replace('desired_gid = 0 if action == "lock" else sandbox_gid', "desired_gid = os.getegid()") + .replaceAll("os.fchown(config_fd, 0, 0)", "os.fchown(config_fd, os.geteuid(), os.getegid())") + .replaceAll("os.fchown(parent_fd, 0, 0)", "os.fchown(parent_fd, os.geteuid(), os.getegid())") + .replace( + "os.fchown(parent_fd, 0, sandbox_gid)", + "os.fchown(parent_fd, os.geteuid(), os.getegid())", + ); +} + +function digestEntry(filePath: string, bytes: Buffer): string { + return `${createHash("sha256").update(bytes).digest("hex")} ${filePath}\n`; +} + +function createFixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "legacy-hermes-transition-")); + fixtures.push(root); + const parentDir = path.join(root, "sandbox"); + const configDir = path.join(parentDir, ".hermes"); + const configPath = path.join(configDir, "config.yaml"); + const envPath = path.join(configDir, ".env"); + const compatPath = path.join(configDir, ".config-hash"); + const strictPath = path.join(root, "hermes.config-hash"); + const configBytes = Buffer.from("default: trusted-model\n"); + const envBytes = Buffer.from("API_KEY=trusted-placeholder\n"); + + fs.mkdirSync(configDir, { recursive: true, mode: 0o770 }); + fs.chmodSync(parentDir, 0o755); + fs.chmodSync(configDir, 0o3770); + fs.writeFileSync(configPath, configBytes, { mode: 0o640 }); + fs.writeFileSync(envPath, envBytes, { mode: 0o640 }); + const hashText = digestEntry(configPath, configBytes) + digestEntry(envPath, envBytes); + fs.writeFileSync(compatPath, hashText, { mode: 0o640 }); + fs.writeFileSync(strictPath, hashText, { mode: 0o444 }); + fs.chmodSync(strictPath, 0o444); + + return { + parentDir, + configDir, + configPath, + envPath, + compatPath, + strictPath, + configBytes, + }; +} + +function runTransition(fixture: ReturnType, action: "lock" | "unlock") { + return spawnSync( + "python3", + [ + "-c", + legacyTransitionScriptForCurrentUser(), + action, + fixture.configDir, + fixture.strictPath, + fixture.configPath, + fixture.envPath, + fixture.compatPath, + ], + { encoding: "utf-8" }, + ); +} + +function mode(filePath: string): number { + return fs.statSync(filePath).mode & 0o7777; +} + +function readRegularFileSnapshot(filePath: string) { + const fd = fs.openSync( + filePath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + try { + const stat = fs.fstatSync(fd, { bigint: true }); + expect(stat.isFile(), `expected a regular file at '${filePath}'`).toBe(true); + return { + bytes: fs.readFileSync(fd), + inode: stat.ino, + mode: Number(stat.mode & 0o7777n), + }; + } finally { + fs.closeSync(fd); + } +} + +afterEach(() => { + for (const fixture of fixtures.splice(0)) { + fs.rmSync(fixture, { recursive: true, force: true }); + } +}); + +describe("legacy Hermes config transition", () => { + it("fresh-replaces locked files, revokes stale writable FDs, protects the parent, and rejects strict-anchor tamper", () => { + const fixture = createFixture(); + const staleFd = fs.openSync(fixture.configPath, "r+"); + const staleInode = fs.fstatSync(staleFd, { bigint: true }).ino; + + const locked = runTransition(fixture, "lock"); + expect(locked.status, locked.stderr).toBe(0); + const lockedSnapshot = readRegularFileSnapshot(fixture.configPath); + expect(lockedSnapshot.inode).not.toBe(staleInode); + fs.writeSync(staleFd, Buffer.from("EVIL"), 0, 4, 0); + fs.fsyncSync(staleFd); + fs.closeSync(staleFd); + + const afterStaleWrite = readRegularFileSnapshot(fixture.configPath); + expect(afterStaleWrite.inode).toBe(lockedSnapshot.inode); + expect(afterStaleWrite.bytes).toEqual(fixture.configBytes); + expect(mode(fixture.parentDir)).toBe(0o1775); + expect(mode(fixture.configDir)).toBe(0o755); + expect(afterStaleWrite.mode).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(mode(fixture.compatPath)).toBe(0o444); + + fs.chmodSync(fixture.strictPath, 0o644); + fs.writeFileSync(fixture.strictPath, "tampered\n"); + fs.chmodSync(fixture.strictPath, 0o444); + const refused = runTransition(fixture, "unlock"); + expect(refused.status).not.toBe(0); + expect(refused.stderr).toContain("strict hash verification failed"); + expect(mode(fixture.parentDir)).toBe(0o1775); + expect(mode(fixture.configDir)).toBe(0o755); + const afterRefusedUnlock = readRegularFileSnapshot(fixture.configPath); + expect(afterRefusedUnlock.inode).toBe(afterStaleWrite.inode); + expect(afterRefusedUnlock.bytes).toEqual(fixture.configBytes); + expect(afterRefusedUnlock.mode).toBe(0o444); + }); + + it("rejects oversized mutable inputs before staging replacements", () => { + const fixture = createFixture(); + fs.truncateSync(fixture.configPath, 16 * 1024 * 1024 + 1); + + const result = runTransition(fixture, "lock"); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("legacy Hermes file exceeds size limit"); + expect(mode(fixture.parentDir)).toBe(0o755); + expect(mode(fixture.configDir)).toBe(0o3770); + }); +}); diff --git a/src/lib/shields/openclaw-config-lock.test.ts b/src/lib/shields/openclaw-config-lock.test.ts new file mode 100644 index 00000000000..2b633aa6f56 --- /dev/null +++ b/src/lib/shields/openclaw-config-lock.test.ts @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + OPENCLAW_CONFIG_DIR, + parseOpenClawConfigGuardOutput, + runOpenClawConfigGuard, +} from "./openclaw-config-lock"; +import type { PrivilegedExec, PrivilegedExecResult } from "./state-dir-lock"; + +type RunCall = { cmd: string[]; input?: string }; + +function success(action: string, chattrApplied = false): string { + return JSON.stringify({ + type: "result", + action, + status: "ok", + configDir: OPENCLAW_CONFIG_DIR, + files: ["openclaw.json", ".config-hash"], + chattrApplied, + ...(action === "write-config" ? { configSha256: "b".repeat(64) } : {}), + }); +} + +function createExec(installed: boolean): { calls: RunCall[]; privileged: PrivilegedExec } { + const calls: RunCall[] = []; + return { + calls, + privileged: { + run: (cmd, input) => { + calls.push({ cmd, input }); + switch (cmd[0]) { + case "test": + return { status: installed ? 0 : 1, signal: null, stdout: "", stderr: "" }; + } + const scriptIndex = + cmd.indexOf("-") >= 0 + ? cmd.indexOf("-") + : cmd.indexOf(cmd.find((arg) => arg.endsWith("openclaw-config-guard.py")) ?? ""); + const action = cmd[scriptIndex + 1]; + return { + status: 0, + signal: null, + stdout: `${success(action, action === "lock")}\n`, + stderr: "", + }; + }, + }, + }; +} + +describe("OpenClaw top-config guard host wiring", () => { + it("uses the root-only installed helper and preserves its immutable result", () => { + const { calls, privileged } = createExec(true); + + expect(runOpenClawConfigGuard(privileged, "lock")).toEqual({ + issues: [], + chattrApplied: true, + }); + expect(calls.at(-1)?.cmd).toEqual([ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "5m", + "python3", + "-I", + "/usr/local/lib/nemoclaw/openclaw-config-guard.py", + "lock", + "--config-dir", + OPENCLAW_CONFIG_DIR, + ]); + expect(calls.at(-1)?.input).toBeUndefined(); + }); + + it("injects the trusted host helper into old images", () => { + const { calls, privileged } = createExec(false); + + expect(runOpenClawConfigGuard(privileged, "unlock").issues).toEqual([]); + expect(calls.at(-1)?.cmd).toEqual([ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "5m", + "python3", + "-I", + "-", + "unlock", + "--config-dir", + OPENCLAW_CONFIG_DIR, + ]); + expect(calls.at(-1)?.input).toContain("Descriptor-safe OpenClaw top-level config"); + }); + + it("passes OpenClaw config bytes and the matching CAS digest to the installed helper", () => { + const { calls, privileged } = createExec(true); + const digest = "a".repeat(64); + + expect( + runOpenClawConfigGuard(privileged, "write-config", { + expectedConfigSha256: digest, + input: '{"gateway":{}}\n', + }), + ).toMatchObject({ issues: [], configSha256: "b".repeat(64) }); + expect(calls.at(-1)?.cmd).toEqual([ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "5m", + "python3", + "-I", + "/usr/local/lib/nemoclaw/openclaw-config-guard.py", + "write-config", + "--config-dir", + OPENCLAW_CONFIG_DIR, + "--expected-config-sha256", + digest, + ]); + expect(calls.at(-1)?.input).toBe('{"gateway":{}}\n'); + }); + + it("refuses an unsafe old-image write fallback because stdin carries the helper source", () => { + const { calls, privileged } = createExec(false); + + expect( + runOpenClawConfigGuard(privileged, "write-config", { + expectedConfigSha256: "a".repeat(64), + input: "{}\n", + }).issues, + ).toEqual([expect.stringContaining("rebuild before writing config transactionally")]); + expect(calls).toHaveLength(1); + }); + + it("surfaces structured findings and contradictory exit contracts", () => { + const result: PrivilegedExecResult = { + status: 0, + signal: null, + stdout: [ + JSON.stringify({ + type: "issue", + code: "hardlinked-config-file", + path: `${OPENCLAW_CONFIG_DIR}/openclaw.json`, + detail: "link count is 2", + }), + JSON.stringify({ type: "result", action: "preflight", status: "failed" }), + ].join("\n"), + stderr: "", + }; + + expect(parseOpenClawConfigGuardOutput("preflight", result).issues).toEqual( + expect.arrayContaining([ + expect.stringContaining("[hardlinked-config-file]"), + expect.stringContaining("reported failure with a zero exit"), + ]), + ); + }); + + it("rejects malformed success summaries and capability probe errors", () => { + const malformed: PrivilegedExecResult = { + status: 0, + signal: null, + stdout: JSON.stringify({ + type: "result", + action: "lock", + status: "ok", + configDir: "/tmp/.openclaw", + files: ["openclaw.json"], + }), + stderr: "", + }; + expect(parseOpenClawConfigGuardOutput("lock", malformed).issues).toEqual( + expect.arrayContaining([ + expect.stringContaining("configDir=/tmp/.openclaw"), + expect.stringContaining("unexpected protected-file set"), + ]), + ); + + const probeFailure: PrivilegedExec = { + run: () => ({ + status: null, + signal: "SIGTERM", + stdout: "", + stderr: "probe timed out", + }), + }; + expect(runOpenClawConfigGuard(probeFailure, "lock").issues).toEqual([ + expect.stringContaining("capability probe failed"), + ]); + }); +}); diff --git a/src/lib/shields/openclaw-config-lock.ts b/src/lib/shields/openclaw-config-lock.ts new file mode 100644 index 00000000000..db5b8a0cd1b --- /dev/null +++ b/src/lib/shields/openclaw-config-lock.ts @@ -0,0 +1,298 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import type { PrivilegedExec, PrivilegedExecResult } from "./state-dir-lock"; + +// OpenClaw's top-level config and trust anchor need a stronger transition than +// pathname chmod/chown can provide. The root-only helper resolves the exact +// directory through descriptors, rejects link/race substitutions, and swaps +// both files onto fresh inodes so writable descriptors opened before shields +// up cannot alter the trusted path afterward. + +export const OPENCLAW_CONFIG_DIR = "/sandbox/.openclaw"; +export const OPENCLAW_CONFIG_PATH = `${OPENCLAW_CONFIG_DIR}/openclaw.json`; +export const OPENCLAW_CONFIG_HASH_PATH = `${OPENCLAW_CONFIG_DIR}/.config-hash`; + +const CONTAINER_HELPER = "/usr/local/lib/nemoclaw/openclaw-config-guard.py"; +const HOST_HELPER = path.resolve(__dirname, "../../../scripts/openclaw-config-guard.py"); +const CONTAINER_TIMEOUT = ["timeout", "--signal=TERM", "--kill-after=5s", "5m"]; + +export type OpenClawConfigGuardAction = + | "preflight" + | "preflight-restart" + | "lock" + | "unlock" + | "seal-restart" + | "unseal-restart" + | "write-config" + | "recover" + | "revoke-startup-ready" + | "publish-startup-ready"; + +export type OpenClawConfigGuardOptions = { + expectedConfigSha256?: string; + input?: string; + startupOwner?: boolean; +}; + +type GuardIssue = { + type: "issue"; + code: string; + path: string; + detail: string; +}; + +type GuardSummary = { + type: "result"; + action: OpenClawConfigGuardAction; + status: "ok" | "failed"; + configDir?: string; + files?: string[]; + chattrApplied?: boolean; + configSha256?: string; + recovery?: string; + originalLocked?: boolean; +}; + +export type OpenClawConfigGuardResult = { + issues: string[]; + chattrApplied: boolean; + configSha256?: string; + recovery?: string; + originalLocked?: boolean; +}; + +const GUARD_ACTIONS = new Set([ + "preflight", + "preflight-restart", + "lock", + "unlock", + "seal-restart", + "unseal-restart", + "write-config", + "recover", + "revoke-startup-ready", + "publish-startup-ready", +]); + +function executionFailure(label: string, result: PrivilegedExecResult): string { + const details = [result.error, result.stderr.trim(), result.stdout.trim()] + .filter((value): value is string => Boolean(value)) + .join("; "); + const termination = + result.signal !== null ? `signal ${result.signal}` : `status ${String(result.status)}`; + return `${label} (${termination})${details ? `: ${details}` : ""}`; +} + +function stringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((entry) => typeof entry === "string"); +} + +export function parseOpenClawConfigGuardOutput( + action: OpenClawConfigGuardAction, + result: PrivilegedExecResult, +): OpenClawConfigGuardResult { + const issues: GuardIssue[] = []; + const summaries: GuardSummary[] = []; + const contractIssues: string[] = []; + + for (const line of result.stdout.split("\n")) { + const trimmed = line.trim(); + if (!trimmed) continue; + let value: unknown; + try { + value = JSON.parse(trimmed); + } catch { + contractIssues.push(`OpenClaw config guard returned non-JSON output: ${trimmed}`); + continue; + } + if (!value || typeof value !== "object") { + contractIssues.push(`OpenClaw config guard returned an invalid record: ${trimmed}`); + continue; + } + const record = value as Record; + if ( + record.type === "issue" && + typeof record.code === "string" && + typeof record.path === "string" && + typeof record.detail === "string" + ) { + issues.push(record as GuardIssue); + continue; + } + if ( + record.type === "result" && + typeof record.action === "string" && + GUARD_ACTIONS.has(record.action as OpenClawConfigGuardAction) && + (record.status === "ok" || record.status === "failed") && + (record.configDir === undefined || typeof record.configDir === "string") && + (record.files === undefined || stringArray(record.files)) && + (record.chattrApplied === undefined || typeof record.chattrApplied === "boolean") && + (record.configSha256 === undefined || typeof record.configSha256 === "string") && + (record.recovery === undefined || typeof record.recovery === "string") && + (record.originalLocked === undefined || typeof record.originalLocked === "boolean") + ) { + summaries.push(record as GuardSummary); + continue; + } + contractIssues.push(`OpenClaw config guard returned an unknown record: ${trimmed}`); + } + + if (summaries.length !== 1) { + contractIssues.push( + `OpenClaw config guard returned ${String(summaries.length)} result records`, + ); + } + const summary = summaries[0]; + if (summary && summary.action !== action) { + contractIssues.push( + `OpenClaw config guard result action=${summary.action} (expected ${action})`, + ); + } + if (summary?.status === "ok") { + if (issues.length > 0 || result.status !== 0) { + contractIssues.push("OpenClaw config guard reported success with issues or a non-zero exit"); + } + if (summary.configDir !== OPENCLAW_CONFIG_DIR) { + contractIssues.push( + `OpenClaw config guard result configDir=${String(summary.configDir)} (expected ${OPENCLAW_CONFIG_DIR})`, + ); + } + const startupAction = action === "revoke-startup-ready" || action === "publish-startup-ready"; + if ( + !startupAction && + (!summary.files || + summary.files.length !== 2 || + summary.files[0] !== "openclaw.json" || + summary.files[1] !== ".config-hash") + ) { + contractIssues.push("OpenClaw config guard returned an unexpected protected-file set"); + } + if (summary.configSha256 !== undefined && !/^[0-9a-f]{64}$/.test(summary.configSha256)) { + contractIssues.push("OpenClaw config guard returned an invalid configSha256"); + } + } + if (summary?.status === "failed" && result.status === 0) { + contractIssues.push("OpenClaw config guard reported failure with a zero exit"); + } + if (result.status === null || result.signal !== null || result.error) { + contractIssues.push(executionFailure("OpenClaw config guard execution failed", result)); + } else if (result.status !== 0 && issues.length === 0) { + contractIssues.push( + executionFailure("OpenClaw config guard failed without a diagnostic", result), + ); + } + if (result.stderr.trim()) { + contractIssues.push(`OpenClaw config guard wrote unexpected stderr: ${result.stderr.trim()}`); + } + + return { + issues: [ + ...issues.map( + (issue) => `OpenClaw config guard ${action} [${issue.code}] ${issue.path}: ${issue.detail}`, + ), + ...contractIssues, + ], + chattrApplied: summary?.status === "ok" && summary.chattrApplied === true, + ...(summary?.status === "ok" && summary.configSha256 + ? { configSha256: summary.configSha256 } + : {}), + ...(summary?.status === "ok" && summary.recovery ? { recovery: summary.recovery } : {}), + ...(summary?.status === "ok" && typeof summary.originalLocked === "boolean" + ? { originalLocked: summary.originalLocked } + : {}), + }; +} + +let cachedHostHelper: string | null = null; + +function readHostHelper(): string { + if (cachedHostHelper !== null) return cachedHostHelper; + cachedHostHelper = fs.readFileSync(HOST_HELPER, "utf-8"); + return cachedHostHelper; +} + +export function runOpenClawConfigGuard( + privileged: PrivilegedExec, + action: OpenClawConfigGuardAction, + options: OpenClawConfigGuardOptions = {}, +): OpenClawConfigGuardResult { + if ( + options.expectedConfigSha256 !== undefined && + !/^[0-9a-f]{64}$/.test(options.expectedConfigSha256) + ) { + return { + issues: ["OpenClaw config guard expectedConfigSha256 must be 64 lowercase hex characters"], + chattrApplied: false, + }; + } + if (action === "write-config" && !options.expectedConfigSha256) { + return { + issues: ["OpenClaw config guard write-config requires expectedConfigSha256"], + chattrApplied: false, + }; + } + + const capability = privileged.run(["test", "-r", CONTAINER_HELPER]); + let command: string[]; + let input: string | undefined; + if (capability.status === 0 && capability.signal === null && !capability.error) { + command = [ + ...CONTAINER_TIMEOUT, + "python3", + "-I", + CONTAINER_HELPER, + action, + "--config-dir", + OPENCLAW_CONFIG_DIR, + ]; + input = options.input; + } else if (capability.status === 1 && capability.signal === null && !capability.error) { + // Keep rebuild and shields recovery usable against older images without + // returning to unsafe pathname mutation: inject the exact helper shipped + // with this CLI over authenticated privileged-exec stdin. + if (action === "write-config") { + return { + issues: [ + "OpenClaw config guard is absent in the sandbox; rebuild before writing config transactionally", + ], + chattrApplied: false, + }; + } + try { + input = readHostHelper(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + issues: [ + `OpenClaw config guard is absent in the sandbox and host helper cannot be read: ${message}`, + ], + chattrApplied: false, + }; + } + command = [ + ...CONTAINER_TIMEOUT, + "python3", + "-I", + "-", + action, + "--config-dir", + OPENCLAW_CONFIG_DIR, + ]; + } else { + return { + issues: [executionFailure("OpenClaw config guard capability probe failed", capability)], + chattrApplied: false, + }; + } + + if (options.expectedConfigSha256) { + command.push("--expected-config-sha256", options.expectedConfigSha256); + } + if (options.startupOwner) command.push("--startup-owner"); + + return parseOpenClawConfigGuardOutput(action, privileged.run(command, input)); +} diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts new file mode 100644 index 00000000000..03435e4556b --- /dev/null +++ b/src/lib/shields/openclaw-transition.test.ts @@ -0,0 +1,168 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const INDEX_MODULE = "./index.js"; + +type ShieldsModule = typeof import("./index"); + +function openClawTarget() { + return { + agentName: "openclaw", + configPath: "/sandbox/.openclaw/openclaw.json", + configDir: "/sandbox/.openclaw", + format: "json", + configFile: "openclaw.json", + sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], + }; +} + +describe("OpenClaw shields top-config transaction", () => { + let homeDir: string; + let shields: ShieldsModule; + let spies: MockInstance[]; + let dockerExecSpy: MockInstance; + let guardSpy: MockInstance; + let applyStateSpy: MockInstance; + let restoreStateSpy: MockInstance; + let events: string[]; + + beforeEach(() => { + homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-transition-")); + vi.stubEnv("HOME", homeDir); + spies = []; + events = []; + delete require.cache[requireSource.resolve(INDEX_MODULE)]; + + const runner = requireSource("../runner.js"); + const config = requireSource("../sandbox/config.js"); + const privilegedExec = requireSource("../sandbox/privileged-exec.js"); + const dockerExec = requireSource("../adapters/docker/exec.js"); + const stateDirLock = requireSource("./state-dir-lock.js"); + const openClawLock = requireSource("./openclaw-config-lock.js"); + + dockerExecSpy = vi.spyOn(dockerExec, "dockerExecFileSync").mockImplementation((cmd) => { + const argv = cmd as string[]; + switch (argv[0]) { + case "stat": + return argv.at(-1) === "/sandbox" + ? "1775 root:sandbox" + : argv.at(-1) === "/sandbox/.openclaw" + ? "755 root:root" + : "444 root:root"; + case "lsattr": + return `---------------- ${String(argv.at(-1))}`; + case "sha256sum": + return `${"a".repeat(64)} ${String(argv.at(-1))}`; + default: + return ""; + } + }); + guardSpy = vi + .spyOn(openClawLock, "runOpenClawConfigGuard") + .mockImplementation((_exec, action) => { + events.push(`top:${action}`); + return { issues: [], chattrApplied: false }; + }); + applyStateSpy = vi + .spyOn(stateDirLock, "applyStateDirLockMode") + .mockImplementation((_exec, _dir, _owner, locking) => { + events.push(`state:${locking ? "lock" : "unlock"}`); + return []; + }); + restoreStateSpy = vi + .spyOn(stateDirLock, "restoreStateDirLockPosture") + .mockImplementation((_exec, _dir, locked) => { + events.push(`state:restore:${locked ? "locked" : "mutable"}`); + return []; + }); + + spies.push( + vi.spyOn(runner, "run").mockReturnValue({ status: 0 }), + vi.spyOn(runner, "runCapture").mockReturnValue(""), + vi.spyOn(config, "resolveAgentConfig").mockImplementation(() => openClawTarget()), + vi + .spyOn(privilegedExec, "privilegedSandboxExecArgv") + .mockImplementation((_sandboxName: unknown, cmd: unknown) => cmd as string[]), + dockerExecSpy, + vi.spyOn(stateDirLock, "preflightStateDirLock").mockReturnValue([]), + applyStateSpy, + restoreStateSpy, + guardSpy, + vi.spyOn(console, "error").mockImplementation(() => undefined), + ); + + shields = requireSource(INDEX_MODULE); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + vi.unstubAllEnvs(); + delete require.cache[requireSource.resolve(INDEX_MODULE)]; + fs.rmSync(homeDir, { recursive: true, force: true }); + }); + + it("freezes the top-level binding before recursive lock and avoids pathname mutation", () => { + expect(() => shields.lockAgentConfig("openclaw", openClawTarget(), false)).not.toThrow(); + + expect(events.slice(0, 2)).toEqual(["top:lock", "state:lock"]); + const commands = dockerExecSpy.mock.calls.map((call) => call[0] as string[]); + expect(commands.some((cmd) => ["chmod", "chown", "chattr"].includes(cmd[0]))).toBe(false); + expect(commands.some((cmd) => cmd[0] === "stat" && cmd.at(-1) === "/sandbox")).toBe(true); + }); + + it("preserves the sealed top after a partial recursive lock", () => { + applyStateSpy.mockImplementationOnce((_exec, _dir, _owner, locking) => { + events.push(`state:${locking ? "lock" : "unlock"}`); + return ["recursive lock failed"]; + }); + + expect(() => shields.lockAgentConfig("openclaw", openClawTarget(), false)).toThrow( + /recursive lock failed/, + ); + + expect(events).toEqual(["top:lock", "state:lock", "top:lock"]); + expect(restoreStateSpy).not.toHaveBeenCalled(); + }); + + it("keeps the protected top binding until recursive unlock is ready", () => { + dockerExecSpy.mockImplementation((cmd) => { + const argv = cmd as string[]; + switch (argv[0]) { + case "stat": + return argv.at(-1) === "/sandbox" + ? "755 sandbox:sandbox" + : argv.at(-1) === "/sandbox/.openclaw" + ? "2770 sandbox:sandbox" + : "660 sandbox:sandbox"; + case "lsattr": + return `---------------- ${String(argv.at(-1))}`; + default: + return ""; + } + }); + + expect(() => shields.unlockAgentConfig("openclaw", openClawTarget(), true)).not.toThrow(); + + expect(events.slice(0, 3)).toEqual(["top:preflight", "state:unlock", "top:unlock"]); + }); + + it("fails closed to the locked posture when recursive unlock is partial", () => { + applyStateSpy.mockImplementationOnce((_exec, _dir, _owner, locking) => { + events.push(`state:${locking ? "lock" : "unlock"}`); + return ["recursive unlock failed"]; + }); + + expect(() => shields.unlockAgentConfig("openclaw", openClawTarget(), true)).toThrow( + /recursive unlock failed/, + ); + expect(events).toEqual(["top:preflight", "state:unlock", "top:lock", "state:restore:locked"]); + }); +}); diff --git a/src/lib/shields/state-dir-lock.test.ts b/src/lib/shields/state-dir-lock.test.ts new file mode 100644 index 00000000000..91ddd2dd303 --- /dev/null +++ b/src/lib/shields/state-dir-lock.test.ts @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import type { PrivilegedExec } from "./state-dir-lock"; +import { + applyStateDirLockMode, + preflightStateDirLock, + restoreStateDirLockPosture, +} from "./state-dir-lock"; + +type RunCall = { cmd: string[]; input?: string }; + +function success(action: string): string { + return JSON.stringify({ + type: "result", + action, + status: "ok", + roots: 0, + directories: 0, + files: 0, + symlinks: 0, + issueCount: 0, + }); +} + +function createExec(installed = true): { calls: RunCall[]; privileged: PrivilegedExec } { + const calls: RunCall[] = []; + return { + calls, + privileged: { + run: (cmd, input) => { + calls.push({ cmd, input }); + switch (cmd[0]) { + case "test": + return { + status: installed ? 0 : 1, + signal: null, + stdout: "", + stderr: "", + }; + } + const pythonIndex = cmd.indexOf("python3"); + const action = cmd[pythonIndex + 3]; + return { + status: 0, + signal: null, + stdout: `${success(action)}\n`, + stderr: "", + }; + }, + }, + }; +} + +function actions(calls: RunCall[]): string[] { + return calls + .filter(({ cmd }) => cmd.includes("python3")) + .map(({ cmd }) => { + const pythonIndex = cmd.indexOf("python3"); + return cmd[pythonIndex + 3]; + }); +} + +describe("recursive state-dir lock host wiring", () => { + it("re-locks state directories when the interrupted transition began locked", () => { + const { calls, privileged } = createExec(); + + expect(restoreStateDirLockPosture(privileged, "/sandbox/.hermes", true)).toEqual([]); + expect(actions(calls)).toEqual(["preflight", "lock"]); + }); + + it("restores mutable state directories when the interrupted transition began mutable", () => { + const { calls, privileged } = createExec(); + + expect(restoreStateDirLockPosture(privileged, "/sandbox/.hermes", false)).toEqual([]); + expect(actions(calls)).toEqual(["unlock"]); + }); + + it("injects the trusted host helper into old images instead of using recursive shell commands", () => { + const { calls, privileged } = createExec(false); + + expect(applyStateDirLockMode(privileged, "/sandbox/.openclaw", "root:sandbox", true)).toEqual( + [], + ); + const invocation = calls.find(({ cmd }) => cmd.includes("python3")); + expect(invocation?.cmd).toEqual([ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "12m", + "python3", + "-I", + "-", + "lock", + "--config-dir", + "/sandbox/.openclaw", + ]); + expect(invocation?.input).toContain("Descriptor-safe recursive state-directory"); + }); + + it("surfaces structured helper findings and rejects contradictory exit contracts", () => { + const privileged: PrivilegedExec = { + run: (cmd) => { + switch (cmd[0]) { + case "test": + return { status: 0, signal: null, stdout: "", stderr: "" }; + } + return { + status: 0, + signal: null, + stdout: [ + JSON.stringify({ + type: "issue", + code: "hardlinked-entry", + path: "/sandbox/.openclaw/plugins/x", + detail: "link count is 2", + }), + JSON.stringify({ + type: "result", + action: "preflight", + status: "failed", + issueCount: 1, + }), + ].join("\n"), + stderr: "", + }; + }, + }; + + expect(preflightStateDirLock(privileged, "/sandbox/.openclaw")).toEqual( + expect.arrayContaining([ + expect.stringContaining("[hardlinked-entry]"), + expect.stringContaining("reported failure with a zero exit"), + ]), + ); + }); +}); diff --git a/src/lib/shields/state-dir-lock.ts b/src/lib/shields/state-dir-lock.ts index 15e93b224e0..7f11a4a329f 100644 --- a/src/lib/shields/state-dir-lock.ts +++ b/src/lib/shields/state-dir-lock.ts @@ -1,65 +1,29 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// State-dir lock fan-out for shields up/down. Owns the inventory of -// high-risk and secret-bearing state directories, the preflight + mutation -// + verification pipeline, and the runtime-subpath carve-out for -// `agents/*/sessions`. The shields entrypoint (`src/lib/shields/index.ts`) -// stays focused on shields state transitions and delegates the chown/chmod -// fan-out to this module. +import fs from "node:fs"; +import path from "node:path"; + +// State-dir lock fan-out for shields up/down. The actual traversal lives in a +// root-only Python helper because shell `chown -R` / `chmod -R` cannot provide +// descriptor-relative, no-symlink-follow semantics or revoke writable file +// descriptors that were opened before shields-up. + +export interface PrivilegedExecResult { + status: number | null; + signal: NodeJS.Signals | null; + stdout: string; + stderr: string; + error?: string; +} export interface PrivilegedExec { - exec(cmd: string[]): void; - capture(cmd: string[]): string; + run(cmd: string[], input?: string): PrivilegedExecResult; } -// --------------------------------------------------------------------------- -// State directories locked by shields-up. -// -// During shields-up, these must be locked so the sandbox user cannot create -// new entries or modify existing ones. This covers both executable state -// (skills, hooks, cron jobs, extensions, plugins, agent definitions) and -// writable agent state entry points such as workspace and memory, so a stale -// symlink bridge cannot bypass the lockdown. -// -// Lock ownership for HIGH_RISK_STATE_DIRS is `root:sandbox` (not -// `root:root`): the OpenClaw gateway runs as `gateway`, which is a member of -// the sandbox group via `Dockerfile.base`. Owning these dirs as -// `root:sandbox` preserves the sandbox group's `r-x` access to descendant -// files (after `chmod -R go-w`), so plugin discovery can still scan -// `extensions//` while the sandbox user is denied write through the -// stripped group/other write bits. -// -// CONFIDENTIALITY_STATE_DIRS holds secret-bearing trees (auth tokens, host -// device pairing material). These get a stricter posture under shields-up: -// `root:root 700` with `chmod -R go-rwX`, so neither the sandbox user nor -// the gateway can read them while shields are up. The mutable-default -// posture is restored on shields-down. -// -// The list is a superset: directories that don't exist in a given agent's -// config dir are silently skipped. -// -// Coverage tracks the union of state_dirs declared by every shipped agent -// manifest (agents/openclaw/manifest.yaml, agents/hermes/manifest.yaml, -// agents/langchain-deepagents-code/manifest.yaml). -// Nested state dirs may be covered by locking their parent directory; `agent` -// covers Deep Agents Code's `agent/skills` so the parent cannot be rename-swapped. -// Runtime-mutable subtrees/files that must keep being writable while shields -// are up are intentionally omitted: -// - `sessions` (Hermes top-level) and `agents/*/sessions` (OpenClaw) — the -// latter is restored via WRITABLE_RUNTIME_SUBPATHS after the lock loop. -// - `.hermes_history` (Hermes top-level file) — prompt_toolkit appends to -// this file from the sandbox user on every TUI keypress. It is deliberately -// precreated/repaired as `sandbox:sandbox 0660` while the parent config dir -// can remain `root:root 0755` under shields-up. Removal condition: upstream -// Hermes exposes a supported option to redirect or disable FileHistory. -// - `memories`, `logs`, `cache`, `plans` (Hermes) — runtime mutables. -// - `openclaw-weixin` is regenerated from envs at image-build time -// (see src/lib/actions/sandbox/rebuild.ts) and is not a manifest state_dir. -// Any new agent state_dir that holds executable code or credentials must be -// added to one of these sets in lockstep with its manifest entry. -// --------------------------------------------------------------------------- - +// Keep this inventory exported for documentation/tests that compare the host +// contract with shipped agent manifests. The helper owns enforcement and must +// be updated in the same change when this inventory changes. export const HIGH_RISK_STATE_DIRS = [ "skills", "agent", @@ -67,491 +31,209 @@ export const HIGH_RISK_STATE_DIRS = [ "cron", "agents", "extensions", - "plugins", // Hermes equivalent of extensions + "plugins", "workspace", "memory", "devices", "canvas", "telegram", - "wechat", // OpenClaw runtime channel state - "whatsapp", // OpenClaw + Hermes channel state (Hermes also nests under platforms/) - "platforms", // Hermes channel-bridge auth state (whatsapp/, etc.) - "weixin", // Hermes iLink WeChat per-account context tokens - "profiles", // Hermes saved profiles - "skins", // Hermes UI/personality bundles (code-like) -]; - -export const CONFIDENTIALITY_STATE_DIRS = [ - "credentials", - "identity", - "pairing", // Hermes device-pairing material (auth tokens) + "wechat", + "whatsapp", + "platforms", + "weixin", + "profiles", + "skins", ]; -// Runtime-data subpaths the agent must keep writing to under shields-up. -// Each entry is a shell glob relative to the agent config dir; after the -// main lock loop the matching directories are restored to -// `sandbox:sandbox 2770` so they remain writable inside an otherwise-locked -// tree. -// -// Removal condition: when the OpenClaw runtime moves session state out of -// the locked config tree (e.g. into `/sandbox/.openclaw-runtime/`), this -// carve-out can be deleted and lockAgentConfig can leave the tree fully -// owned by `root:sandbox` with no writable holes. +export const CONFIDENTIALITY_STATE_DIRS = ["credentials", "identity", "pairing"]; export const WRITABLE_RUNTIME_SUBPATHS = ["agents/*/sessions"]; -interface StateDirLockScript { - script: string; - args: string[]; -} - -interface StateDirLockScriptResult { - symlinkedRoots: string[]; - mutationFailures: Array<{ op: string; path: string }>; - // Non-null when the script exec itself failed (kubectl exec hiccup, - // privileged-exec timeout, etc.). Fail-closed: the caller surfaces a - // lock issue rather than treating the empty output as a clean run. - execError: string | null; -} - -interface PreflightResult { - symlinkedRoots: string[]; - // Non-null when the preflight exec itself failed. Fail-closed: the - // caller must treat a non-null `error` as "do not lock" so a kubectl - // exec hiccup cannot let shields-up advance while a symlinked root - // remains unobserved. - error: string | null; +const CONTAINER_HELPER = "/usr/local/lib/nemoclaw/state-dir-guard.py"; +const HOST_HELPER = path.resolve(__dirname, "../../../scripts/state-dir-guard.py"); +const CONTAINER_TIMEOUT = ["timeout", "--signal=TERM", "--kill-after=5s", "12m"]; + +type GuardAction = "preflight" | "lock" | "unlock"; + +type GuardIssue = { + type: "issue"; + code: string; + path: string; + detail: string; +}; + +type GuardSummary = { + type: "result"; + action: GuardAction; + status: "ok" | "failed"; + issueCount: number; +}; + +function resultFailure(label: string, result: PrivilegedExecResult): string { + const details = [result.error, result.stderr.trim(), result.stdout.trim()] + .filter((value): value is string => Boolean(value)) + .join("; "); + const termination = + result.signal !== null ? `signal ${result.signal}` : `status ${String(result.status)}`; + return `${label} (${termination})${details ? `: ${details}` : ""}`; } -// Run the symlink preflight against every state-dir root and the -// `workspace-*` glob, returning issues the caller must surface before -// touching any config files. Empty list means it is safe to proceed with -// `applyStateDirLockMode`. Exposed separately so callers can hoist this -// before chmod/chown on configPath + sensitiveFiles, keeping the "no -// mutations until preflight clears" invariant. -export function preflightStateDirLock(privileged: PrivilegedExec, configDir: string): string[] { - const allStateDirs = [...HIGH_RISK_STATE_DIRS, ...CONFIDENTIALITY_STATE_DIRS]; - const preflight = preflightSymlinkedRoots(privileged, configDir, allStateDirs); - if (preflight.error !== null) { - return [`Symlink preflight failed; refusing to lock: ${preflight.error}`]; - } - return preflight.symlinkedRoots.map( - (path) => `state dir root is a symlink: ${path} (refusing to lock)`, - ); -} - -// Apply lock or unlock mode to every existing high-risk and confidentiality -// state directory under `configDir`. Returns a list of issues; an empty -// list means the fan-out completed cleanly. -// -// Callers that lock (`isLocking === true`) must invoke -// `preflightStateDirLock` first and abort on a non-empty result. This -// function intentionally re-runs symlink checks inline so a mid-lock race -// (state-dir root becoming a symlink after the hoisted preflight) is still -// caught, but the hoisted preflight is the one that keeps file mutations -// from leaking out before validation. -export function applyStateDirLockMode( - privileged: PrivilegedExec, - configDir: string, - highRiskOwner: string, - isLocking: boolean, -): string[] { - // Locking (shields-up) strips group + world write for HIGH_RISK dirs. - // Unlocking (shields-down) restores the same group-readable/writable + - // o-rwx mutable-default contract as startup, plus setgid so the gateway - // UID — now in the sandbox group via Dockerfile.base — can write to - // OpenClaw's mutable config tree. The unlock variant uses - // `g+rwX,o-rwx` because a prior lock can strip group access from - // descendants. - const highRiskRecursiveMode = isLocking ? "go-w" : "g+rwX,o-rwx"; - const highRiskDirMode = isLocking ? "755" : "2770"; - const clearSetgid = isLocking ? "1" : "0"; - - const mainPassResult = runStateDirLockScript(privileged, { - script: STATE_DIR_LOCK_SCRIPT_BY_LIST, - args: [ - configDir, - highRiskOwner, - highRiskRecursiveMode, - highRiskDirMode, - clearSetgid, - ...HIGH_RISK_STATE_DIRS, - ], - }); - - // Multi-agent OpenClaw workspaces are named workspace-. Glob is - // expanded by the shell because the list is configured by openclaw.json. - const workspacePassResult = runStateDirLockScript(privileged, { - script: STATE_DIR_LOCK_SCRIPT_WORKSPACE_GLOB, - args: [configDir, highRiskOwner, highRiskRecursiveMode, highRiskDirMode, clearSetgid], - }); - - // Secret-bearing dirs: stricter posture. Locked = `root:root 700` with - // `go-rwX` so neither sandbox user nor gateway can read them while - // shields are up. Unlocked = sandbox:sandbox 2770 / g+rwX. - const confidentialityOwner = isLocking ? "root:root" : highRiskOwner; - const confidentialityRecursiveMode = isLocking ? "go-rwX" : "g+rwX,o-rwx"; - const confidentialityDirMode = isLocking ? "700" : "2770"; - const confidentialityPassResult = runStateDirLockScript(privileged, { - script: STATE_DIR_LOCK_SCRIPT_BY_LIST, - args: [ - configDir, - confidentialityOwner, - confidentialityRecursiveMode, - confidentialityDirMode, - clearSetgid, - ...CONFIDENTIALITY_STATE_DIRS, - ], - }); - - const issues: string[] = []; - const allResults = [ - { label: "high-risk", result: mainPassResult }, - { label: "workspace-*", result: workspacePassResult }, - { label: "confidentiality", result: confidentialityPassResult }, - ]; - for (const { label, result } of allResults) { - if (result.execError !== null) { - issues.push(`state dir lock ${label} exec failed: ${result.execError}`); +function parseGuardOutput(action: GuardAction, result: PrivilegedExecResult): string[] { + const issues: GuardIssue[] = []; + const summaries: GuardSummary[] = []; + const contractIssues: string[] = []; + + for (const line of result.stdout.split("\n")) { + const trimmed = line.trim(); + if (!trimmed) continue; + let value: unknown; + try { + value = JSON.parse(trimmed); + } catch { + contractIssues.push(`state-dir guard returned non-JSON output: ${trimmed}`); + continue; + } + if (!value || typeof value !== "object") { + contractIssues.push(`state-dir guard returned an invalid record: ${trimmed}`); + continue; } - for (const path of result.symlinkedRoots) { - issues.push(`state dir root is a symlink: ${path} (refusing to lock)`); + const record = value as Record; + if ( + record.type === "issue" && + typeof record.code === "string" && + typeof record.path === "string" && + typeof record.detail === "string" + ) { + issues.push(record as GuardIssue); + continue; } - for (const failure of result.mutationFailures) { - issues.push(`state dir mutation failed (${failure.op}): ${failure.path}`); + if ( + record.type === "result" && + (record.action === "preflight" || record.action === "lock" || record.action === "unlock") && + (record.status === "ok" || record.status === "failed") && + typeof record.issueCount === "number" && + Number.isInteger(record.issueCount) + ) { + summaries.push(record as GuardSummary); + continue; } + contractIssues.push(`state-dir guard returned an unknown record: ${trimmed}`); } - if (isLocking) { - issues.push( - ...verifyStateDirsLocked(privileged, configDir, { - highRiskOwner, - highRiskDirMode, - confidentialityOwner, - confidentialityDirMode, - }), + if (summaries.length !== 1) { + contractIssues.push(`state-dir guard returned ${String(summaries.length)} result records`); + } + const summary = summaries[0]; + if (summary && summary.action !== action) { + contractIssues.push(`state-dir guard result action=${summary.action} (expected ${action})`); + } + if (summary && summary.issueCount !== issues.length) { + contractIssues.push( + `state-dir guard result issueCount=${String(summary.issueCount)} (observed ${String(issues.length)})`, ); } - - // Restoration of runtime-writable subpaths runs only when the lock - // fan-out reported no issues. If preflight, mutation, or verification - // surfaced anything, the tree is in a known-bad state and re-opening - // `agents/*/sessions` for the sandbox user would widen the blast radius - // of whatever broke. - if (isLocking && issues.length === 0) { - issues.push(...restoreWritableRuntimeSubpaths(privileged, configDir)); + if (summary?.status === "ok" && (issues.length > 0 || result.status !== 0)) { + contractIssues.push("state-dir guard reported success with issues or a non-zero exit"); + } + if (summary?.status === "failed" && result.status === 0) { + contractIssues.push("state-dir guard reported failure with a zero exit"); + } + if (result.status === null || result.signal !== null || result.error) { + contractIssues.push(resultFailure("state-dir guard execution failed", result)); + } else if (result.status !== 0 && issues.length === 0) { + contractIssues.push(resultFailure("state-dir guard failed without a diagnostic", result)); + } + if (result.stderr.trim()) { + contractIssues.push(`state-dir guard wrote unexpected stderr: ${result.stderr.trim()}`); } - return issues; -} - -const STATE_DIR_LOCK_SCRIPT_BY_LIST = ` -set -u -config_dir="$1" -owner="$2" -recursive_mode="$3" -dir_mode="$4" -clear_setgid="$5" -shift 5 -for dir in "$@"; do - path="$config_dir/$dir" - if [ -L "$path" ]; then - printf 'symlinked-root\\t%s\\n' "$path" - continue - fi - [ -d "$path" ] || continue - if ! chown -R "$owner" "$path" 2>/dev/null; then - printf 'mutation-failed\\tchown\\t%s\\n' "$path" - fi - if ! chmod "$dir_mode" "$path" 2>/dev/null; then - printf 'mutation-failed\\tchmod-dir\\t%s\\n' "$path" - fi - if [ "$clear_setgid" = "1" ]; then - chmod g-s "$path" 2>/dev/null || true - fi - if ! chmod -R "$recursive_mode" "$path" 2>/dev/null; then - printf 'mutation-failed\\tchmod-recursive\\t%s\\n' "$path" - fi -done -exit 0 -`; - -const STATE_DIR_LOCK_SCRIPT_WORKSPACE_GLOB = ` -set -u -config_dir="$1" -owner="$2" -recursive_mode="$3" -dir_mode="$4" -clear_setgid="$5" -for dir in "$config_dir"/workspace-*; do - if [ -L "$dir" ]; then - printf 'symlinked-root\\t%s\\n' "$dir" - continue - fi - [ -d "$dir" ] || continue - if ! chown -R "$owner" "$dir" 2>/dev/null; then - printf 'mutation-failed\\tchown\\t%s\\n' "$dir" - fi - if ! chmod "$dir_mode" "$dir" 2>/dev/null; then - printf 'mutation-failed\\tchmod-dir\\t%s\\n' "$dir" - fi - if [ "$clear_setgid" = "1" ]; then - chmod g-s "$dir" 2>/dev/null || true - fi - if ! chmod -R "$recursive_mode" "$dir" 2>/dev/null; then - printf 'mutation-failed\\tchmod-recursive\\t%s\\n' "$dir" - fi -done -exit 0 -`; -interface VerifyExpectations { - highRiskOwner: string; - highRiskDirMode: string; - confidentialityOwner: string; - confidentialityDirMode: string; + return [ + ...issues.map( + (issue) => `state-dir guard ${action} [${issue.code}] ${issue.path}: ${issue.detail}`, + ), + ...contractIssues, + ]; } -function verifyStateDirsLocked( - privileged: PrivilegedExec, - configDir: string, - expected: VerifyExpectations, -): string[] { - const issues: string[] = []; - issues.push( - ...verifyStateDirGroup(privileged, configDir, HIGH_RISK_STATE_DIRS, { - owner: expected.highRiskOwner, - dirMode: expected.highRiskDirMode, - includeWorkspaceGlob: true, - }), - ); - issues.push( - ...verifyStateDirGroup(privileged, configDir, CONFIDENTIALITY_STATE_DIRS, { - owner: expected.confidentialityOwner, - dirMode: expected.confidentialityDirMode, - includeWorkspaceGlob: false, - }), - ); - return issues; +let cachedHostHelper: string | null = null; + +function readHostHelper(): string { + if (cachedHostHelper !== null) return cachedHostHelper; + cachedHostHelper = fs.readFileSync(HOST_HELPER, "utf-8"); + return cachedHostHelper; } -function verifyStateDirGroup( +function runStateDirGuard( privileged: PrivilegedExec, + action: GuardAction, configDir: string, - dirs: readonly string[], - expected: { owner: string; dirMode: string; includeWorkspaceGlob: boolean }, ): string[] { - let stdout = ""; - try { - stdout = privileged.capture([ - "sh", - "-c", - ` -set -u -config_dir="$1" -expected_owner="$2" -expected_mode="$3" -include_workspace="$4" -shift 4 -check() { - path="$1" - [ -L "$path" ] && { printf 'verify-symlink\\t%s\\n' "$path"; return; } - [ -d "$path" ] || return - perms="$(stat -c '%a %U:%G' "$path" 2>/dev/null)" || { - printf 'verify-stat-failed\\t%s\\n' "$path" - return - } - mode="\${perms%% *}" - owner="\${perms#* }" - [ "$mode" = "$expected_mode" ] || printf 'verify-mode\\t%s\\t%s\\t%s\\n' "$path" "$mode" "$expected_mode" - [ "$owner" = "$expected_owner" ] || printf 'verify-owner\\t%s\\t%s\\t%s\\n' "$path" "$owner" "$expected_owner" -} -for dir in "$@"; do - check "$config_dir/$dir" -done -if [ "$include_workspace" = "1" ]; then - for dir in "$config_dir"/workspace-*; do - case "$dir" in *"*"*) continue ;; esac - check "$dir" - done -fi -exit 0 -`, - "sh", + const capability = privileged.run(["test", "-r", CONTAINER_HELPER]); + let command: string[]; + let input: string | undefined; + if (capability.status === 0 && capability.signal === null && !capability.error) { + command = [ + ...CONTAINER_TIMEOUT, + "python3", + "-I", + CONTAINER_HELPER, + action, + "--config-dir", configDir, - expected.owner, - expected.dirMode, - expected.includeWorkspaceGlob ? "1" : "0", - ...dirs, - ]); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - return [`state dir verification exec failed: ${msg}`]; - } - const issues: string[] = []; - for (const line of stdout.split("\n")) { - const parts = line.split("\t"); - if (parts[0] === "verify-symlink" && parts[1]) { - issues.push(`state dir became a symlink mid-lock: ${parts[1]}`); - } else if (parts[0] === "verify-stat-failed" && parts[1]) { - issues.push(`state dir stat failed after lock: ${parts[1]}`); - } else if (parts[0] === "verify-mode" && parts[1]) { - issues.push(`state dir mode=${parts[2]} (expected ${parts[3]}): ${parts[1]}`); - } else if (parts[0] === "verify-owner" && parts[1]) { - issues.push(`state dir owner=${parts[2]} (expected ${parts[3]}): ${parts[1]}`); + ]; + } else if (capability.status === 1 && capability.signal === null && !capability.error) { + // New CLIs must still be able to rebuild an old sandbox image. Inject the + // exact trusted helper shipped with this CLI over docker exec stdin rather + // than falling back to symlink-following recursive shell commands. + try { + input = readHostHelper(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return [ + `state-dir guard is absent in the sandbox and host helper cannot be read: ${message}`, + ]; } + command = [...CONTAINER_TIMEOUT, "python3", "-I", "-", action, "--config-dir", configDir]; + } else { + return [resultFailure("state-dir guard capability probe failed", capability)]; } - return issues; + + return parseGuardOutput(action, privileged.run(command, input)); } -function preflightSymlinkedRoots( - privileged: PrivilegedExec, - configDir: string, - allStateDirs: readonly string[], -): PreflightResult { - let stdout = ""; - try { - stdout = privileged.capture([ - "sh", - "-c", - ` -set -u -config_dir="$1" -shift -for dir in "$@"; do - path="$config_dir/$dir" - if [ -L "$path" ]; then printf '%s\\n' "$path"; fi -done -for dir in "$config_dir"/workspace-*; do - if [ -L "$dir" ]; then printf '%s\\n' "$dir"; fi -done -exit 0 -`, - "sh", - configDir, - ...allStateDirs, - ]); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - return { symlinkedRoots: [], error: msg }; - } - return { - symlinkedRoots: stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0), - error: null, - }; +// Read-only recursive validation. Call this before top-level config mutation so +// a hostile nested link, hardlink, special entry, or cross-device mount fails +// without partially changing the protected tree. +export function preflightStateDirLock(privileged: PrivilegedExec, configDir: string): string[] { + return runStateDirGuard(privileged, "preflight", configDir); } -function runStateDirLockScript( +// Apply and independently verify the complete recursive state-dir posture. +// `highRiskOwner` remains explicit to prevent a caller from accidentally using +// this fixed policy for a different ownership contract. +export function applyStateDirLockMode( privileged: PrivilegedExec, - script: StateDirLockScript, -): StateDirLockScriptResult { - let stdout = ""; - try { - stdout = privileged.capture(["sh", "-c", script.script, "sh", ...script.args]); - } catch (err) { - return { - symlinkedRoots: [], - mutationFailures: [], - execError: err instanceof Error ? err.message : String(err), - }; - } - const result: StateDirLockScriptResult = { - symlinkedRoots: [], - mutationFailures: [], - execError: null, - }; - for (const line of stdout.split("\n")) { - const parts = line.split("\t"); - if (parts[0] === "symlinked-root" && parts[1]) { - result.symlinkedRoots.push(parts[1]); - } else if (parts[0] === "mutation-failed" && parts[1] && parts[2]) { - result.mutationFailures.push({ op: parts[1], path: parts[2] }); - } + configDir: string, + highRiskOwner: string, + isLocking: boolean, +): string[] { + const expectedOwner = isLocking ? "root:sandbox" : "sandbox:sandbox"; + if (highRiskOwner !== expectedOwner) { + return [ + `state-dir guard owner contract mismatch: ${highRiskOwner} (expected ${expectedOwner})`, + ]; } - return result; + return runStateDirGuard(privileged, isLocking ? "lock" : "unlock", configDir); } -// Restore runtime-writable subpaths after a successful lock fan-out. -// Returns issues for any mkdir/chown/chmod failure observed inside the -// script (parsed from `restore-failed\t\t` markers) plus a -// stat-based verification pass that confirms every restored target ends -// up as `sandbox:sandbox 2770`. Empty list means the carve-out is good. -function restoreWritableRuntimeSubpaths(privileged: PrivilegedExec, configDir: string): string[] { - let stdout = ""; - try { - stdout = privileged.capture([ - "sh", - "-c", - ` -set -u -config_dir="$1" -shift -for pattern in "$@"; do - case "$pattern" in - */*) prefix="\${pattern%/*}"; leaf="\${pattern##*/}" ;; - *) prefix=""; leaf="$pattern" ;; - esac - if [ -n "$prefix" ]; then - set -- "$config_dir"/$prefix - else - set -- "$config_dir" - fi - for parent in "$@"; do - case "$parent" in - *"*"*) continue ;; - esac - if [ -L "$parent" ]; then continue; fi - if [ ! -d "$parent" ]; then continue; fi - target="$parent/$leaf" - if [ -L "$target" ]; then continue; fi - if ! mkdir -p "$target" 2>/dev/null; then - printf 'restore-failed\\tmkdir\\t%s\\n' "$target" - continue - fi - if ! chown -R sandbox:sandbox "$target" 2>/dev/null; then - printf 'restore-failed\\tchown\\t%s\\n' "$target" - fi - if ! chmod 2770 "$target" 2>/dev/null; then - printf 'restore-failed\\tchmod-dir\\t%s\\n' "$target" - fi - if ! chmod -R g+rwX,o-rwx "$target" 2>/dev/null; then - printf 'restore-failed\\tchmod-recursive\\t%s\\n' "$target" - fi - perms="$(stat -c '%a %U:%G' "$target" 2>/dev/null)" || { - printf 'restore-verify-stat-failed\\t%s\\n' "$target" - continue - } - mode="\${perms%% *}" - owner="\${perms#* }" - [ "$mode" = "2770" ] || printf 'restore-verify-mode\\t%s\\t%s\\n' "$target" "$mode" - [ "$owner" = "sandbox:sandbox" ] || printf 'restore-verify-owner\\t%s\\t%s\\n' "$target" "$owner" - done -done -exit 0 -`, - "sh", - configDir, - ...WRITABLE_RUNTIME_SUBPATHS, - ]); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - return [`runtime-writable subpath restore exec failed: ${msg}`]; - } - const issues: string[] = []; - for (const line of stdout.split("\n")) { - const parts = line.split("\t"); - if (parts[0] === "restore-failed" && parts[1] && parts[2]) { - issues.push(`runtime-writable subpath restore failed (${parts[1]}): ${parts[2]}`); - } else if (parts[0] === "restore-verify-stat-failed" && parts[1]) { - issues.push(`runtime-writable subpath stat failed after restore: ${parts[1]}`); - } else if (parts[0] === "restore-verify-mode" && parts[1]) { - issues.push(`runtime-writable subpath mode=${parts[2]} (expected 2770): ${parts[1]}`); - } else if (parts[0] === "restore-verify-owner" && parts[1]) { - issues.push( - `runtime-writable subpath owner=${parts[2]} (expected sandbox:sandbox): ${parts[1]}`, - ); - } +export function restoreStateDirLockPosture( + privileged: PrivilegedExec, + configDir: string, + originallyLocked: boolean, +): string[] { + if (!originallyLocked) { + return applyStateDirLockMode(privileged, configDir, "sandbox:sandbox", false); } - return issues; + const preflightIssues = preflightStateDirLock(privileged, configDir); + if (preflightIssues.length > 0) return preflightIssues; + return applyStateDirLockMode(privileged, configDir, "root:sandbox", true); } diff --git a/src/lib/shields/timer-bound-lock.test.ts b/src/lib/shields/timer-bound-lock.test.ts new file mode 100644 index 00000000000..435c558cb9e --- /dev/null +++ b/src/lib/shields/timer-bound-lock.test.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { + withTimerBoundShieldsMutationLock, + withTimerBoundShieldsMutationLockAsync, +} from "./timer-bound-lock"; + +describe("timer-bound shields mutation lock", () => { + it("retries without mutating when the timer generation changes while waiting", () => { + const oldToken = "1".repeat(32); + const newToken = "2".repeat(32); + const tokens = [oldToken, newToken, newToken, newToken]; + const callback = vi.fn(() => "done"); + const observedOptions: unknown[] = []; + + const result = withTimerBoundShieldsMutationLock("alpha", "config set write", callback, { + readToken: () => tokens.shift(), + withLock: (_name, _command, fn, options) => { + observedOptions.push(options); + return fn(); + }, + withLockAsync: vi.fn(), + }); + + expect(result).toBe("done"); + expect(callback).toHaveBeenCalledTimes(1); + expect(observedOptions).toEqual([{ takeoverToken: oldToken }, { takeoverToken: newToken }]); + }); + + it("binds the async operation to the stable current timer token", async () => { + const token = "a".repeat(32); + const callback = vi.fn(async () => 42); + const withLockAsync = vi.fn(async (_name, _command, fn, options) => { + expect(options).toEqual({ takeoverToken: token }); + return fn(); + }); + + await expect( + withTimerBoundShieldsMutationLockAsync("alpha", "inference set", callback, { + readToken: () => token, + withLock: vi.fn(), + withLockAsync, + }), + ).resolves.toBe(42); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it("fails closed when timer generations keep changing", () => { + let generation = 0; + expect(() => + withTimerBoundShieldsMutationLock("alpha", "gateway restart", () => undefined, { + readToken: () => (++generation).toString(16).padStart(32, "0"), + withLock: (_name, _command, fn) => fn(), + withLockAsync: vi.fn(), + }), + ).toThrow(/kept changing/); + }); +}); diff --git a/src/lib/shields/timer-bound-lock.ts b/src/lib/shields/timer-bound-lock.ts new file mode 100644 index 00000000000..4514cefe55f --- /dev/null +++ b/src/lib/shields/timer-bound-lock.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readAutoRestoreTakeoverToken } from "./timer-control"; +import { withShieldsTransitionLock, withShieldsTransitionLockAsync } from "./transition-lock"; + +const MAX_TIMER_GENERATION_RETRIES = 3; + +type TimerBoundLockDeps = { + readToken: (sandboxName: string) => string | undefined; + withLock: typeof withShieldsTransitionLock; + withLockAsync: typeof withShieldsTransitionLockAsync; +}; + +const defaultDeps: TimerBoundLockDeps = { + readToken: readAutoRestoreTakeoverToken, + withLock: withShieldsTransitionLock, + withLockAsync: withShieldsTransitionLockAsync, +}; + +type Attempt = { retry: true } | { retry: false; value: T }; + +/** + * Serialize a mutation and bind its lock owner to the exact active restore + * timer generation. If a timer is replaced while this operation waits for the + * lock, release without mutating and retry with the new token. This prevents a + * command that observed timer A from becoming non-preemptible inside timer B's + * mutable window. + */ +export function withTimerBoundShieldsMutationLock( + sandboxName: string, + command: string, + fn: () => T, + deps: TimerBoundLockDeps = defaultDeps, +): T { + for (let attempt = 0; attempt < MAX_TIMER_GENERATION_RETRIES; attempt += 1) { + const token = deps.readToken(sandboxName); + const result = deps.withLock>( + sandboxName, + command, + () => { + if (deps.readToken(sandboxName) !== token) return { retry: true }; + return { retry: false, value: fn() }; + }, + token ? { takeoverToken: token } : {}, + ); + if (!result.retry) return result.value; + } + throw new Error(`Auto-restore timer generation kept changing while acquiring '${command}'`); +} + +export async function withTimerBoundShieldsMutationLockAsync( + sandboxName: string, + command: string, + fn: () => Promise, + deps: TimerBoundLockDeps = defaultDeps, +): Promise { + for (let attempt = 0; attempt < MAX_TIMER_GENERATION_RETRIES; attempt += 1) { + const token = deps.readToken(sandboxName); + const result = await deps.withLockAsync>( + sandboxName, + command, + async () => { + if (deps.readToken(sandboxName) !== token) return { retry: true }; + return { retry: false, value: await fn() }; + }, + token ? { takeoverToken: token } : {}, + ); + if (!result.retry) return result.value; + } + throw new Error(`Auto-restore timer generation kept changing while acquiring '${command}'`); +} diff --git a/src/lib/shields/timer-control.ts b/src/lib/shields/timer-control.ts index 9b575a7ee21..6efd41881c0 100644 --- a/src/lib/shields/timer-control.ts +++ b/src/lib/shields/timer-control.ts @@ -13,6 +13,9 @@ interface TimerMarker { snapshotPath: string; restoreAt: string; processToken?: string; + allowLegacyHermesProtocol?: boolean; + leaseOwnerPid?: number; + leaseOwnerStartIdentity?: string; } type UnknownRecord = { [key: string]: unknown }; @@ -31,7 +34,19 @@ function isTimerMarker(value: unknown): value is TimerMarker { typeof value.sandboxName === "string" && typeof value.snapshotPath === "string" && typeof value.restoreAt === "string" && - (value.processToken === undefined || typeof value.processToken === "string") + (value.processToken === undefined || typeof value.processToken === "string") && + (value.allowLegacyHermesProtocol === undefined || + typeof value.allowLegacyHermesProtocol === "boolean") && + (value.leaseOwnerPid === undefined || + (typeof value.leaseOwnerPid === "number" && + Number.isInteger(value.leaseOwnerPid) && + value.leaseOwnerPid > 0)) && + (value.leaseOwnerStartIdentity === undefined || + typeof value.leaseOwnerStartIdentity === "string") && + ((value.leaseOwnerPid === undefined && value.leaseOwnerStartIdentity === undefined) || + (typeof value.leaseOwnerPid === "number" && + typeof value.leaseOwnerStartIdentity === "string" && + value.leaseOwnerStartIdentity.length > 0)) ); } @@ -50,6 +65,18 @@ function readTimerMarker(sandboxName: string): TimerMarker | null { } } +function readAutoRestoreTakeoverToken(sandboxName: string): string | undefined { + const marker = readTimerMarker(sandboxName); + if ( + marker?.sandboxName !== sandboxName || + typeof marker.processToken !== "string" || + !/^[0-9a-f]{32}$/.test(marker.processToken) + ) { + return undefined; + } + return marker.processToken; +} + interface ClearTimerMarkerResult { cleared: boolean; warning?: string; @@ -74,6 +101,30 @@ function clearTimerMarker(sandboxName: string): ClearTimerMarkerResult { function isProcessAlive(pid: number): boolean { if (!Number.isInteger(pid) || pid <= 0) return false; + try { + const raw = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf-8"); + const closingParen = raw.lastIndexOf(")"); + if ( + closingParen >= 0 && + raw + .slice(closingParen + 2) + .trim() + .split(/\s+/, 1)[0] === "Z" + ) { + return false; + } + } catch { + try { + const state = execFileSync("ps", ["-o", "stat=", "-p", String(pid)], { + stdio: ["ignore", "pipe", "ignore"], + }) + .toString() + .trim(); + if (state.startsWith("Z")) return false; + } catch { + // Fall through to kill(0), which supplies the final liveness answer. + } + } try { process.kill(pid, 0); return true; @@ -82,6 +133,89 @@ function isProcessAlive(pid: number): boolean { } } +function readProcessStartIdentity(pid: number): string | null { + if (!Number.isInteger(pid) || pid <= 0) return null; + try { + const raw = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf-8"); + const closingParen = raw.lastIndexOf(")"); + if (closingParen >= 0) { + const fields = raw + .slice(closingParen + 2) + .trim() + .split(/\s+/); + // The suffix starts at field 3 (`state`); Linux starttime is field 22. + if (fields[19]) return `proc:${fields[19]}`; + } + } catch { + // Fall through to the portable ps identity. + } + + try { + const started = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { + stdio: ["ignore", "pipe", "ignore"], + }) + .toString() + .trim(); + return started ? `ps:${started}` : null; + } catch { + return null; + } +} + +interface ProcessIdentity { + pid: number; + startIdentity: string; + depth: number; +} + +function listDescendantProcessIdentities(rootPid: number): ProcessIdentity[] | null { + if (!Number.isInteger(rootPid) || rootPid <= 0) return null; + let rows: Array<{ pid: number; ppid: number }> = []; + try { + rows = execFileSync("ps", ["-e", "-o", "pid=,ppid="], { + stdio: ["ignore", "pipe", "ignore"], + }) + .toString() + .split("\n") + .map((line) => line.trim().split(/\s+/)) + .filter((parts) => parts.length >= 2) + .map(([pid, ppid]) => ({ pid: Number(pid), ppid: Number(ppid) })) + .filter((row) => Number.isInteger(row.pid) && Number.isInteger(row.ppid)); + } catch { + return null; + } + + const descendants: Array<{ pid: number; depth: number }> = []; + let frontier = [{ pid: rootPid, depth: 0 }]; + const seen = new Set([rootPid]); + while (frontier.length > 0) { + const next: Array<{ pid: number; depth: number }> = []; + for (const parent of frontier) { + for (const row of rows) { + if (row.ppid !== parent.pid || seen.has(row.pid)) continue; + seen.add(row.pid); + const child = { pid: row.pid, depth: parent.depth + 1 }; + descendants.push(child); + next.push(child); + } + } + frontier = next; + } + + const identities: ProcessIdentity[] = []; + for (const { pid, depth } of descendants) { + const startIdentity = readProcessStartIdentity(pid); + if (startIdentity) { + identities.push({ pid, startIdentity, depth }); + } else if (isProcessAlive(pid)) { + // A live descendant that cannot be identity-pinned must not be signaled; + // callers fail closed instead of risking PID-reuse collateral damage. + return null; + } + } + return identities.sort((a, b) => b.depth - a.depth); +} + function readProcessCommandLine(pid: number): string | null { const procCmdline = `/proc/${String(pid)}/cmdline`; try { @@ -187,13 +321,15 @@ function killTimer(sandboxName: string): KillTimerResult { }; } +export type { ClearTimerMarkerResult, KillTimerResult, ProcessIdentity, TimerMarker }; export { - timerMarkerPath, - readTimerMarker, clearTimerMarker, isProcessAlive, - verifyTimerMarkerIdentity, killTimer, + listDescendantProcessIdentities, + readAutoRestoreTakeoverToken, + readProcessStartIdentity, + readTimerMarker, + timerMarkerPath, + verifyTimerMarkerIdentity, }; - -export type { TimerMarker, ClearTimerMarkerResult, KillTimerResult }; diff --git a/src/lib/shields/timer.test.ts b/src/lib/shields/timer.test.ts index ab5e97203fd..8dd80effec4 100644 --- a/src/lib/shields/timer.test.ts +++ b/src/lib/shields/timer.test.ts @@ -9,8 +9,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const shieldsIndexMock = vi.hoisted(() => ({ lockAgentConfig: vi.fn() as unknown, + prepareAutoRestoreTransitionTakeover: vi.fn(), })); +const PROCESS_TOKEN = "a".repeat(32); + const runMock = vi.fn(() => ({ status: 0 })); vi.mock("../runner", () => ({ @@ -41,6 +44,7 @@ vi.mock("./index", () => ({ get lockAgentConfig() { return shieldsIndexMock.lockAgentConfig; }, + prepareAutoRestoreTransitionTakeover: shieldsIndexMock.prepareAutoRestoreTransitionTakeover, })); describe("shields timer authorization", () => { @@ -77,6 +81,21 @@ describe("shields timer authorization", () => { } } + function invokeTimerAndExpectRetry(runRestoreTimer: (args: any) => void, args: unknown): void { + vi.useFakeTimers(); + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + try { + runRestoreTimer(args); + expect(exitSpy).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(1); + } finally { + exitSpy.mockRestore(); + vi.useRealTimers(); + } + } + it("does not restore or rewrite state when marker is missing", async () => { const timer = await import("./timer"); const stateDir = path.join(tmpHome, ".nemoclaw", "state"); @@ -144,6 +163,160 @@ describe("shields timer authorization", () => { expect(fs.existsSync(markerPath)).toBe(true); }); + it("binds rebuild-only legacy authorization to both argv and the root-owned marker", async () => { + const timer = await import("./timer"); + const stateDir = path.join(tmpHome, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + const sandboxName = "legacy-hermes"; + const snapshotPath = path.join(stateDir, "snapshot.yaml"); + const restoreAtIso = new Date(Date.now() + 60_000).toISOString(); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAtIso, + processToken: PROCESS_TOKEN, + allowLegacyHermesProtocol: true, + }), + ); + + const authorized = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "/sandbox/.hermes/config.yaml", + "/sandbox/.hermes", + PROCESS_TOKEN, + "1", + ]); + const ordinary = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "/sandbox/.hermes/config.yaml", + "/sandbox/.hermes", + PROCESS_TOKEN, + "0", + ]); + + expect(authorized).not.toBeNull(); + expect(authorized?.allowLegacyHermesProtocol).toBe(true); + expect(timer.markerMatchesCurrentTimer(authorized!)).toBe(true); + expect(timer.markerMatchesCurrentTimer(ordinary!)).toBe(false); + expect( + timer.parseTimerArgs([sandboxName, snapshotPath, restoreAtIso, "", "", PROCESS_TOKEN, "yes"]), + ).toBeNull(); + }); + + it("defers the rebuild auto-restore deadline while the exact rebuild owner is alive", async () => { + vi.useFakeTimers(); + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + try { + const timer = await import("./timer"); + const { readProcessStartIdentity } = await import("./timer-control"); + const ownerIdentity = readProcessStartIdentity(process.pid); + expect(ownerIdentity).toBeTruthy(); + const stateDir = path.join(tmpHome, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + const sandboxName = "rebuild-live"; + const snapshotPath = path.join(stateDir, "snapshot.yaml"); + const restoreAtIso = new Date().toISOString(); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAtIso, + processToken: PROCESS_TOKEN, + leaseOwnerPid: process.pid, + leaseOwnerStartIdentity: ownerIdentity, + }), + ); + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + "0", + String(process.pid), + ownerIdentity!, + ]); + expect(args).not.toBeNull(); + + timer.runRestoreTimer(args!); + + expect(runMock).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(1); + expect(fs.existsSync(markerPath)).toBe(true); + } finally { + exitSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("retains a dead rebuild owner's timer and retries a transient restore failure", async () => { + vi.useFakeTimers(); + const exitSpy = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + try { + const timer = await import("./timer"); + const stateDir = path.join(tmpHome, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + const sandboxName = "rebuild-dead"; + const snapshotPath = path.join(stateDir, "snapshot.yaml"); + const restoreAtIso = new Date().toISOString(); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAtIso, + processToken: PROCESS_TOKEN, + leaseOwnerPid: 2_147_483_000, + leaseOwnerStartIdentity: "proc:dead-owner", + }), + ); + runMock.mockReturnValueOnce({ status: 17 }); + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + "0", + "2147483000", + "proc:dead-owner", + ]); + expect(args).not.toBeNull(); + + timer.runRestoreTimer(args!); + + expect(runMock).toHaveBeenCalledTimes(1); + expect(exitSpy).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(1); + expect(fs.existsSync(markerPath)).toBe(true); + } finally { + exitSpy.mockRestore(); + vi.useRealTimers(); + } + }); + it("does not restore or rewrite state when marker pid mismatches", async () => { const timer = await import("./timer"); const stateDir = path.join(tmpHome, ".nemoclaw", "state"); @@ -165,11 +338,18 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); - const args = timer.parseTimerArgs([sandboxName, snapshotPath, restoreAtIso, "", "", "tok"]); + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + ]); expect(args).not.toBeNull(); const exitCode = invokeTimerAndCaptureExit(timer.runRestoreTimer, args); @@ -180,6 +360,52 @@ describe("shields timer authorization", () => { expect(fs.existsSync(markerPath)).toBe(true); }); + it("does not delete a replacement timer marker during owned-marker cleanup", async () => { + const timer = await import("./timer"); + const stateDir = path.join(tmpHome, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + const sandboxName = "marker-race"; + const snapshotPath = path.join(stateDir, "snapshot.yaml"); + const restoreAtIso = new Date().toISOString(); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + const oldMarker = { + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAtIso, + processToken: PROCESS_TOKEN, + }; + const replacementMarker = { + ...oldMarker, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken: "b".repeat(32), + }; + fs.writeFileSync(markerPath, JSON.stringify(oldMarker)); + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + ]); + expect(args).not.toBeNull(); + + const originalRename = fs.renameSync.bind(fs); + const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + originalRename(source, destination); + String(source) === markerPath && + fs.writeFileSync(markerPath, JSON.stringify(replacementMarker)); + }); + try { + expect(timer.cleanupOwnedTimerMarker(args!)).toBe(true); + } finally { + renameSpy.mockRestore(); + } + + expect(JSON.parse(fs.readFileSync(markerPath, "utf-8"))).toEqual(replacementMarker); + }); + it("restores and updates state when marker matches current timer invocation", async () => { const timer = await import("./timer"); const stateDir = path.join(tmpHome, ".nemoclaw", "state"); @@ -198,13 +424,30 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); - const args = timer.parseTimerArgs([sandboxName, snapshotPath, restoreAtIso, "", "", "tok"]); + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + ]); expect(args).not.toBeNull(); + const lockPath = path.join(stateDir, `shields-transition-lock-${sandboxName}.json`); + runMock.mockImplementationOnce(() => { + expect(JSON.parse(fs.readFileSync(lockPath, "utf-8"))).toMatchObject({ + sandboxName, + command: "shields auto-restore", + takeoverToken: PROCESS_TOKEN, + }); + return { status: 0 }; + }); + const exitCode = invokeTimerAndCaptureExit(timer.runRestoreTimer, args); const stateFile = path.join(stateDir, `shields-${sandboxName}.json`); const updatedState = JSON.parse(fs.readFileSync(stateFile, "utf-8")); @@ -216,6 +459,59 @@ describe("shields timer authorization", () => { expect(fs.existsSync(markerPath)).toBe(false); }); + it("retains recovery authority when the locked-state commit cannot be persisted", async () => { + const timer = await import("./timer"); + const stateDir = path.join(tmpHome, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + + const sandboxName = "alpha"; + const snapshotPath = path.join(stateDir, "snapshot.yaml"); + const restoreAtIso = new Date(Date.now() + 60_000).toISOString(); + const markerPath = path.join(stateDir, `shields-timer-${sandboxName}.json`); + const stateFile = path.join(stateDir, `shields-${sandboxName}.json`); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n default: {}\n"); + fs.writeFileSync(stateFile, JSON.stringify({ shieldsDown: true }), { mode: 0o600 }); + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: process.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAtIso, + processToken: PROCESS_TOKEN, + }), + ); + + const originalRename = fs.renameSync.bind(fs); + const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + switch (String(destination)) { + case stateFile: { + const error = new Error("simulated state commit failure") as NodeJS.ErrnoException; + error.code = "EIO"; + throw error; + } + } + return originalRename(source, destination); + }); + try { + const args = timer.parseTimerArgs([ + sandboxName, + snapshotPath, + restoreAtIso, + "", + "", + PROCESS_TOKEN, + ]); + expect(args).not.toBeNull(); + invokeTimerAndExpectRetry(timer.runRestoreTimer, args); + } finally { + renameSpy.mockRestore(); + } + + expect(JSON.parse(fs.readFileSync(stateFile, "utf-8")).shieldsDown).toBe(true); + expect(fs.existsSync(markerPath)).toBe(true); + }); + it("persists chattrApplied and fileHashes from the auto-restore lock result", async () => { const stateDir = path.join(tmpHome, ".nemoclaw", "state"); fs.mkdirSync(stateDir, { recursive: true }); @@ -237,7 +533,7 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); @@ -267,7 +563,7 @@ describe("shields timer authorization", () => { restoreAtIso, configPath, configDir, - "tok", + PROCESS_TOKEN, ]); expect(args).not.toBeNull(); @@ -309,7 +605,7 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); @@ -329,11 +625,11 @@ describe("shields timer authorization", () => { restoreAtIso, configPath, configDir, - "tok", + PROCESS_TOKEN, ]); expect(args).not.toBeNull(); - const exitCode = invokeTimerAndCaptureExit(timer.runRestoreTimer, args); + invokeTimerAndExpectRetry(timer.runRestoreTimer, args); const updatedState = JSON.parse(fs.readFileSync(stateFile, "utf-8")); const auditEntries = fs .readFileSync(auditFile, "utf-8") @@ -341,7 +637,6 @@ describe("shields timer authorization", () => { .split("\n") .map((line) => JSON.parse(line)); - expect(exitCode).toBe(1); expect(runMock).toHaveBeenCalledTimes(1); expect(updatedState.shieldsDown).toBe(true); expect(auditEntries).toContainEqual( @@ -359,7 +654,7 @@ describe("shields timer authorization", () => { error: "Config re-lock verification failed — shields remain DOWN", }), ); - expect(fs.existsSync(markerPath)).toBe(false); + expect(fs.existsSync(markerPath)).toBe(true); }); // ------------------------------------------------------------------------- @@ -402,7 +697,7 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); @@ -429,7 +724,7 @@ describe("shields timer authorization", () => { restoreAtIso, configPath, configDir, - "tok", + PROCESS_TOKEN, ]); expect(args).not.toBeNull(); @@ -466,7 +761,7 @@ describe("shields timer authorization", () => { sandboxName, snapshotPath, restoreAt: restoreAtIso, - processToken: "tok", + processToken: PROCESS_TOKEN, }), ); @@ -502,11 +797,11 @@ describe("shields timer authorization", () => { restoreAtIso, configPath, configDir, - "tok", + PROCESS_TOKEN, ]); expect(args).not.toBeNull(); - const exitCode = invokeTimerAndCaptureExit(timer.runRestoreTimer, args); + invokeTimerAndExpectRetry(timer.runRestoreTimer, args); const updatedState = JSON.parse(fs.readFileSync(stateFile, "utf-8")); const auditEntries = fs .readFileSync(auditFile, "utf-8") @@ -514,7 +809,6 @@ describe("shields timer authorization", () => { .split("\n") .map((line) => JSON.parse(line)); - expect(exitCode).toBe(1); expect(updatedState.shieldsDown).toBe(true); // Both audit outcomes must fire: the re-lock warning AND the terminal // fail-closed entry that keeps shields DOWN. diff --git a/src/lib/shields/timer.ts b/src/lib/shields/timer.ts index e26c9f6f95d..a0c25602535 100644 --- a/src/lib/shields/timer.ts +++ b/src/lib/shields/timer.ts @@ -6,7 +6,7 @@ // restores the captured policy snapshot. // // Usage (internal — called by shields.ts via fork()): -// node shields-timer.js +// node shields-timer.js import fs from "node:fs"; import path from "node:path"; @@ -18,6 +18,8 @@ import { resolveNemoclawStateDir } from "../state/paths"; import { appendAuditEntry, type ShieldsAuditEntry } from "./audit"; import * as shields from "./index"; import { relockAndReconfirm } from "./relock-reconfirm"; +import { isProcessAlive, readProcessStartIdentity } from "./timer-control"; +import { withShieldsTransitionLock } from "./transition-lock"; interface ShieldsStatePatch { shieldsDown?: boolean; @@ -40,17 +42,41 @@ interface TimerArgs { configPath?: string; configDir?: string; processToken?: string; + allowLegacyHermesProtocol: boolean; + leaseOwnerPid?: number; + leaseOwnerStartIdentity?: string; } type LockAgentConfig = typeof shields.lockAgentConfig; const STATE_DIR = resolveNemoclawStateDir(); +const AUTO_RESTORE_RETRY_MS = 5_000; function parseTimerArgs(argv: string[]): TimerArgs | null { - const [sandboxName, snapshotPath, restoreAtIso, configPath, configDir, processToken] = argv; + const [ + sandboxName, + snapshotPath, + restoreAtIso, + configPath, + configDir, + processToken, + allowLegacyHermes, + leaseOwnerPidRaw, + leaseOwnerStartIdentityRaw, + ] = argv; const restoreAtMs = restoreAtIso ? new Date(restoreAtIso).getTime() : Number.NaN; + const leaseOwnerPid = leaseOwnerPidRaw ? Number(leaseOwnerPidRaw) : undefined; + const leaseOwnerStartIdentity = leaseOwnerStartIdentityRaw || undefined; - if (!sandboxName || !snapshotPath || !restoreAtIso || Number.isNaN(restoreAtMs)) { + if ( + !sandboxName || + !snapshotPath || + !restoreAtIso || + Number.isNaN(restoreAtMs) || + (allowLegacyHermes !== undefined && allowLegacyHermes !== "0" && allowLegacyHermes !== "1") || + ((leaseOwnerPidRaw || leaseOwnerStartIdentityRaw) && + (!Number.isInteger(leaseOwnerPid) || Number(leaseOwnerPid) <= 0 || !leaseOwnerStartIdentity)) + ) { return null; } @@ -65,6 +91,8 @@ function parseTimerArgs(argv: string[]): TimerArgs | null { configPath, configDir, processToken, + allowLegacyHermesProtocol: allowLegacyHermes === "1", + ...(leaseOwnerPid && leaseOwnerStartIdentity ? { leaseOwnerPid, leaseOwnerStartIdentity } : {}), }; } @@ -89,22 +117,35 @@ function readStateFile(stateFile: string): UnknownRecord { } function updateState(stateFile: string, patch: ShieldsStatePatch): void { + const current = readStateFile(stateFile); + const updated = { ...current, ...patch, updatedAt: new Date().toISOString() }; + const parent = path.dirname(stateFile); + fs.mkdirSync(parent, { recursive: true, mode: 0o700 }); + const tempPath = path.join( + parent, + `.${path.basename(stateFile)}.${String(process.pid)}.${Date.now().toString(16)}.tmp`, + ); + let fd: number | undefined; try { - const current = readStateFile(stateFile); - const updated = { ...current, ...patch, updatedAt: new Date().toISOString() }; - fs.writeFileSync(stateFile, JSON.stringify(updated, null, 2), { mode: 0o600 }); - } catch { - // Best effort - } -} - -function cleanupMarker(markerPath: string): void { - try { - if (fs.existsSync(markerPath)) { - fs.unlinkSync(markerPath); + fd = fs.openSync(tempPath, "wx", 0o600); + fs.writeFileSync(fd, JSON.stringify(updated, null, 2)); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = undefined; + fs.renameSync(tempPath, stateFile); + const parentFd = fs.openSync(parent, "r"); + try { + fs.fsyncSync(parentFd); + } finally { + fs.closeSync(parentFd); + } + } finally { + if (fd !== undefined) fs.closeSync(fd); + try { + fs.rmSync(tempPath, { force: true }); + } catch { + // Preserve the original state-commit failure. } - } catch { - // Best effort } } @@ -120,6 +161,48 @@ function readTimerMarker(markerPath: string): UnknownRecord | null { } } +function markerRecordMatchesCurrentTimer(marker: UnknownRecord | null, args: TimerArgs): boolean { + if (!marker) return false; + return ( + marker.pid === process.pid && + marker.sandboxName === args.sandboxName && + marker.snapshotPath === args.snapshotPath && + marker.restoreAt === args.restoreAtIso && + marker.processToken === args.processToken && + (marker.allowLegacyHermesProtocol === true) === args.allowLegacyHermesProtocol && + marker.leaseOwnerPid === args.leaseOwnerPid && + marker.leaseOwnerStartIdentity === args.leaseOwnerStartIdentity + ); +} + +function cleanupOwnedTimerMarker(args: TimerArgs): boolean { + const quarantinePath = `${args.markerPath}.completed-${String(process.pid)}-${Date.now().toString(16)}`; + try { + fs.renameSync(args.markerPath, quarantinePath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + + if (markerRecordMatchesCurrentTimer(readTimerMarker(quarantinePath), args)) { + fs.unlinkSync(quarantinePath); + return true; + } + + // We moved a replacement marker, not our authority record. Restore it only + // if no newer canonical marker exists; link cannot overwrite a concurrent + // timer generation. + try { + fs.linkSync(quarantinePath, args.markerPath); + fs.unlinkSync(quarantinePath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + // Preserve the quarantined record for explicit inspection rather than + // deleting either timer generation. + } + return false; +} + function resolveLockAgentConfig(): LockAgentConfig { // The timer is a detached child process that must never mark shields up // unless it can call the lock verifier. Guard the CommonJS export boundary @@ -132,28 +215,27 @@ function resolveLockAgentConfig(): LockAgentConfig { } function markerMatchesCurrentTimer(args: TimerArgs): boolean { - const marker = readTimerMarker(args.markerPath); - if (!marker) return false; - - const markerPid = marker.pid; - const markerSandboxName = marker.sandboxName; - const markerSnapshotPath = marker.snapshotPath; - const markerRestoreAt = marker.restoreAt; - const markerProcessToken = marker.processToken; + return markerRecordMatchesCurrentTimer(readTimerMarker(args.markerPath), args); +} +function rebuildLeaseOwnerIsCurrent(args: TimerArgs): boolean { + if (!args.leaseOwnerPid || !args.leaseOwnerStartIdentity) return false; return ( - markerPid === process.pid && - markerSandboxName === args.sandboxName && - markerSnapshotPath === args.snapshotPath && - markerRestoreAt === args.restoreAtIso && - markerProcessToken === args.processToken + isProcessAlive(args.leaseOwnerPid) && + readProcessStartIdentity(args.leaseOwnerPid) === args.leaseOwnerStartIdentity ); } function runRestoreTimer(args: TimerArgs): void { const now = new Date().toISOString(); let exitCode = 0; - let ownedMarker = false; + let retryScheduled = false; + const scheduleRetry = (): boolean => { + if (!markerMatchesCurrentTimer(args)) return false; + retryScheduled = true; + setTimeout(() => runRestoreTimer(args), AUTO_RESTORE_RETRY_MS); + return true; + }; try { // Timer markers are the source of authority. If the marker was removed or @@ -162,159 +244,210 @@ function runRestoreTimer(args: TimerArgs): void { if (!markerMatchesCurrentTimer(args)) { return; } - ownedMarker = true; - - if (!fs.existsSync(args.snapshotPath)) { - appendAudit({ - action: "shields_up_failed", - sandbox: args.sandboxName, - timestamp: now, - restored_by: "auto_timer", - error: "Policy snapshot file missing", - }); - exitCode = 1; + + // A rebuild can legitimately span the nominal 30-minute deadline while + // its old sandbox is deleted and the replacement is still being created. + // Bind that extension to the exact host PID/start identity. If the rebuild + // dies, the lease expires immediately and this same detached owner keeps + // retrying until it can restore the named sandbox. + if (rebuildLeaseOwnerIsCurrent(args)) { + scheduleRetry(); return; } - // Restore policy (slow — openshell policy set --wait blocks) - const result = run(buildPolicySetCommand(args.snapshotPath, args.sandboxName), { - ignoreError: true, - }); - const status = typeof result.status === "number" ? result.status : 1; - - if (status !== 0) { - appendAudit({ - action: "shields_up_failed", - sandbox: args.sandboxName, - timestamp: now, - restored_by: "auto_timer", - error: `Policy restore exited with status ${String(status)}`, - }); - exitCode = 1; - return; + if (!args.processToken || !/^[0-9a-f]{32}$/.test(args.processToken)) { + throw new Error("Auto-restore timer has no valid transition takeover token"); } + shields.prepareAutoRestoreTransitionTakeover( + args.sandboxName, + args.processToken, + args.snapshotPath, + ); - // Re-lock config file using the shared lockAgentConfig from shields.ts. - // lockAgentConfig runs each operation independently and verifies the - // on-disk state — it throws if verification fails. - // - // NC-2227-03: Resolve the full agent config target (including sensitive - // files like .config-hash, .env) so the timer re-locks the same scope - // that interactive `shields up` uses. Fall back to the bare configPath/ - // configDir from argv if resolution fails (e.g., registry unavailable). - let lockVerified = true; - let lockedChattr: boolean | null = null; - let lockedHashes: { [path: string]: string } | null = null; - if (args.configPath) { - let lockTarget: { - agentName?: string; - configPath: string; - configDir: string; - sensitiveFiles?: string[]; - } | null = null; - try { - // Always prefer the resolved target — even DEFAULT_AGENT_CONFIG - // carries the OpenClaw sensitiveFiles (.config-hash) that - // shields-up locks and that the content seal hashes. Dropping - // them here would persist a partial fileHashes map and the next - // `shields status` would flag the missing entries as drift. - lockTarget = resolveAgentConfig(args.sandboxName); - } catch { - // Resolver itself threw (registry unavailable). Fall back to - // argv-supplied paths, but still infer sensitiveFiles from - // configDir so the locked set matches what shields-up uses. - if (args.configDir) { - lockTarget = { - configPath: args.configPath, - configDir: args.configDir, - sensitiveFiles: [`${args.configDir}/.config-hash`], - }; - } else { - lockVerified = false; + withShieldsTransitionLock( + args.sandboxName, + "shields auto-restore", + () => { + // A manual hardening command may have completed while this timer waited + // for the host mutation lock. The marker is the timer's authority, so + // re-check it only after serialization is established. + if (!markerMatchesCurrentTimer(args)) return; + + if (!fs.existsSync(args.snapshotPath)) { appendAudit({ - action: "shields_auto_restore_lock_warning", + action: "shields_up_failed", sandbox: args.sandboxName, timestamp: now, restored_by: "auto_timer", - warning: "Missing config directory for auto-restore re-lock verification", - lock_verified: false, + error: "Policy snapshot file missing", }); + exitCode = 1; + scheduleRetry(); + return; } - } - if (lockTarget) { - try { - const lockAgentConfig = resolveLockAgentConfig(); - // #4663: a single instantaneous lock+verify cannot prove an - // in-sandbox reconciler didn't re-permission .config-hash after the - // verified lock returned. Re-confirm the lock held once the gateway - // has settled, re-applying if it drifted. This narrows (does not - // close) the revert window; fail closed (leave shields DOWN + audit) - // when the lock will not re-confirm within the retry budget. - const relock = relockAndReconfirm(() => lockAgentConfig(args.sandboxName, lockTarget)); - if (relock.ok && relock.lastResult) { - lockedChattr = relock.lastResult.chattrApplied; - lockedHashes = relock.lastResult.fileHashes; - } else { - lockVerified = false; - appendAudit({ - action: "shields_auto_restore_lock_warning", - sandbox: args.sandboxName, - timestamp: now, - restored_by: "auto_timer", - warning: relock.error ?? "Config re-lock did not re-confirm after settle window", - lock_verified: false, - }); - } - } catch (error: unknown) { - lockVerified = false; + + // Restore policy (slow — openshell policy set --wait blocks) + const result = run(buildPolicySetCommand(args.snapshotPath, args.sandboxName), { + ignoreError: true, + }); + const status = typeof result.status === "number" ? result.status : 1; + + if (status !== 0) { appendAudit({ - action: "shields_auto_restore_lock_warning", + action: "shields_up_failed", sandbox: args.sandboxName, timestamp: now, restored_by: "auto_timer", - warning: error instanceof Error ? error.message : String(error), - lock_verified: false, + error: `Policy restore exited with status ${String(status)}`, }); + exitCode = 1; + scheduleRetry(); + return; } - } - } - // Only mark shields as UP if the lock was verified (or no config path). - if (lockVerified) { - const patch: ShieldsStatePatch = { - shieldsDown: false, - shieldsDownAt: null, - shieldsDownTimeout: null, - shieldsDownReason: null, - shieldsDownPolicy: null, - }; - if (lockedChattr !== null) patch.chattrApplied = lockedChattr; - if (lockedHashes !== null) patch.fileHashes = lockedHashes; - updateState(args.stateFile, patch); - - appendAudit({ - action: "shields_auto_restore", - sandbox: args.sandboxName, - timestamp: now, - restored_by: "auto_timer", - policy_snapshot: args.snapshotPath, - scheduled_restore_at: args.restoreAtIso, - }); - return; - } + // Destroy and force-restore can revoke this marker while a slow + // policy restore is already in flight. Stop before the next sandbox + // mutation if this timer generation no longer owns recovery. + if (!markerMatchesCurrentTimer(args)) return; - // Explicitly ensure state reflects shields are still DOWN. - // shieldsDown() already wrote shieldsDown: true, but be explicit rather - // than relying on the absence of an update. - updateState(args.stateFile, { shieldsDown: true }); - appendAudit({ - action: "shields_up_failed", - sandbox: args.sandboxName, - timestamp: now, - restored_by: "auto_timer", - error: "Config re-lock verification failed — shields remain DOWN", - }); - exitCode = 1; + // Re-lock config file using the shared lockAgentConfig from shields.ts. + // lockAgentConfig runs each operation independently and verifies the + // on-disk state — it throws if verification fails. + // + // NC-2227-03: Resolve the full agent config target (including sensitive + // files like .config-hash, .env) so the timer re-locks the same scope + // that interactive `shields up` uses. Fall back to the bare configPath/ + // configDir from argv if resolution fails (e.g., registry unavailable). + let lockVerified = true; + let lockedChattr: boolean | null = null; + let lockedHashes: { [path: string]: string } | null = null; + if (args.configPath) { + let lockTarget: { + agentName?: string; + configPath: string; + configDir: string; + sensitiveFiles?: string[]; + } | null = null; + try { + // Always prefer the resolved target — even DEFAULT_AGENT_CONFIG + // carries the OpenClaw sensitiveFiles (.config-hash) that + // shields-up locks and that the content seal hashes. Dropping + // them here would persist a partial fileHashes map and the next + // `shields status` would flag the missing entries as drift. + lockTarget = resolveAgentConfig(args.sandboxName); + } catch { + // Resolver itself threw (registry unavailable). Fall back to + // argv-supplied paths, but still infer sensitiveFiles from + // configDir so the locked set matches what shields-up uses. + if (args.configDir) { + lockTarget = { + configPath: args.configPath, + configDir: args.configDir, + sensitiveFiles: [`${args.configDir}/.config-hash`], + }; + } else { + lockVerified = false; + appendAudit({ + action: "shields_auto_restore_lock_warning", + sandbox: args.sandboxName, + timestamp: now, + restored_by: "auto_timer", + warning: "Missing config directory for auto-restore re-lock verification", + lock_verified: false, + }); + } + } + if (lockTarget) { + try { + if (!markerMatchesCurrentTimer(args)) return; + const lockAgentConfig = resolveLockAgentConfig(); + // #4663: a single instantaneous lock+verify cannot prove an + // in-sandbox reconciler didn't re-permission .config-hash after the + // verified lock returned. Re-confirm the lock held once the gateway + // has settled, re-applying if it drifted. This narrows (does not + // close) the revert window; fail closed (leave shields DOWN + audit) + // when the lock will not re-confirm within the retry budget. + const relock = relockAndReconfirm(() => + lockAgentConfig( + args.sandboxName, + lockTarget, + false, + args.allowLegacyHermesProtocol, + ), + ); + if (relock.ok && relock.lastResult) { + lockedChattr = relock.lastResult.chattrApplied; + lockedHashes = relock.lastResult.fileHashes; + } else { + lockVerified = false; + appendAudit({ + action: "shields_auto_restore_lock_warning", + sandbox: args.sandboxName, + timestamp: now, + restored_by: "auto_timer", + warning: relock.error ?? "Config re-lock did not re-confirm after settle window", + lock_verified: false, + }); + } + } catch (error: unknown) { + lockVerified = false; + appendAudit({ + action: "shields_auto_restore_lock_warning", + sandbox: args.sandboxName, + timestamp: now, + restored_by: "auto_timer", + warning: error instanceof Error ? error.message : String(error), + lock_verified: false, + }); + } + } + } + + // Re-lock verification includes a settle window. Do not rewrite state + // or remove a replacement marker if authority changed while it ran. + if (!markerMatchesCurrentTimer(args)) return; + + // Only mark shields as UP if the lock was verified (or no config path). + if (lockVerified) { + const patch: ShieldsStatePatch = { + shieldsDown: false, + shieldsDownAt: null, + shieldsDownTimeout: null, + shieldsDownReason: null, + shieldsDownPolicy: null, + }; + if (lockedChattr !== null) patch.chattrApplied = lockedChattr; + if (lockedHashes !== null) patch.fileHashes = lockedHashes; + updateState(args.stateFile, patch); + + appendAudit({ + action: "shields_auto_restore", + sandbox: args.sandboxName, + timestamp: now, + restored_by: "auto_timer", + policy_snapshot: args.snapshotPath, + scheduled_restore_at: args.restoreAtIso, + }); + cleanupOwnedTimerMarker(args); + return; + } + + // Explicitly ensure state reflects shields are still DOWN. + // shieldsDown() already wrote shieldsDown: true, but be explicit rather + // than relying on the absence of an update. + updateState(args.stateFile, { shieldsDown: true }); + appendAudit({ + action: "shields_up_failed", + sandbox: args.sandboxName, + timestamp: now, + restored_by: "auto_timer", + error: "Config re-lock verification failed — shields remain DOWN", + }); + exitCode = 1; + scheduleRetry(); + }, + { takeoverToken: args.processToken }, + ); } catch (error: unknown) { appendAudit({ action: "shields_up_failed", @@ -324,11 +457,9 @@ function runRestoreTimer(args: TimerArgs): void { error: error instanceof Error ? error.message : String(error), }); exitCode = 1; + scheduleRetry(); } finally { - if (ownedMarker && markerMatchesCurrentTimer(args)) { - cleanupMarker(args.markerPath); - } - process.exit(exitCode); + if (!retryScheduled) process.exit(exitCode); } } @@ -338,13 +469,42 @@ function main(): void { process.exit(1); } - setTimeout(() => { - runRestoreTimer(args); - }, args.delayMs); + let scheduled = false; + const authorize = (): void => { + if (scheduled || !markerMatchesCurrentTimer(args)) return; + scheduled = true; + setTimeout( + () => { + runRestoreTimer(args); + }, + Math.max(0, args.restoreAtMs - Date.now()), + ); + }; + + // The parent publishes the PID/token marker before authorizing this child. + // Without this barrier a short timeout can fire in the fork-to-marker gap, + // causing the child to exit before the parent records a now-dead timer PID. + process.on("message", (message: unknown) => { + if ( + typeof message === "object" && + message !== null && + (message as { type?: unknown }).type === "authorize" && + (message as { processToken?: unknown }).processToken === args.processToken + ) { + authorize(); + } + }); + process.once("disconnect", authorize); } if (require.main === module) { main(); } -export { markerMatchesCurrentTimer, parseTimerArgs, readTimerMarker, runRestoreTimer }; +export { + cleanupOwnedTimerMarker, + markerMatchesCurrentTimer, + parseTimerArgs, + readTimerMarker, + runRestoreTimer, +}; diff --git a/src/lib/shields/transition-lock.test.ts b/src/lib/shields/transition-lock.test.ts new file mode 100644 index 00000000000..5ee01b7803e --- /dev/null +++ b/src/lib/shields/transition-lock.test.ts @@ -0,0 +1,671 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + ShieldsTransitionLockManager, + type ShieldsTransitionLockOwner, + shieldsTransitionLockPath, +} from "./transition-lock"; + +const SELF_PID = 101; +const SELF_IDENTITY = "proc:self-start"; +const TAKEOVER_TOKEN = "a".repeat(32); +const OTHER_TAKEOVER_TOKEN = "b".repeat(32); + +function runWhen(condition: boolean, action: () => void): void { + condition && action(); +} + +function readLockFileSnapshot(lockPath: string) { + const fd = fs.openSync( + lockPath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + try { + const stat = fs.fstatSync(fd, { bigint: true }); + expect(stat.isFile(), `expected a regular lock file at '${lockPath}'`).toBe(true); + return { + contents: fs.readFileSync(fd, "utf8"), + inode: stat.ino, + mode: stat.mode & 0o777n, + mtimeMs: Number(stat.mtimeMs), + }; + } finally { + fs.closeSync(fd); + } +} + +function owner( + sandboxName: string, + pid: number, + processStartIdentity: string, + command = "nemoclaw sandbox shields up", + takeoverToken?: string, +): ShieldsTransitionLockOwner { + return { + version: 1, + sandboxName, + pid, + processStartIdentity, + command, + acquiredAtMs: 1_000, + ...(takeoverToken ? { takeoverToken } : {}), + }; +} + +describe("host shields transition lock", () => { + let root: string; + let stateDir: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-transition-lock-")); + stateDir = path.join(root, "state"); + fs.mkdirSync(stateDir, { recursive: true }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + function manager( + overrides: Partial[0]> = {}, + ): ShieldsTransitionLockManager { + return new ShieldsTransitionLockManager({ + stateDir, + pid: SELF_PID, + now: () => 2_000, + sleep: () => {}, + isProcessAlive: (pid) => pid === SELF_PID, + readProcessStartIdentity: (pid) => (pid === SELF_PID ? SELF_IDENTITY : null), + ...overrides, + }); + } + + function writeOwner(sandboxName: string, value: ShieldsTransitionLockOwner | string): string { + const lockPath = shieldsTransitionLockPath(sandboxName, stateDir); + fs.writeFileSync(lockPath, typeof value === "string" ? value : JSON.stringify(value), { + mode: 0o600, + }); + return lockPath; + } + + it("atomically creates a regular owner file and removes it after the callback", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + const originalLinkSync = fs.linkSync; + let completeBeforePublish = false; + vi.spyOn(fs, "linkSync").mockImplementation((source, destination) => { + expect(String(destination)).toBe(lockPath); + expect(String(source)).not.toBe(lockPath); + expect(JSON.parse(fs.readFileSync(source, "utf8"))).toMatchObject({ + sandboxName: "alpha", + pid: SELF_PID, + processStartIdentity: SELF_IDENTITY, + }); + completeBeforePublish = true; + originalLinkSync(source, destination); + }); + + const result = locker.withShieldsTransitionLock("alpha", "nemoclaw alpha shields up", () => { + const snapshot = readLockFileSnapshot(lockPath); + const written = JSON.parse(snapshot.contents); + expect(snapshot.mode).toBe(0o600n); + expect(written).toEqual({ + version: 1, + sandboxName: "alpha", + pid: SELF_PID, + processStartIdentity: SELF_IDENTITY, + command: "nemoclaw alpha shields up", + acquiredAtMs: 2_000, + }); + return "complete"; + }); + + expect(result).toBe("complete"); + expect(completeBeforePublish).toBe(true); + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("never publishes a canonical owner when atomic link publication fails", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + vi.spyOn(fs, "linkSync").mockImplementation(() => { + const error = new Error("injected publication failure") as NodeJS.ErrnoException; + error.code = "EIO"; + throw error; + }); + + expect(() => + locker.withShieldsTransitionLock("alpha", "nemoclaw alpha shields down", () => undefined), + ).toThrow(/injected publication failure/); + expect(fs.existsSync(lockPath)).toBe(false); + expect(fs.readdirSync(stateDir)).toEqual([]); + }); + + it("defers process.exit until after the canonical lock is released", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + const exitError = new Error("captured real exit"); + const exit = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + expect(code).toBe(7); + expect(fs.existsSync(lockPath)).toBe(false); + throw exitError; + }) as never); + + expect(() => + locker.withShieldsTransitionLock("alpha", "failing policy command", () => { + process.exit(7); + }), + ).toThrow(exitError); + expect(exit).toHaveBeenCalledTimes(1); + }); + + it("persists an optional authorized takeover token", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + + locker.withShieldsTransitionLock( + "alpha", + "nemoclaw alpha shields down", + () => { + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toMatchObject({ + pid: SELF_PID, + processStartIdentity: SELF_IDENTITY, + takeoverToken: TAKEOVER_TOKEN, + }); + }, + { takeoverToken: TAKEOVER_TOKEN }, + ); + }); + + it("inspects owner identity only for the matching takeover token", () => { + const locker = manager(); + writeOwner("alpha", owner("alpha", 202, "proc:holder", "shields down", TAKEOVER_TOKEN)); + + expect(locker.inspectShieldsTransitionLockOwner("alpha", OTHER_TAKEOVER_TOKEN)).toBeNull(); + expect(locker.inspectShieldsTransitionLockOwner("alpha", TAKEOVER_TOKEN)).toEqual({ + pid: 202, + processStartIdentity: "proc:holder", + command: "shields down", + }); + }); + + it("returns no inspected owner when the canonical path changes identity before open", () => { + const locker = manager(); + const original = owner("alpha", 202, "proc:original", "original", TAKEOVER_TOKEN); + const replacement = owner("alpha", 303, "proc:replacement", "replacement", TAKEOVER_TOKEN); + const lockPath = writeOwner("alpha", original); + const displacedPath = `${lockPath}.displaced`; + const originalOpenSync = fs.openSync; + let swapped = false; + vi.spyOn(fs, "openSync").mockImplementation(((file, flags, mode) => { + runWhen(String(file) === lockPath && !swapped, () => { + swapped = true; + fs.renameSync(lockPath, displacedPath); + fs.writeFileSync(lockPath, JSON.stringify(replacement), { mode: 0o600 }); + }); + return originalOpenSync(file, flags, mode); + }) as typeof fs.openSync); + + expect(locker.inspectShieldsTransitionLockOwner("alpha", TAKEOVER_TOKEN)).toBeNull(); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(replacement); + expect(JSON.parse(fs.readFileSync(displacedPath, "utf8"))).toEqual(original); + }); + + it("rejects takeover with the wrong token without moving the owner", () => { + const recorded = owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN); + const lockPath = writeOwner("alpha", recorded); + const result = manager().takeoverShieldsTransitionLock( + "alpha", + 202, + "proc:owner", + OTHER_TAKEOVER_TOKEN, + ); + + expect(result).toEqual({ removed: false, reason: "owner-mismatch" }); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(recorded); + }); + + it("rejects takeover while the exact owner process is still live", () => { + const recorded = owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN); + const lockPath = writeOwner("alpha", recorded); + const locker = manager({ + isProcessAlive: (pid) => pid === SELF_PID || pid === 202, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === 202 ? "proc:owner" : null, + }); + + expect( + locker.takeoverShieldsTransitionLock("alpha", 202, "proc:owner", TAKEOVER_TOKEN), + ).toEqual({ removed: false, reason: "owner-live" }); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(recorded); + }); + + it("rejects a mismatched expected identity even when the PID was reused", () => { + const recorded = owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN); + const lockPath = writeOwner("alpha", recorded); + const locker = manager({ + isProcessAlive: (pid) => pid === SELF_PID || pid === 202, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === 202 ? "proc:reused" : null, + }); + + expect( + locker.takeoverShieldsTransitionLock("alpha", 202, "proc:not-owner", TAKEOVER_TOKEN), + ).toEqual({ removed: false, reason: "owner-mismatch" }); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(recorded); + }); + + it("removes the exact token-authorized lock after its owner dies", () => { + const lockPath = writeOwner( + "alpha", + owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN), + ); + + expect( + manager().takeoverShieldsTransitionLock("alpha", 202, "proc:owner", TAKEOVER_TOKEN), + ).toEqual({ removed: true, reason: "removed-dead-owner" }); + expect(fs.existsSync(lockPath)).toBe(false); + expect(fs.readdirSync(stateDir)).toEqual([]); + }); + + it("removes the exact token-authorized lock after its PID is reused", () => { + const lockPath = writeOwner( + "alpha", + owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN), + ); + const locker = manager({ + isProcessAlive: (pid) => pid === SELF_PID || pid === 202, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === 202 ? "proc:reused" : null, + }); + + expect( + locker.takeoverShieldsTransitionLock("alpha", 202, "proc:owner", TAKEOVER_TOKEN), + ).toEqual({ removed: true, reason: "removed-reused-pid" }); + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("preserves a replacement raced into the token-specific quarantine", () => { + const original = owner("alpha", 202, "proc:owner", "shields down", TAKEOVER_TOKEN); + const replacement = owner( + "alpha", + 303, + "proc:replacement", + "replacement owner", + TAKEOVER_TOKEN, + ); + const lockPath = writeOwner("alpha", original); + const displacedPath = `${lockPath}.displaced`; + const originalRenameSync = fs.renameSync; + let raced = false; + vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + runWhen(String(source) === lockPath && !raced, () => { + raced = true; + originalRenameSync(lockPath, displacedPath); + fs.writeFileSync(lockPath, JSON.stringify(replacement), { mode: 0o600 }); + }); + originalRenameSync(source, destination); + }); + const locker = manager({ + isProcessAlive: (pid) => pid === SELF_PID || pid === 303, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === 303 ? "proc:replacement" : null, + }); + + const result = locker.takeoverShieldsTransitionLock("alpha", 202, "proc:owner", TAKEOVER_TOKEN); + + expect(result).toMatchObject({ removed: false, reason: "replacement-preserved" }); + expect(result.quarantinePath).toContain(`.takeover-${TAKEOVER_TOKEN}-`); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(replacement); + expect(JSON.parse(fs.readFileSync(result.quarantinePath!, "utf8"))).toEqual(replacement); + expect(JSON.parse(fs.readFileSync(displacedPath, "utf8"))).toEqual(original); + }); + + it("waits for a live holder with the same process identity", () => { + const holderPid = 202; + const holderIdentity = "proc:holder-start"; + const lockPath = writeOwner("alpha", owner("alpha", holderPid, holderIdentity)); + let nowMs = 2_000; + let sleepCalls = 0; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + sleepCalls += 1; + nowMs += milliseconds; + fs.unlinkSync(lockPath); + }, + isProcessAlive: (pid) => pid === holderPid || pid === SELF_PID, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === holderPid ? holderIdentity : null, + }); + + expect( + locker.withShieldsTransitionLock("alpha", "nemoclaw alpha shields down", () => "acquired", { + waitTimeoutMs: 10, + pollIntervalMs: 1, + }), + ).toBe("acquired"); + expect(sleepCalls).toBe(1); + }); + + it("times out without reclaiming a live holder whose identity cannot be read", () => { + const holderPid = 202; + const lockPath = writeOwner("alpha", owner("alpha", holderPid, "proc:holder-start")); + let nowMs = 2_000; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + nowMs += milliseconds; + }, + isProcessAlive: (pid) => pid === holderPid || pid === SELF_PID, + }); + + expect(() => + locker.withShieldsTransitionLock("alpha", "timer restore", () => undefined, { + waitTimeoutMs: 3, + pollIntervalMs: 1, + }), + ).toThrow(/PID 202 is alive but its process-start identity cannot be verified/); + expect(fs.existsSync(lockPath)).toBe(true); + }); + + it("fails closed with recovery guidance when the recorded holder is dead", () => { + const recorded = owner("alpha", 202, "proc:dead-holder"); + const lockPath = writeOwner("alpha", recorded); + const liveness = vi.fn((pid: number) => pid === SELF_PID); + let nowMs = 2_000; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + nowMs += milliseconds; + }, + isProcessAlive: liveness, + }); + const unlink = vi.spyOn(fs, "unlinkSync"); + + expect(() => + locker.withShieldsTransitionLock("alpha", "nemoclaw alpha shields up", () => undefined, { + waitTimeoutMs: 2, + pollIntervalMs: 1, + }), + ).toThrow(/will not remove a stale lock pathname automatically.*remove '.*' manually/s); + + expect(liveness).toHaveBeenCalledWith(202); + expect(unlink).not.toHaveBeenCalledWith(lockPath); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(recorded); + }); + + it("fails closed with recovery guidance when a live PID has been reused", () => { + const holderPid = 202; + const recorded = owner("alpha", holderPid, "proc:original"); + const lockPath = writeOwner("alpha", recorded); + let nowMs = 2_000; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + nowMs += milliseconds; + }, + isProcessAlive: (pid) => pid === holderPid || pid === SELF_PID, + readProcessStartIdentity: (pid) => + pid === SELF_PID ? SELF_IDENTITY : pid === holderPid ? "proc:reused" : null, + }); + + expect(() => + locker.withShieldsTransitionLock("alpha", "timer restore", () => undefined, { + waitTimeoutMs: 2, + pollIntervalMs: 1, + }), + ).toThrow(/now has process-start identity 'proc:reused'.*remove '.*' manually/s); + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(recorded); + }); + + it("waits on a recent malformed owner record", () => { + const lockPath = writeOwner("alpha", "{incomplete"); + const initialSnapshot = readLockFileSnapshot(lockPath); + let nowMs = initialSnapshot.mtimeMs + 5; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + nowMs += milliseconds; + }, + }); + + expect(() => + locker.withShieldsTransitionLock("alpha", "timer restore", () => undefined, { + waitTimeoutMs: 3, + pollIntervalMs: 1, + malformedStaleMs: 30_000, + }), + ).toThrow(/owner record is incomplete/); + const finalSnapshot = readLockFileSnapshot(lockPath); + expect(finalSnapshot.inode).toBe(initialSnapshot.inode); + expect(finalSnapshot.contents).toBe("{incomplete"); + }); + + it("fails closed with manual recovery guidance for an old malformed owner record", () => { + const lockPath = writeOwner("alpha", "{incomplete"); + fs.utimesSync(lockPath, new Date(1_000), new Date(1_000)); + let nowMs = 60_000; + const locker = manager({ + now: () => nowMs, + sleep: (milliseconds) => { + nowMs += milliseconds; + }, + }); + + expect(() => + locker.withShieldsTransitionLock("alpha", "nemoclaw alpha shields up", () => undefined, { + waitTimeoutMs: 2, + pollIntervalMs: 1, + malformedStaleMs: 30_000, + }), + ).toThrow(/owner record is incomplete.*will not remove.*remove '.*' manually/s); + expect(fs.readFileSync(lockPath, "utf8")).toBe("{incomplete"); + }); + + it("rejects symbolic-link and non-regular lock paths", () => { + const target = path.join(root, "target"); + fs.writeFileSync(target, "{}", { mode: 0o600 }); + const symlinkPath = shieldsTransitionLockPath("symlinked", stateDir); + fs.symlinkSync(target, symlinkPath); + const directoryPath = shieldsTransitionLockPath("directory", stateDir); + fs.mkdirSync(directoryPath); + const locker = manager(); + + expect(() => + locker.withShieldsTransitionLock("symlinked", "shields up", () => undefined), + ).toThrow(/symbolic links are not allowed/); + expect(() => + locker.withShieldsTransitionLock("directory", "shields up", () => undefined), + ).toThrow(/path is not a regular file/); + }); + + it("keeps one inode across reentrant calls and releases only at depth zero", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + + locker.withShieldsTransitionLock("alpha", "outer transition", () => { + const outerSnapshot = readLockFileSnapshot(lockPath); + locker.withShieldsTransitionLock("alpha", "inner transition", () => { + const innerSnapshot = readLockFileSnapshot(lockPath); + expect(innerSnapshot.inode).toBe(outerSnapshot.inode); + expect(JSON.parse(innerSnapshot.contents).command).toBe("outer transition"); + }); + expect(fs.existsSync(lockPath)).toBe(true); + }); + + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("uses independent lock files for different sandboxes", () => { + const locker = manager(); + const alphaPath = shieldsTransitionLockPath("alpha", stateDir); + const betaPath = shieldsTransitionLockPath("beta", stateDir); + + locker.withShieldsTransitionLock("alpha", "alpha transition", () => { + locker.withShieldsTransitionLock("beta", "beta transition", () => { + expect(fs.existsSync(alphaPath)).toBe(true); + expect(fs.existsSync(betaPath)).toBe(true); + }); + expect(fs.existsSync(alphaPath)).toBe(true); + expect(fs.existsSync(betaPath)).toBe(false); + }); + + expect(fs.existsSync(alphaPath)).toBe(false); + }); + + it("uses the held descriptor to avoid removing a replacement during release", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + const displacedPath = `${lockPath}.displaced`; + const replacement = owner("alpha", 303, "proc:replacement", "replacement holder"); + + locker.withShieldsTransitionLock("alpha", "outer transition", () => { + fs.renameSync(lockPath, displacedPath); + fs.writeFileSync(lockPath, JSON.stringify(replacement), { mode: 0o600 }); + }); + + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(replacement); + expect(fs.existsSync(displacedPath)).toBe(true); + }); + + it("preserves a replacement installed at the exact release rename boundary", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + const displacedPath = `${lockPath}.original`; + const replacement = owner("alpha", 303, "proc:replacement", "replacement holder"); + const originalRename = fs.renameSync.bind(fs); + let armRace = false; + vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + runWhen( + armRace && String(source) === lockPath && String(destination).includes(".release-"), + () => { + armRace = false; + originalRename(lockPath, displacedPath); + fs.writeFileSync(lockPath, JSON.stringify(replacement), { mode: 0o600 }); + }, + ); + return originalRename(source, destination); + }); + + locker.withShieldsTransitionLock("alpha", "outer transition", () => { + armRace = true; + }); + + expect(JSON.parse(fs.readFileSync(lockPath, "utf8"))).toEqual(replacement); + expect(fs.existsSync(displacedPath)).toBe(true); + const quarantines = fs + .readdirSync(stateDir) + .filter((name) => name.startsWith(`${path.basename(lockPath)}.release-`)); + expect(quarantines).toHaveLength(1); + }); + + it("releases the lock when the protected callback throws", () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + + expect(() => + locker.withShieldsTransitionLock("alpha", "shields up", () => { + throw new Error("transition failed"); + }), + ).toThrow("transition failed"); + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("holds the lock across an asynchronous callback and releases after settlement", async () => { + const locker = manager(); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + let releaseCallback: (() => void) | undefined; + const pending = locker.withShieldsTransitionLockAsync( + "alpha", + "async config mutation", + async () => { + expect(fs.existsSync(lockPath)).toBe(true); + await new Promise((resolve) => { + releaseCallback = resolve; + }); + expect(fs.existsSync(lockPath)).toBe(true); + return "complete"; + }, + ); + + await vi.waitFor(() => expect(releaseCallback).toBeTypeOf("function")); + expect(fs.existsSync(lockPath)).toBe(true); + releaseCallback?.(); + await expect(pending).resolves.toBe("complete"); + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("allows reentrancy only inside the owning asynchronous chain", async () => { + const sleepAsync = vi.fn(async () => {}); + const locker = manager({ sleepAsync }); + const lockPath = shieldsTransitionLockPath("alpha", stateDir); + + await expect( + locker.withShieldsTransitionLockAsync("alpha", "outer async transition", async () => { + const outerSnapshot = readLockFileSnapshot(lockPath); + await Promise.resolve(); + await locker.withShieldsTransitionLockAsync("alpha", "inner async transition", async () => { + const innerSnapshot = readLockFileSnapshot(lockPath); + expect(innerSnapshot.inode).toBe(outerSnapshot.inode); + expect(JSON.parse(innerSnapshot.contents).command).toBe("outer async transition"); + }); + expect(fs.existsSync(lockPath)).toBe(true); + }), + ).resolves.toBeUndefined(); + + expect(sleepAsync).not.toHaveBeenCalled(); + expect(fs.existsSync(lockPath)).toBe(false); + }); + + it("serializes unrelated concurrent async calls in the same process", async () => { + let nowMs = 2_000; + let releaseFirst: (() => void) | undefined; + const events: string[] = []; + const locker = manager({ + now: () => nowMs, + sleepAsync: async (milliseconds) => { + nowMs += milliseconds; + const release = releaseFirst; + releaseFirst = undefined; + release?.(); + await Promise.resolve(); + }, + }); + + const first = locker.withShieldsTransitionLockAsync( + "alpha", + "first async transition", + async () => { + events.push("first-enter"); + await new Promise((resolve) => { + releaseFirst = resolve; + }); + events.push("first-exit"); + return "first"; + }, + ); + await vi.waitFor(() => expect(releaseFirst).toBeTypeOf("function")); + + const second = locker.withShieldsTransitionLockAsync( + "alpha", + "second async transition", + async () => { + events.push("second-enter"); + return "second"; + }, + { waitTimeoutMs: 10, pollIntervalMs: 1 }, + ); + + await expect(Promise.all([first, second])).resolves.toEqual(["first", "second"]); + expect(events).toEqual(["first-enter", "first-exit", "second-enter"]); + }); +}); diff --git a/src/lib/shields/transition-lock.ts b/src/lib/shields/transition-lock.ts new file mode 100644 index 00000000000..c769eb6837c --- /dev/null +++ b/src/lib/shields/transition-lock.ts @@ -0,0 +1,916 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { AsyncLocalStorage } from "node:async_hooks"; +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { NAME_ALLOWED_FORMAT, NAME_MAX_LENGTH, NAME_VALID_PATTERN } from "../name-validation"; +import { resolveNemoclawStateDir } from "../state/paths"; +import { isProcessAlive, readProcessStartIdentity } from "./timer-control"; + +const LOCK_VERSION = 1; +const MAX_OWNER_BYTES = 16 * 1024; +const DEFAULT_WAIT_TIMEOUT_MS = 30_000; +const DEFAULT_POLL_INTERVAL_MS = 50; +const DEFAULT_MALFORMED_STALE_MS = 30_000; +const TAKEOVER_TOKEN_PATTERN = /^[0-9a-f]{32}$/; + +const waitBuffer = new Int32Array(new SharedArrayBuffer(4)); + +export interface ShieldsTransitionLockOwner { + version: 1; + sandboxName: string; + pid: number; + processStartIdentity: string; + command: string; + acquiredAtMs: number; + takeoverToken?: string; +} + +export interface ShieldsTransitionLockOptions { + waitTimeoutMs?: number; + pollIntervalMs?: number; + malformedStaleMs?: number; + takeoverToken?: string; +} + +export interface ShieldsTransitionLockDependencies { + stateDir?: string; + pid?: number; + now?: () => number; + sleep?: (milliseconds: number) => void; + sleepAsync?: (milliseconds: number) => Promise; + isProcessAlive?: (pid: number) => boolean; + readProcessStartIdentity?: (pid: number) => string | null; +} + +interface InodeIdentity { + dev: bigint; + ino: bigint; +} + +class DeferredTransitionProcessExit extends Error { + readonly exitCode: string | number | null | undefined; + + constructor(exitCode: string | number | null | undefined) { + super( + `process.exit(${String(exitCode ?? 0)}) requested while a shields transition lock is held`, + ); + this.name = "DeferredTransitionProcessExit"; + this.exitCode = exitCode; + } +} + +interface ExistingLockSnapshot { + fd: number; + identity: InodeIdentity; + mtimeMs: number; + owner: ShieldsTransitionLockOwner | null; +} + +interface HeldLock { + fd: number; + identity: InodeIdentity; + lockPath: string; + depth: number; + ownerToken: symbol; + owner: ShieldsTransitionLockOwner; +} + +interface AcquisitionState { + lockPath: string; + owner: ShieldsTransitionLockOwner; + startedAtMs: number; + waitTimeoutMs: number; + pollIntervalMs: number; + malformedStaleMs: number; +} + +type WaitReason = + | { kind: "live"; owner: ShieldsTransitionLockOwner } + | { kind: "same-process"; owner: ShieldsTransitionLockOwner } + | { kind: "identity-unavailable"; owner: ShieldsTransitionLockOwner } + | { kind: "recent-malformed"; ageMs: number } + | { kind: "stale-malformed"; ageMs: number } + | { kind: "dead"; owner: ShieldsTransitionLockOwner } + | { + kind: "pid-reused"; + owner: ShieldsTransitionLockOwner; + currentProcessStartIdentity: string; + }; + +export interface InspectedShieldsTransitionOwner { + pid: number; + processStartIdentity: string; + command: string; +} + +export type ShieldsTransitionTakeoverReason = + | "removed-dead-owner" + | "removed-reused-pid" + | "missing" + | "owner-mismatch" + | "owner-live" + | "owner-identity-unavailable" + | "path-changed" + | "replacement-preserved"; + +export interface ShieldsTransitionTakeoverResult { + removed: boolean; + reason: ShieldsTransitionTakeoverReason; + quarantinePath?: string; +} + +function isErrnoException(error: unknown): error is NodeJS.ErrnoException { + return error instanceof Error && "code" in error; +} + +function inodeIdentity(stat: fs.BigIntStats): InodeIdentity { + return { dev: stat.dev, ino: stat.ino }; +} + +function sameInode(left: InodeIdentity, right: InodeIdentity): boolean { + return left.dev === right.dev && left.ino === right.ino; +} + +function requireNonNegativeFinite(value: number, label: string): number { + if (!Number.isFinite(value) || value < 0) { + throw new Error(`${label} must be a non-negative finite number`); + } + return value; +} + +function requireTakeoverToken(token: string, label = "takeoverToken"): string { + if (!TAKEOVER_TOKEN_PATTERN.test(token)) { + throw new Error(`${label} must be exactly 32 lowercase hexadecimal characters`); + } + return token; +} + +function optionalTakeoverToken(token: string | undefined): string | undefined { + return token === undefined ? undefined : requireTakeoverToken(token); +} + +function validateSandboxName(name: string): string { + if (!name || typeof name !== "string") { + throw new Error(`sandbox name is required. Allowed format: ${NAME_ALLOWED_FORMAT}.`); + } + if (name.length > NAME_MAX_LENGTH) { + throw new Error( + `sandbox name too long (max ${String(NAME_MAX_LENGTH)} chars). Allowed format: ${NAME_ALLOWED_FORMAT}.`, + ); + } + if (!NAME_VALID_PATTERN.test(name)) { + throw new Error(`Invalid sandbox name: '${name}'. Allowed format: ${NAME_ALLOWED_FORMAT}.`); + } + return name; +} + +function parseOwner(raw: string, sandboxName: string): ShieldsTransitionLockOwner | null { + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return null; + } + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const owner = value as Record; + if ( + owner.version !== LOCK_VERSION || + owner.sandboxName !== sandboxName || + typeof owner.pid !== "number" || + !Number.isInteger(owner.pid) || + owner.pid <= 0 || + typeof owner.processStartIdentity !== "string" || + owner.processStartIdentity.length === 0 || + typeof owner.command !== "string" || + owner.command.length === 0 || + typeof owner.acquiredAtMs !== "number" || + !Number.isFinite(owner.acquiredAtMs) || + (owner.takeoverToken !== undefined && + (typeof owner.takeoverToken !== "string" || + !TAKEOVER_TOKEN_PATTERN.test(owner.takeoverToken))) + ) { + return null; + } + return owner as unknown as ShieldsTransitionLockOwner; +} + +function unsafeLockPathError(lockPath: string, reason: string): Error { + return new Error(`Unsafe shields transition lock '${lockPath}': ${reason}`); +} + +function readExistingLock(lockPath: string, sandboxName: string): ExistingLockSnapshot | null { + let pathStat: fs.BigIntStats; + try { + pathStat = fs.lstatSync(lockPath, { bigint: true }); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") return null; + throw error; + } + if (pathStat.isSymbolicLink()) { + throw unsafeLockPathError(lockPath, "symbolic links are not allowed"); + } + if (!pathStat.isFile()) { + throw unsafeLockPathError(lockPath, "path is not a regular file"); + } + + let fd: number; + try { + fd = fs.openSync( + lockPath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") return null; + if (isErrnoException(error) && error.code === "ELOOP") { + throw unsafeLockPathError(lockPath, "symbolic links are not allowed"); + } + throw error; + } + + try { + const fdStat = fs.fstatSync(fd, { bigint: true }); + if (!fdStat.isFile()) { + throw unsafeLockPathError(lockPath, "path is not a regular file"); + } + if (!sameInode(inodeIdentity(pathStat), inodeIdentity(fdStat))) { + fs.closeSync(fd); + return null; + } + + const buffer = Buffer.alloc(MAX_OWNER_BYTES + 1); + const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0); + const owner = + bytesRead > MAX_OWNER_BYTES + ? null + : parseOwner(buffer.subarray(0, bytesRead).toString("utf8"), sandboxName); + return { + fd, + identity: inodeIdentity(fdStat), + mtimeMs: Number(fdStat.mtimeMs), + owner, + }; + } catch (error) { + try { + fs.closeSync(fd); + } catch { + // Preserve the inspection error. + } + throw error; + } +} + +function closeSnapshot(snapshot: ExistingLockSnapshot): void { + try { + fs.closeSync(snapshot.fd); + } catch { + // The snapshot is advisory after inspection; there is nothing safe to clean up here. + } +} + +function defaultSleep(milliseconds: number): void { + Atomics.wait(waitBuffer, 0, 0, milliseconds); +} + +function defaultSleepAsync(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +function staleRecovery(lockPath: string): string { + return `NemoClaw will not remove a stale lock pathname automatically because another process could replace it after inspection. Verify that no shields transition is active, remove '${lockPath}' manually, and retry.`; +} + +function formatWaitReason(reason: WaitReason | null, lockPath: string): string { + if (!reason) return "the lock changed during inspection; retry the command"; + if (reason.kind === "recent-malformed") { + return `the owner record is incomplete and only ${Math.max(0, Math.floor(reason.ageMs))}ms old. Retry after the writer finishes`; + } + if (reason.kind === "stale-malformed") { + return `the owner record is incomplete and ${Math.max(0, Math.floor(reason.ageMs))}ms old. ${staleRecovery(lockPath)}`; + } + const owner = reason.owner; + if (reason.kind === "dead") { + return `recorded owner PID ${String(owner.pid)} is not running (${owner.command}). ${staleRecovery(lockPath)}`; + } + if (reason.kind === "pid-reused") { + return `recorded owner PID ${String(owner.pid)} now has process-start identity '${reason.currentProcessStartIdentity}' instead of '${owner.processStartIdentity}' (${owner.command}). ${staleRecovery(lockPath)}`; + } + if (reason.kind === "identity-unavailable") { + return `PID ${String(owner.pid)} is alive but its process-start identity cannot be verified (${owner.command}). Verify the active process and retry`; + } + if (reason.kind === "same-process") { + return `another async chain in this process still owns the lock (${owner.command}). Wait for that operation to finish and retry`; + } + return `PID ${String(owner.pid)} is still running (${owner.command}). Wait for that operation to finish and retry`; +} + +export function shieldsTransitionLockPath( + sandboxName: string, + stateDir: string = resolveNemoclawStateDir(), +): string { + const validName = validateSandboxName(sandboxName); + return path.join(stateDir, `shields-transition-lock-${validName}.json`); +} + +export class ShieldsTransitionLockManager { + private readonly stateDir: string; + private readonly pid: number; + private readonly now: () => number; + private readonly sleep: (milliseconds: number) => void; + private readonly sleepAsync: (milliseconds: number) => Promise; + private readonly processIsAlive: (pid: number) => boolean; + private readonly processStartIdentity: (pid: number) => string | null; + private readonly held = new Map(); + private readonly ownership = new AsyncLocalStorage>(); + + constructor(deps: ShieldsTransitionLockDependencies = {}) { + this.stateDir = deps.stateDir ?? resolveNemoclawStateDir(); + this.pid = deps.pid ?? process.pid; + this.now = deps.now ?? Date.now; + this.sleep = deps.sleep ?? defaultSleep; + this.sleepAsync = deps.sleepAsync ?? defaultSleepAsync; + this.processIsAlive = deps.isProcessAlive ?? isProcessAlive; + this.processStartIdentity = deps.readProcessStartIdentity ?? readProcessStartIdentity; + } + + withShieldsTransitionLock( + sandboxName: string, + command: string, + fn: () => T, + options: ShieldsTransitionLockOptions = {}, + ): T { + const validName = validateSandboxName(sandboxName); + if (typeof command !== "string" || command.trim().length === 0) { + throw new Error("shields transition command is required"); + } + const requestedTakeoverToken = optionalTakeoverToken(options.takeoverToken); + const existing = this.reentrantLock(validName); + if (existing) { + if ( + requestedTakeoverToken !== undefined && + requestedTakeoverToken !== existing.owner.takeoverToken + ) { + throw new Error("reentrant shields transition takeoverToken does not match the owner"); + } + this.assertHeldPath(existing); + existing.depth += 1; + try { + return fn(); + } finally { + this.release(validName, existing); + } + } + + const held = this.acquire(validName, command, options); + this.held.set(validName, held); + const originalExit = process.exit; + let deferredExit: DeferredTransitionProcessExit | null = null; + try { + // Legacy runner/policy helpers may call process.exit on command failure. + // A real exit skips finally blocks, so translate it into an exception + // while this synchronous callback owns the lock. Reentrant callbacks + // inherit the same guard and propagate the sentinel to this outer owner. + process.exit = ((code?: string | number | null): never => { + throw new DeferredTransitionProcessExit(code); + }) as typeof process.exit; + try { + return this.ownership.run(this.ownershipContext(validName, held.ownerToken), fn); + } catch (error) { + if (!(error instanceof DeferredTransitionProcessExit)) throw error; + deferredExit = error; + } + } finally { + process.exit = originalExit; + this.release(validName, held); + } + if (deferredExit) { + originalExit(deferredExit.exitCode); + } + throw new Error("unreachable: deferred process exit did not terminate"); + } + + async withShieldsTransitionLockAsync( + sandboxName: string, + command: string, + fn: () => Promise, + options: ShieldsTransitionLockOptions = {}, + ): Promise { + const validName = validateSandboxName(sandboxName); + if (typeof command !== "string" || command.trim().length === 0) { + throw new Error("shields transition command is required"); + } + const requestedTakeoverToken = optionalTakeoverToken(options.takeoverToken); + const existing = this.reentrantLock(validName); + if (existing) { + if ( + requestedTakeoverToken !== undefined && + requestedTakeoverToken !== existing.owner.takeoverToken + ) { + throw new Error("reentrant shields transition takeoverToken does not match the owner"); + } + this.assertHeldPath(existing); + existing.depth += 1; + try { + return await fn(); + } finally { + this.release(validName, existing); + } + } + + const held = await this.acquireAsync(validName, command, options); + this.held.set(validName, held); + try { + return await this.ownership.run(this.ownershipContext(validName, held.ownerToken), fn); + } finally { + this.release(validName, held); + } + } + + inspectShieldsTransitionLockOwner( + sandboxName: string, + takeoverToken: string, + ): InspectedShieldsTransitionOwner | null { + const validName = validateSandboxName(sandboxName); + const validToken = requireTakeoverToken(takeoverToken); + const lockPath = shieldsTransitionLockPath(validName, this.stateDir); + const snapshot = readExistingLock(lockPath, validName); + if (!snapshot) return null; + try { + const owner = snapshot.owner; + if (!owner || owner.takeoverToken !== validToken) return null; + return { + pid: owner.pid, + processStartIdentity: owner.processStartIdentity, + command: owner.command, + }; + } finally { + closeSnapshot(snapshot); + } + } + + takeoverShieldsTransitionLock( + sandboxName: string, + expectedOwnerPid: number, + expectedOwnerStartIdentity: string, + takeoverToken: string, + ): ShieldsTransitionTakeoverResult { + const validName = validateSandboxName(sandboxName); + if (!Number.isInteger(expectedOwnerPid) || expectedOwnerPid <= 0) { + throw new Error("expectedOwnerPid must be a positive integer"); + } + if (typeof expectedOwnerStartIdentity !== "string" || expectedOwnerStartIdentity.length === 0) { + throw new Error("expectedOwnerStartIdentity is required"); + } + const validToken = requireTakeoverToken(takeoverToken); + const lockPath = shieldsTransitionLockPath(validName, this.stateDir); + const snapshot = readExistingLock(lockPath, validName); + if (!snapshot) return { removed: false, reason: "missing" }; + + try { + const owner = snapshot.owner; + if ( + !owner || + owner.pid !== expectedOwnerPid || + owner.processStartIdentity !== expectedOwnerStartIdentity || + owner.takeoverToken !== validToken + ) { + return { removed: false, reason: "owner-mismatch" }; + } + + let removalReason: Extract< + ShieldsTransitionTakeoverReason, + "removed-dead-owner" | "removed-reused-pid" + >; + if (!this.processIsAlive(owner.pid)) { + removalReason = "removed-dead-owner"; + } else { + const currentIdentity = this.processStartIdentity(owner.pid); + if (!currentIdentity) { + return { removed: false, reason: "owner-identity-unavailable" }; + } + if (currentIdentity === owner.processStartIdentity) { + return { removed: false, reason: "owner-live" }; + } + removalReason = "removed-reused-pid"; + } + + const current = this.currentRegularLockIdentity(lockPath); + if (!current || !sameInode(current, snapshot.identity)) { + return { removed: false, reason: "path-changed" }; + } + + const quarantineDir = fs.mkdtempSync(`${lockPath}.takeover-${validToken}-`); + fs.chmodSync(quarantineDir, 0o700); + const quarantinePath = path.join(quarantineDir, "owner.json"); + try { + fs.renameSync(lockPath, quarantinePath); + } catch (error) { + this.removeEmptyQuarantine(quarantineDir); + if (isErrnoException(error) && error.code === "ENOENT") { + return { removed: false, reason: "path-changed" }; + } + throw error; + } + + const moved = readExistingLock(quarantinePath, validName); + if (!moved) { + return { removed: false, reason: "replacement-preserved", quarantinePath }; + } + try { + const movedOwner = moved.owner; + const movedMatches = + sameInode(moved.identity, snapshot.identity) && + movedOwner?.pid === expectedOwnerPid && + movedOwner.processStartIdentity === expectedOwnerStartIdentity && + movedOwner.takeoverToken === validToken; + if (!movedMatches) { + this.restoreQuarantinedReplacement(lockPath, quarantinePath); + return { removed: false, reason: "replacement-preserved", quarantinePath }; + } + + const currentQuarantine = this.currentRegularLockIdentity(quarantinePath); + if (!currentQuarantine || !sameInode(currentQuarantine, moved.identity)) { + this.restoreQuarantinedReplacement(lockPath, quarantinePath); + return { removed: false, reason: "replacement-preserved", quarantinePath }; + } + fs.unlinkSync(quarantinePath); + } finally { + closeSnapshot(moved); + } + this.removeEmptyQuarantine(quarantineDir); + return { removed: true, reason: removalReason }; + } finally { + closeSnapshot(snapshot); + } + } + + private currentRegularLockIdentity(lockPath: string): InodeIdentity | null { + try { + const stat = fs.lstatSync(lockPath, { bigint: true }); + if (stat.isSymbolicLink()) { + throw unsafeLockPathError(lockPath, "symbolic links are not allowed"); + } + if (!stat.isFile()) { + throw unsafeLockPathError(lockPath, "path is not a regular file"); + } + return inodeIdentity(stat); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") return null; + throw error; + } + } + + private restoreQuarantinedReplacement(lockPath: string, quarantinePath: string): void { + let quarantineStat: fs.BigIntStats; + try { + quarantineStat = fs.lstatSync(quarantinePath, { bigint: true }); + } catch { + return; + } + if (!quarantineStat.isFile()) return; + try { + fs.linkSync(quarantinePath, lockPath); + } catch (error) { + if (!isErrnoException(error) || error.code !== "EEXIST") throw error; + // A newer owner already occupies the canonical path. Preserve both it + // and the quarantined replacement for explicit recovery. + } + } + + private removeEmptyQuarantine(quarantineDir: string): void { + try { + fs.rmdirSync(quarantineDir); + } catch (error) { + if (!isErrnoException(error) || (error.code !== "ENOENT" && error.code !== "ENOTEMPTY")) { + throw error; + } + } + } + + private reentrantLock(sandboxName: string): HeldLock | null { + const existing = this.held.get(sandboxName); + if (!existing) return null; + return this.ownership.getStore()?.get(sandboxName) === existing.ownerToken ? existing : null; + } + + private ownershipContext(sandboxName: string, ownerToken: symbol): ReadonlyMap { + const context = new Map(this.ownership.getStore() ?? []); + context.set(sandboxName, ownerToken); + return context; + } + + private acquire( + sandboxName: string, + command: string, + options: ShieldsTransitionLockOptions, + ): HeldLock { + const state = this.acquisitionState(sandboxName, command, options); + let lastWaitReason: WaitReason | null = null; + + while (true) { + const inProcess = this.held.get(sandboxName); + if (inProcess) { + lastWaitReason = { kind: "same-process", owner: inProcess.owner }; + } else { + const created = this.tryCreate(state.lockPath, state.owner); + if (created) return created; + const observed = this.observeWaitReason( + state.lockPath, + sandboxName, + state.malformedStaleMs, + ); + if (!observed) continue; + lastWaitReason = observed; + } + this.sleep(this.waitDuration(state, lastWaitReason)); + } + } + + private async acquireAsync( + sandboxName: string, + command: string, + options: ShieldsTransitionLockOptions, + ): Promise { + const state = this.acquisitionState(sandboxName, command, options); + let lastWaitReason: WaitReason | null = null; + + while (true) { + const inProcess = this.held.get(sandboxName); + if (inProcess) { + lastWaitReason = { kind: "same-process", owner: inProcess.owner }; + } else { + const created = this.tryCreate(state.lockPath, state.owner); + if (created) return created; + const observed = this.observeWaitReason( + state.lockPath, + sandboxName, + state.malformedStaleMs, + ); + if (!observed) continue; + lastWaitReason = observed; + } + await this.sleepAsync(this.waitDuration(state, lastWaitReason)); + } + } + + private acquisitionState( + sandboxName: string, + command: string, + options: ShieldsTransitionLockOptions, + ): AcquisitionState { + const waitTimeoutMs = requireNonNegativeFinite( + options.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, + "waitTimeoutMs", + ); + const pollIntervalMs = requireNonNegativeFinite( + options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, + "pollIntervalMs", + ); + const malformedStaleMs = requireNonNegativeFinite( + options.malformedStaleMs ?? DEFAULT_MALFORMED_STALE_MS, + "malformedStaleMs", + ); + const ownerStartIdentity = this.processStartIdentity(this.pid); + if (!ownerStartIdentity) { + throw new Error( + `Cannot acquire shields transition lock: process-start identity for PID ${String(this.pid)} is unavailable`, + ); + } + + fs.mkdirSync(this.stateDir, { recursive: true, mode: 0o700 }); + const lockPath = shieldsTransitionLockPath(sandboxName, this.stateDir); + const acquiredAtMs = this.now(); + const takeoverToken = optionalTakeoverToken(options.takeoverToken); + return { + lockPath, + owner: { + version: LOCK_VERSION, + sandboxName, + pid: this.pid, + processStartIdentity: ownerStartIdentity, + command, + acquiredAtMs, + ...(takeoverToken ? { takeoverToken } : {}), + }, + startedAtMs: acquiredAtMs, + waitTimeoutMs, + pollIntervalMs, + malformedStaleMs, + }; + } + + private observeWaitReason( + lockPath: string, + sandboxName: string, + malformedStaleMs: number, + ): WaitReason | null { + const snapshot = readExistingLock(lockPath, sandboxName); + if (!snapshot) return null; + try { + const owner = snapshot.owner; + if (!owner) { + const ageMs = Math.max(0, this.now() - snapshot.mtimeMs); + return ageMs >= malformedStaleMs + ? { kind: "stale-malformed", ageMs } + : { kind: "recent-malformed", ageMs }; + } + if (!this.processIsAlive(owner.pid)) return { kind: "dead", owner }; + const currentIdentity = this.processStartIdentity(owner.pid); + if (!currentIdentity) return { kind: "identity-unavailable", owner }; + if (currentIdentity !== owner.processStartIdentity) { + return { kind: "pid-reused", owner, currentProcessStartIdentity: currentIdentity }; + } + return { kind: "live", owner }; + } finally { + closeSnapshot(snapshot); + } + } + + private waitDuration(state: AcquisitionState, reason: WaitReason | null): number { + const elapsedMs = Math.max(0, this.now() - state.startedAtMs); + if (elapsedMs >= state.waitTimeoutMs) { + throw new Error( + `Timed out after ${String(state.waitTimeoutMs)}ms waiting for shields transition lock '${state.lockPath}': ${formatWaitReason(reason, state.lockPath)}`, + ); + } + return Math.min(state.pollIntervalMs, state.waitTimeoutMs - elapsedMs); + } + + private tryCreate(lockPath: string, owner: ShieldsTransitionLockOwner): HeldLock | null { + // Avoid temp-inode/fsync churn for the common waiter path. This check is + // advisory only: link(2) below remains the no-overwrite race authority. + try { + fs.lstatSync(lockPath); + return null; + } catch (error) { + if (!isErrnoException(error) || error.code !== "ENOENT") throw error; + } + const tempPath = `${lockPath}.acquire-${String(this.pid)}-${randomBytes(16).toString("hex")}.tmp`; + let fd: number; + try { + fd = fs.openSync( + tempPath, + fs.constants.O_WRONLY | + fs.constants.O_CREAT | + fs.constants.O_EXCL | + fs.constants.O_NOFOLLOW, + 0o600, + ); + } catch (error) { + if (isErrnoException(error) && error.code === "ELOOP") { + throw unsafeLockPathError(tempPath, "symbolic links are not allowed"); + } + throw error; + } + + try { + const fdStat = fs.fstatSync(fd, { bigint: true }); + if (!fdStat.isFile()) { + throw unsafeLockPathError(tempPath, "new lock is not a regular file"); + } + fs.fchmodSync(fd, 0o600); + fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, "utf8"); + fs.fsyncSync(fd); + try { + // Publish only a complete, durable owner record. link(2) is atomic and + // refuses to overwrite an existing canonical lock, so a crash before + // this point leaves at most an unreferenced temp inode and a crash + // after it leaves a parseable token/identity record. + fs.linkSync(tempPath, lockPath); + } catch (error) { + if (isErrnoException(error) && error.code === "EEXIST") { + fs.closeSync(fd); + try { + fs.unlinkSync(tempPath); + } catch { + // The unpublished temp file is inert and can be cleaned manually. + } + return null; + } + throw error; + } + try { + fs.unlinkSync(tempPath); + } catch { + // The canonical hard link is already complete and authoritative. A + // leftover root-only temp link is inert and must not fail acquisition. + } + return { + fd, + identity: inodeIdentity(fdStat), + lockPath, + depth: 1, + ownerToken: Symbol("shields-transition-lock-owner"), + owner, + }; + } catch (error) { + try { + fs.closeSync(fd); + } catch { + // Preserve the creation error. + } + try { + fs.unlinkSync(tempPath); + } catch { + // Preserve the creation error. The temp path is never authoritative. + } + throw error; + } + } + + private assertHeldPath(held: HeldLock): void { + const fdStat = fs.fstatSync(held.fd, { bigint: true }); + let pathStat: fs.BigIntStats; + try { + pathStat = fs.lstatSync(held.lockPath, { bigint: true }); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") { + throw new Error(`Shields transition lock '${held.lockPath}' disappeared while held`); + } + throw error; + } + if (!pathStat.isFile() || !sameInode(inodeIdentity(pathStat), inodeIdentity(fdStat))) { + throw new Error(`Shields transition lock '${held.lockPath}' was replaced while held`); + } + } + + private release(sandboxName: string, held: HeldLock): void { + if (this.held.get(sandboxName) !== held) return; + held.depth -= 1; + if (held.depth > 0) return; + this.held.delete(sandboxName); + + try { + const heldIdentity = inodeIdentity(fs.fstatSync(held.fd, { bigint: true })); + const quarantineDir = fs.mkdtempSync(`${held.lockPath}.release-`); + fs.chmodSync(quarantineDir, 0o700); + const quarantinePath = path.join(quarantineDir, "owner.json"); + try { + fs.renameSync(held.lockPath, quarantinePath); + } catch (error) { + this.removeEmptyQuarantine(quarantineDir); + if (isErrnoException(error) && error.code === "ENOENT") return; + throw error; + } + + const moved = readExistingLock(quarantinePath, sandboxName); + if (!moved || !sameInode(moved.identity, heldIdentity)) { + if (moved) closeSnapshot(moved); + this.restoreQuarantinedReplacement(held.lockPath, quarantinePath); + // Never delete a replacement that appeared while the owner was + // releasing. Keep it canonical (and quarantined as a forensic hard + // link) so the next command fails closed on that owner's record. + return; + } + closeSnapshot(moved); + fs.unlinkSync(quarantinePath); + this.removeEmptyQuarantine(quarantineDir); + } finally { + fs.closeSync(held.fd); + } + } +} + +const defaultManager = new ShieldsTransitionLockManager(); + +export function withShieldsTransitionLock( + sandboxName: string, + command: string, + fn: () => T, + options: ShieldsTransitionLockOptions = {}, +): T { + return defaultManager.withShieldsTransitionLock(sandboxName, command, fn, options); +} + +export function withShieldsTransitionLockAsync( + sandboxName: string, + command: string, + fn: () => Promise, + options: ShieldsTransitionLockOptions = {}, +): Promise { + return defaultManager.withShieldsTransitionLockAsync(sandboxName, command, fn, options); +} + +export function inspectShieldsTransitionLockOwner( + sandboxName: string, + takeoverToken: string, +): InspectedShieldsTransitionOwner | null { + return defaultManager.inspectShieldsTransitionLockOwner(sandboxName, takeoverToken); +} + +export function takeoverShieldsTransitionLock( + sandboxName: string, + expectedOwnerPid: number, + expectedOwnerStartIdentity: string, + takeoverToken: string, +): ShieldsTransitionTakeoverResult { + return defaultManager.takeoverShieldsTransitionLock( + sandboxName, + expectedOwnerPid, + expectedOwnerStartIdentity, + takeoverToken, + ); +} diff --git a/src/lib/shields/verify-lock.test.ts b/src/lib/shields/verify-lock.test.ts index 583ddaf330d..c059485c5d2 100644 --- a/src/lib/shields/verify-lock.test.ts +++ b/src/lib/shields/verify-lock.test.ts @@ -63,6 +63,91 @@ describe("verifyShieldsLockState", () => { ); }); + it("requires the sticky root-owned sandbox parent for a locked Hermes tree", async () => { + const { verifyShieldsLockState } = await loadVerifier(); + const hermesTarget = { + agentName: "hermes", + configPath: "/sandbox/.hermes/config.yaml", + configDir: "/sandbox/.hermes", + sensitiveFiles: ["/sandbox/.hermes/.env", "/sandbox/.hermes/.config-hash"], + }; + const clean = makeExec({ + "/sandbox/.hermes/config.yaml": "444 root:root", + "/sandbox/.hermes/.env": "444 root:root", + "/sandbox/.hermes/.config-hash": "444 root:root", + "/sandbox/.hermes": "755 root:root", + "/sandbox": "1775 root:sandbox", + }); + + expect( + verifyShieldsLockState("hermes", hermesTarget, { + exec: clean, + verifyParentProtection: true, + }), + ).toEqual({ ok: true, issues: [] }); + + const replaceableParent = makeExec({ + "/sandbox/.hermes/config.yaml": "444 root:root", + "/sandbox/.hermes/.env": "444 root:root", + "/sandbox/.hermes/.config-hash": "444 root:root", + "/sandbox/.hermes": "755 root:root", + "/sandbox": "755 sandbox:sandbox", + }); + const drifted = verifyShieldsLockState("hermes", hermesTarget, { + exec: replaceableParent, + verifyParentProtection: true, + }); + expect(drifted.ok).toBe(false); + expect(drifted.issues).toEqual( + expect.arrayContaining([ + "parent dir mode=755 (expected 1775)", + "parent dir owner=sandbox:sandbox (expected root:sandbox)", + ]), + ); + }); + + it("requires the same protected parent for OpenClaw but does not impose it on custom agents", async () => { + const { verifyShieldsLockState } = await loadVerifier(); + const openClawTarget = { ...target, agentName: "openclaw" }; + const replaceableParent = makeExec({ + "/sandbox/.openclaw/openclaw.json": "444 root:root", + "/sandbox/.openclaw/.config-hash": "444 root:root", + "/sandbox/.openclaw": "755 root:root", + "/sandbox": "755 sandbox:sandbox", + }); + + expect( + verifyShieldsLockState("openclaw", openClawTarget, { + exec: replaceableParent, + verifyParentProtection: true, + }).issues, + ).toEqual( + expect.arrayContaining([ + "parent dir mode=755 (expected 1775)", + "parent dir owner=sandbox:sandbox (expected root:sandbox)", + ]), + ); + + const customTarget = { + agentName: "dcode", + configPath: "/sandbox/.dcode/config.json", + configDir: "/sandbox/.dcode", + sensitiveFiles: ["/sandbox/.dcode/.config-hash"], + }; + const customExec = makeExec({ + "/sandbox/.dcode/config.json": "444 root:root", + "/sandbox/.dcode/.config-hash": "444 root:root", + "/sandbox/.dcode": "755 root:root", + "/sandbox": "755 sandbox:sandbox", + }); + expect( + verifyShieldsLockState("dcode", customTarget, { + exec: customExec, + verifyParentProtection: true, + }), + ).toEqual({ ok: true, issues: [] }); + }); + it.each([ ["402", "world-writable file"], ["420", "group-writable file"], diff --git a/src/lib/shields/verify-lock.ts b/src/lib/shields/verify-lock.ts index 786497be6bd..3ff3ae8c1c4 100644 --- a/src/lib/shields/verify-lock.ts +++ b/src/lib/shields/verify-lock.ts @@ -19,6 +19,7 @@ import { parseSha256Output } from "./seal"; export type LockTarget = { + agentName?: string; configPath: string; configDir: string; sensitiveFiles?: string[]; @@ -29,6 +30,7 @@ export type VerifyShieldsLockOptions = { exec: (cmd: string[]) => string; assertLegacyLayout?: (sandboxName: string, configDir: string) => void; expectedHashes?: { [path: string]: string }; + verifyParentProtection?: boolean; }; export type VerifyShieldsLockResult = { @@ -83,6 +85,27 @@ export function verifyShieldsLockState( issues.push(`dir stat failed: ${msg}`); } + if ( + options.verifyParentProtection && + (target.agentName === "hermes" || target.agentName === "openclaw") + ) { + const separator = target.configDir.lastIndexOf("/"); + const parentDir = separator > 0 ? target.configDir.slice(0, separator) : "/"; + try { + const parentPerms = exec(["stat", "-c", "%a %U:%G", parentDir]); + const [parentMode, parentOwner] = parentPerms.split(" "); + if (parentMode !== "1775") { + issues.push(`parent dir mode=${parentMode} (expected 1775)`); + } + if (parentOwner !== "root:sandbox") { + issues.push(`parent dir owner=${parentOwner} (expected root:sandbox)`); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + issues.push(`parent dir stat failed: ${msg}`); + } + } + if (options.verifyChattr) { for (const f of filesToVerify) { try { diff --git a/test/cli/connect-readiness.test.ts b/test/cli/connect-readiness.test.ts new file mode 100644 index 00000000000..bb85fecdf98 --- /dev/null +++ b/test/cli/connect-readiness.test.ts @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + execTimeout, + runWithEnv, + testTimeout, + testTimeoutOptions, + writeHealthyDockerStub, +} from "./helpers"; + +describe("CLI connect readiness", () => { + it("waits for sandbox readiness before connecting", testTimeoutOptions(15_000), () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-wait-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const markerFile = path.join(home, "openshell-calls"); + const stateFile = path.join(home, "sandbox-list-count"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `marker_file=${JSON.stringify(markerFile)}`, + `state_file=${JSON.stringify(stateFile)}`, + 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + " echo 'Sandbox:'", + " echo", + " echo ' Id: abc'", + " echo ' Name: alpha'", + " echo ' Namespace: openshell'", + " echo ' Phase: Pending'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + ' count=$(cat "$state_file" 2>/dev/null || echo 0)', + " count=$((count + 1))", + ' echo "$count" > "$state_file"', + ' if [ "$count" -eq 1 ]; then', + " echo 'alpha ContainerCreating 10s ago'", + " else", + " echo 'alpha Ready 20s ago'", + " fi", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(localBin, "sleep"), ["#!/usr/bin/env bash", "exit 0"].join("\n"), { + mode: 0o755, + }); + // Healthy Docker so the connect readiness wait is not short-circuited by + // the #4428 docker-down fast-fail. + writeHealthyDockerStub(localBin); + + const r = runWithEnv( + "alpha connect", + { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }, + execTimeout(30_000), + ); + + expect(r.code).toBe(0); + expect(r.out.includes("Waiting for sandbox 'alpha' to be ready")).toBeTruthy(); + expect(r.out.includes("Sandbox is ready. Connecting")).toBeTruthy(); + const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); + expect(calls).toContain("sandbox get alpha"); + expect(calls.filter((call) => call === "sandbox list").length).toBeGreaterThanOrEqual(2); + expect(calls).toContain("sandbox connect alpha"); + }); + + it( + "fails fast with gateway recovery guidance when connect readiness sees a disconnected gateway", + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-gateway-down-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const markerFile = path.join(home, "openshell-calls"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + writeHealthyDockerStub(localBin); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `marker_file=${JSON.stringify(markerFile)}`, + 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + " echo 'Sandbox:'", + " echo", + " echo ' Id: abc'", + " echo ' Name: alpha'", + " echo ' Namespace: openshell'", + " echo ' Phase: Pending'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + " echo 'alpha unknown 103s ago'", + " exit 0", + "fi", + 'if [ "$1" = "status" ]; then', + " echo 'Server Status'", + " echo", + " echo ' Gateway: nemoclaw'", + " echo ' Status: Disconnected'", + " exit 0", + "fi", + 'if [ "$1" = "gateway" ] && [ "$2" = "info" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ]; then', + " echo 'Gateway Info'", + " echo", + " echo ' Gateway: nemoclaw'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', + " echo 'should-not-connect' >> \"$marker_file\"", + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + + const r = runWithEnv( + "alpha connect", + { + HOME: home, + NEMOCLAW_CONNECT_TIMEOUT: "1", + PATH: `${localBin}:${process.env.PATH || ""}`, + }, + execTimeout(10_000), + ); + + expect(r.code).toBe(1); + expect(r.out).toContain("OpenShell gateway is not running or unreachable"); + expect(r.out).toContain("nemoclaw onboard"); + expect(r.out).not.toContain("Timed out after 1s"); + const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); + expect(calls).toContain("status"); + expect(calls).not.toContain("should-not-connect"); + }, + testTimeout(15_000), + ); + + it("prints recovery guidance when readiness polling hits a terminal sandbox state", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-failed-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const markerFile = path.join(home, "openshell-calls"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `marker_file=${JSON.stringify(markerFile)}`, + 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + " echo 'Sandbox:'", + " echo", + " echo ' Id: abc'", + " echo ' Name: alpha'", + " echo ' Namespace: openshell'", + " echo ' Phase: Failed'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + " echo 'alpha Failed 1m ago'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', + " echo 'should-not-connect' >> \"$marker_file\"", + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + + const r = runWithEnv("alpha connect", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); + + expect(r.code).toBe(1); + expect(r.out.includes("Sandbox 'alpha' is in 'Failed' state")).toBeTruthy(); + expect(r.out.includes("nemoclaw alpha logs --follow")).toBeTruthy(); + expect(r.out.includes("nemoclaw alpha status")).toBeTruthy(); + const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); + expect(calls).toContain("sandbox get alpha"); + expect(calls).toContain("sandbox list"); + expect(calls).not.toContain("should-not-connect"); + }); +}); diff --git a/test/cli/connect-recovery-markerless.test.ts b/test/cli/connect-recovery-markerless.test.ts deleted file mode 100644 index 06cd03adadb..00000000000 --- a/test/cli/connect-recovery-markerless.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; - -import { runWithEnv, testTimeoutOptions, writeSandboxRegistry } from "./helpers"; - -describe("CLI markerless connect recovery", testTimeoutOptions(15_000), () => { - it("accepts sandbox exec recovery when the gateway becomes healthy", () => { - const home = fs.mkdtempSync( - path.join(os.tmpdir(), "nemoclaw-cli-connect-markerless-recovery-"), - ); - const localBin = path.join(home, "bin"); - const markerFile = path.join(home, "openshell-calls"); - const stateFile = path.join(home, "probe-state"); - const readyCountFile = path.join(home, "ready-count"); - fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home); - fs.writeFileSync(stateFile, "stopped"); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - `state_file=${JSON.stringify(stateFile)}`, - `ready_count_file=${JSON.stringify(readyCountFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Ready'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', - ' cmd="$8"', - ' case "$cmd" in', - ' *"OPENCLAW="*)', - ' echo recovered > "$state_file"', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo 'OpenClaw gateway launcher started without legacy recovery marker'", - " exit 0", - " ;;", - " *'curl -so'*)", - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - ' if [ "$(cat "$state_file")" != recovered ]; then echo STOPPED; exit 0; fi', - ' count=$(cat "$ready_count_file" 2>/dev/null || echo 0)', - " count=$((count + 1))", - ' echo "$count" > "$ready_count_file"', - ' if [ "$count" -ge 2 ]; then echo RUNNING; else echo STOPPED; fi', - " exit 0", - " ;;", - " esac", - "fi", - 'if [ "$1" = "forward" ]; then', - " exit 0", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - - const r = runWithEnv("alpha connect --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS: "0", - NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS: "0", - NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS: "3", - }); - - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); - expect(fs.readFileSync(readyCountFile, "utf8").trim()).toBe("2"); - }); - - it("does not accept markerless launcher output when gateway health never becomes running", () => { - const home = fs.mkdtempSync( - path.join(os.tmpdir(), "nemoclaw-cli-connect-markerless-unhealthy-"), - ); - const localBin = path.join(home, "bin"); - const markerFile = path.join(home, "openshell-calls"); - const stateFile = path.join(home, "probe-state"); - const readyCountFile = path.join(home, "ready-count"); - fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home); - fs.writeFileSync(stateFile, "stopped"); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - `state_file=${JSON.stringify(stateFile)}`, - `ready_count_file=${JSON.stringify(readyCountFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Ready'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', - ' cmd="$8"', - ' case "$cmd" in', - ' *"OPENCLAW="*)', - ' echo recovered > "$state_file"', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo 'OpenClaw gateway launcher started without legacy recovery marker'", - " exit 0", - " ;;", - " *'curl -so'*)", - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - ' count=$(cat "$ready_count_file" 2>/dev/null || echo 0)', - " count=$((count + 1))", - ' echo "$count" > "$ready_count_file"', - " echo STOPPED", - " exit 0", - " ;;", - " esac", - "fi", - 'if [ "$1" = "forward" ]; then', - " echo 'forward should not run before verified gateway health' >&2", - " exit 1", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - - const r = runWithEnv("alpha connect --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS: "0", - NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS: "0", - NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS: "2", - }); - - expect(r.code).toBe(1); - expect(r.out).toContain("automatic recovery failed"); - expect(r.out).not.toContain("Probe complete: recovered OpenClaw gateway"); - expect(fs.readFileSync(readyCountFile, "utf8").trim()).toBe("4"); - }); -}); diff --git a/test/cli/connect-recovery-settle.test.ts b/test/cli/connect-recovery-settle.test.ts index bd0f4787464..aeffcf59cdd 100644 --- a/test/cli/connect-recovery-settle.test.ts +++ b/test/cli/connect-recovery-settle.test.ts @@ -2,20 +2,20 @@ // SPDX-License-Identifier: Apache-2.0 // // CLI coverage for the #4710 post-recovery settle-confirm: a wedged gateway -// serves the first probe after relaunch and then drops its HTTP listener, so +// passes the controller's initial recovery proof and then drops its listener, so // `connect --probe-only` must fail and surface the wedge signature instead of // declaring a recovery that is already dying. Split from // connect-recovery.test.ts, which is at the default size budget. -import { describe, it, expect } from "vitest"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { describe, expect, it } from "vitest"; import { runWithEnv, writeSandboxRegistry } from "./helpers"; describe("CLI dispatch", () => { - it("fails probe-only when a wedged gateway serves once and then drops its listener (#4710)", () => { + it("fails probe-only when the authenticated settle probe detects a listener wedge (#4710)", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-wedge-")); const localBin = path.join(home, "bin"); const markerFile = path.join(home, "openshell-calls"); @@ -53,9 +53,9 @@ describe("CLI dispatch", () => { " *'curl -so'*)", " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", ' if [ "$(cat "$state_file")" != recovered ]; then echo STOPPED; exit 0; fi', - // The wedge shape: the relaunched gateway answers the first - // post-recovery probe, then drops its listener — every later probe - // refuses. + // Any outer-namespace post-recovery health check would be invalid in + // the OpenShell topology. Keep a counter so the assertion below proves + // the authenticated controller probe was used instead. ' count=$(cat "$ready_count_file" 2>/dev/null || echo 0)', " count=$((count + 1))", ' echo "$count" > "$ready_count_file"', @@ -74,6 +74,38 @@ describe("CLI dispatch", () => { ].join("\n"), { mode: 0o755 }, ); + fs.writeFileSync( + path.join(localBin, "docker"), + [ + "#!/usr/bin/env bash", + "set -u", + `marker_file=${JSON.stringify(markerFile)}`, + `state_file=${JSON.stringify(stateFile)}`, + 'printf \'docker %s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "info" ]; then echo "24.0.0"; exit 0; fi', + 'if [ "$1" = "ps" ] && [ "$2" = "--format" ]; then', + " echo openshell-alpha", + " exit 0", + "fi", + 'if [[ "$*" == *"--env LD_PRELOAD="* ]] && [[ "$*" == *"--env PYTHONPATH="* ]] && [[ "$*" == *"--user root openshell-alpha /usr/local/bin/nemoclaw-gateway-control recover "* ]]; then', + ' nonce="${!#}"', + ' case "$nonce" in *[!0-9a-f]*|"") exit 64 ;; esac', + ' [ "${#nonce}" -eq 64 ] || exit 64', + ' echo recovered > "$state_file"', + " echo 'GATEWAY_PID=123'", + " exit 0", + "fi", + 'if [[ "$*" == *"--env LD_PRELOAD="* ]] && [[ "$*" == *"--env PYTHONPATH="* ]] && [[ "$*" == *"--user root openshell-alpha /usr/local/bin/nemoclaw-gateway-control probe "* ]]; then', + ' nonce="${!#}"', + ' case "$nonce" in *[!0-9a-f]*|"") exit 64 ;; esac', + ' [ "${#nonce}" -eq 64 ] || exit 64', + " echo 'GATEWAY_HEALTH_TIMEOUT' >&2", + " exit 1", + "fi", + "exit 65", + ].join("\n"), + { mode: 0o755 }, + ); const r = runWithEnv("alpha connect --probe-only", { HOME: home, @@ -89,7 +121,18 @@ describe("CLI dispatch", () => { ); expect(r.out).toContain("#4710 wedge signature"); expect(r.out).toContain("config change requires gateway restart (plugins.installs)"); - // First probe succeeded, settle confirm observed the dropped listener. - expect(fs.readFileSync(readyCountFile, "utf8").trim()).toBe("2"); + const calls = fs.readFileSync(markerFile, "utf8"); + expect(calls).toMatch( + /^docker exec (?:--env [A-Z0-9_]+=[^ ]* )+--user root openshell-alpha \/usr\/local\/bin\/nemoclaw-gateway-control recover [0-9a-f]{64}$/m, + ); + expect(calls).toMatch( + /^docker exec (?:--env [A-Z0-9_]+=[^ ]* )+--user root openshell-alpha \/usr\/local\/bin\/nemoclaw-gateway-control probe [0-9a-f]{64}$/m, + ); + expect(calls).toContain("--env LD_PRELOAD="); + expect(calls).toContain("--env PYTHONPATH="); + expect(calls).toContain("--env PYTHONUSERBASE="); + expect(calls).toContain("--env PYTHONNOUSERSITE=1"); + expect(calls).not.toContain("OPENCLAW="); + expect(fs.existsSync(readyCountFile)).toBe(false); }); }); diff --git a/test/cli/connect-recovery.test.ts b/test/cli/connect-recovery.test.ts index 065bcd32790..83af5d33041 100644 --- a/test/cli/connect-recovery.test.ts +++ b/test/cli/connect-recovery.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -16,8 +17,144 @@ import { writeSandboxRegistry, } from "./helpers"; +type GatewayControlDockerStubOptions = { + callsFile: string; + stateFile: string; + recoveryStatus?: number; +}; + +function writeGatewayControlDockerStub( + localBin: string, + { callsFile, stateFile, recoveryStatus = 0 }: GatewayControlDockerStubOptions, +): void { + fs.writeFileSync( + path.join(localBin, "docker"), + [ + "#!/usr/bin/env bash", + `calls=${JSON.stringify(callsFile)}`, + `state_file=${JSON.stringify(stateFile)}`, + `recovery_status=${recoveryStatus}`, + 'printf \'%s\\n\' "$*" >> "$calls"', + 'if [ "$1" = "info" ]; then echo "24.0.0"; exit 0; fi', + 'if [ "$1" = "ps" ]; then', + ' if [[ "$*" == *"{{.ID}}"* ]]; then', + " printf 'container-id\\topenshell-alpha\\n'", + " else", + " echo openshell-alpha", + " fi", + " exit 0", + "fi", + 'if [ "$1" = "exec" ]; then', + ' if [[ "$*" == *"/usr/local/bin/nemoclaw-gateway-control recover "* ]]; then', + ' if [ "$recovery_status" -ne 0 ]; then', + " echo 'privileged gateway control failed' >&2", + ' exit "$recovery_status"', + " fi", + ' echo recovered > "$state_file"', + " echo 'GATEWAY_PID=123'", + " exit 0", + " fi", + ' if [[ "$*" == *"curl -so"* ]]; then', + " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", + ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', + " exit 0", + " fi", + "fi", + "exit 1", + ].join("\n"), + { mode: 0o755 }, + ); +} + +function expectGatewayControlRecovery(callsFile: string): void { + const calls = fs.readFileSync(callsFile, "utf8"); + expect(calls).toContain("ps --format {{.Names}}"); + const recoveryCall = calls + .split("\n") + .find((line) => line.includes("/usr/local/bin/nemoclaw-gateway-control recover")); + expect(recoveryCall).toBeDefined(); + expect(recoveryCall).toContain("--env LD_PRELOAD="); + expect(recoveryCall).toContain("--env LD_LIBRARY_PATH="); + expect(recoveryCall).toContain("--env LD_AUDIT="); + expect(recoveryCall).toContain("--env PYTHONPATH="); + expect(recoveryCall).toContain("--env PYTHONUSERBASE="); + expect(recoveryCall).toContain("--env PYTHONNOUSERSITE=1"); + expect(recoveryCall).toMatch( + /^exec (?:--env [A-Z0-9_]+=[^ ]* )+--user root openshell-alpha \/usr\/local\/bin\/nemoclaw-gateway-control recover [0-9a-f]{64}$/, + ); + expect(calls).not.toContain("OPENCLAW="); + expect(calls).not.toContain("base64 -d | sh"); +} + +async function startForwardListeners(ports: number[]): Promise<() => Promise> { + const script = [ + 'const net = require("node:net");', + "const ports = JSON.parse(process.argv[1]);", + "const servers = [];", + "let pending = ports.length;", + "const markReady = () => { pending -= 1; if (pending === 0) process.stdout.write('ready\\n'); };", + "for (const port of ports) {", + " const server = net.createServer((socket) => socket.end());", + " server.on('error', (error) => {", + " if (error.code === 'EADDRINUSE') { markReady(); return; }", + " console.error(error.stack || error);", + " process.exit(1);", + " });", + " server.listen(port, '127.0.0.1', () => {", + " servers.push(server);", + " markReady();", + " });", + "}", + "const shutdown = () => {", + " let remaining = servers.length;", + " if (remaining === 0) process.exit(0);", + " for (const server of servers) server.close(() => { if (--remaining === 0) process.exit(0); });", + " setTimeout(() => process.exit(0), 1000).unref();", + "};", + "process.on('SIGTERM', shutdown);", + ].join("\n"); + const child = spawn(process.execPath, ["-e", script, JSON.stringify(ports)], { + stdio: ["ignore", "pipe", "pipe"], + }); + let stderr = ""; + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr += chunk; + }); + + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`forward listener startup timed out: ${stderr}`)), + 2000, + ); + const markReady = (): void => { + clearTimeout(timer); + resolve(); + }; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => (chunk.includes("ready") ? markReady() : undefined)); + child.once("exit", (code) => { + clearTimeout(timer); + reject(new Error(`forward listener exited with ${code}: ${stderr}`)); + }); + }); + + return async () => { + await (child.exitCode !== null + ? Promise.resolve() + : new Promise((resolve) => { + child.kill("SIGTERM"); + const timer = setTimeout(resolve, 1500); + child.once("exit", () => { + clearTimeout(timer); + resolve(); + }); + })); + }; +} + describe("CLI dispatch", () => { - it("connect does not pre-start a duplicate port forward", () => { + it("connect does not pre-start a duplicate port forward", testTimeoutOptions(15_000), () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-forward-")); const localBin = path.join(home, "bin"); const registryDir = path.join(home, ".nemoclaw"); @@ -62,6 +199,8 @@ describe("CLI dispatch", () => { 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', " exit 0", "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, @@ -146,72 +285,83 @@ describe("CLI dispatch", () => { expect(fs.existsSync(sshMarkerFile)).toBe(false); }); - it("connect --probe-only recovers the gateway without opening SSH", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-")); - const localBin = path.join(home, "bin"); - const markerFile = path.join(home, "openshell-calls"); - const sshMarkerFile = path.join(home, "ssh-calls"); - const stateFile = path.join(home, "probe-state"); - fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home); - fs.writeFileSync(stateFile, "stopped"); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - `state_file=${JSON.stringify(stateFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Ready'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', - ' cmd="$8"', - ' case "$cmd" in', - ' *"OPENCLAW="*)', - ' echo recovered > "$state_file"', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo 'GATEWAY_PID=123'", - " exit 42", - " ;;", - " *'curl -so'*)", - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', - " exit 0", - " ;;", - " esac", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - writeRecordingCommand(localBin, "ssh", sshMarkerFile, 98); + it( + "connect --probe-only recovers the gateway without opening SSH", + testTimeoutOptions(15_000), + async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-")); + const localBin = path.join(home, "bin"); + const markerFile = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); + const sshMarkerFile = path.join(home, "ssh-calls"); + const stateFile = path.join(home, "probe-state"); + fs.mkdirSync(localBin, { recursive: true }); + writeSandboxRegistry(home); + fs.writeFileSync(stateFile, "stopped"); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `marker_file=${JSON.stringify(markerFile)}`, + `state_file=${JSON.stringify(stateFile)}`, + 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + " echo 'Sandbox:'", + " echo", + " echo ' Id: abc'", + " echo ' Name: alpha'", + " echo ' Namespace: openshell'", + " echo ' Phase: Ready'", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', + ' cmd="$8"', + ' case "$cmd" in', + " *'curl -so'*)", + " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", + ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', + " exit 0", + " ;;", + " esac", + "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + writeGatewayControlDockerStub(localBin, { callsFile: dockerCalls, stateFile }); + writeRecordingCommand(localBin, "ssh", sshMarkerFile, 98); + const stopForwardListeners = await startForwardListeners([18789]); - const r = runWithEnv("alpha connect --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - }); + try { + const r = runWithEnv("alpha connect --probe-only", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); - const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); - expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe(true); - expect(calls).not.toContain("sandbox ssh-config alpha"); - expect(calls).not.toContain("sandbox connect alpha"); - expect(fs.existsSync(sshMarkerFile)).toBe(false); - }); + expect(r.code).toBe(0); + expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); + const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); + expect(calls).toContain("sandbox get alpha"); + expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe( + true, + ); + expect(calls).not.toContain("sandbox ssh-config alpha"); + expect(calls).not.toContain("sandbox connect alpha"); + expect(fs.existsSync(sshMarkerFile)).toBe(false); + expectGatewayControlRecovery(dockerCalls); + } finally { + await stopForwardListeners(); + } + }, + ); - it("waits for recovered gateway health before failing probe-only", () => { + it("uses the authenticated recovery marker as the initial managed health proof", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-wait-")); const localBin = path.join(home, "bin"); const markerFile = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); const stateFile = path.join(home, "probe-state"); const readyCountFile = path.join(home, "ready-count"); fs.mkdirSync(localBin, { recursive: true }); @@ -237,12 +387,6 @@ describe("CLI dispatch", () => { 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', ' cmd="$8"', ' case "$cmd" in', - ' *"OPENCLAW="*)', - ' echo recovered > "$state_file"', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo 'GATEWAY_PID=123'", - " exit 0", - " ;;", " *'curl -so'*)", " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", ' if [ "$(cat "$state_file")" != recovered ]; then echo STOPPED; exit 0; fi', @@ -254,27 +398,33 @@ describe("CLI dispatch", () => { " ;;", " esac", "fi", - 'if [ "$1" = "forward" ]; then', - " exit 0", - "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, ); + writeGatewayControlDockerStub(localBin, { callsFile: dockerCalls, stateFile }); + const stopForwardListeners = await startForwardListeners([18789]); - const r = runWithEnv("alpha connect --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS: "3", - NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS: "0", - }); + try { + const r = runWithEnv("alpha connect --probe-only", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS: "3", + NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS: "0", + }); - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); - expect(fs.readFileSync(readyCountFile, "utf8").trim()).toBe("3"); + expect(r.code).toBe(0); + expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); + expect(fs.existsSync(readyCountFile)).toBe(false); + expectGatewayControlRecovery(dockerCalls); + } finally { + await stopForwardListeners(); + } }); - it("treats leading --probe-only as an implicit connect probe", () => { + it("treats leading --probe-only as an implicit connect probe", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-leading-")); const localBin = path.join(home, "bin"); const markerFile = path.join(home, "openshell-calls"); @@ -299,36 +449,47 @@ describe("CLI dispatch", () => { 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', ' cmd="$8"', ' if [[ "$cmd" == *"curl -so"* ]]; then echo "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; echo RUNNING; exit 0; fi', - ' if [[ "$cmd" == *"OPENCLAW="* ]]; then echo "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; echo UNEXPECTED_RECOVERY; exit 1; fi', "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, ); writeRecordingCommand(localBin, "ssh", sshMarkerFile, 98); + const stopForwardListeners = await startForwardListeners([18789]); - const r = runWithEnv("alpha --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - }); + try { + const r = runWithEnv("alpha --probe-only", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: OpenClaw gateway is running"); - const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); - expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe(true); - expect(calls).not.toContain("sandbox ssh-config alpha"); - expect(calls).not.toContain("sandbox connect alpha"); - expect(fs.existsSync(sshMarkerFile)).toBe(false); + expect(r.code).toBe(0); + expect(r.out).toContain("Probe complete: OpenClaw gateway is running"); + const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); + expect(calls).toContain("sandbox get alpha"); + expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe( + true, + ); + expect(calls).not.toContain("sandbox ssh-config alpha"); + expect(calls).not.toContain("sandbox connect alpha"); + expect(fs.existsSync(sshMarkerFile)).toBe(false); + } finally { + await stopForwardListeners(); + } }); - it("connect --probe-only does not retry a failed sandbox exec recovery over SSH", () => { + it("connect --probe-only does not retry failed privileged recovery over SSH", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-no-ssh-")); const localBin = path.join(home, "bin"); const markerFile = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); const sshMarkerFile = path.join(home, "ssh-calls"); + const stateFile = path.join(home, "probe-state"); fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home); + fs.writeFileSync(stateFile, "stopped"); fs.writeFileSync( path.join(localBin, "openshell"), [ @@ -346,7 +507,6 @@ describe("CLI dispatch", () => { "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "exec" ] && [ "$3" = "--name" ] && [ "$4" = "alpha" ]; then', ' cmd="$8"', - ' if [[ "$cmd" == *"OPENCLAW="* ]]; then echo "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; echo RECOVERY_FAILED >&2; exit 42; fi', ' if [[ "$cmd" == *"curl -so"* ]]; then echo "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; echo STOPPED; exit 0; fi', "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ]; then', @@ -357,6 +517,11 @@ describe("CLI dispatch", () => { ].join("\n"), { mode: 0o755 }, ); + writeGatewayControlDockerStub(localBin, { + callsFile: dockerCalls, + stateFile, + recoveryStatus: 42, + }); writeRecordingCommand(localBin, "ssh", sshMarkerFile, 98); const r = runWithEnv("alpha connect --probe-only", { @@ -370,10 +535,11 @@ describe("CLI dispatch", () => { expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe(true); expect(calls).not.toContain("sandbox ssh-config alpha"); expect(fs.existsSync(sshMarkerFile)).toBe(false); + expectGatewayControlRecovery(dockerCalls); }); it( - "connect --probe-only falls back to SSH when sandbox exec never starts", + "connect --probe-only does not fall back to SSH when sandbox exec never starts", testTimeoutOptions(15_000), () => { const home = fs.mkdtempSync( @@ -381,6 +547,7 @@ describe("CLI dispatch", () => { ); const localBin = path.join(home, "bin"); const openshellCalls = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); const sshCalls = path.join(home, "ssh-calls"); const stateFile = path.join(home, "probe-state"); fs.mkdirSync(localBin, { recursive: true }); @@ -405,58 +572,36 @@ describe("CLI dispatch", () => { " echo 'error: sandbox exec transport failed before command start' >&2", " exit 2", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "alpha" ]; then', - " echo 'Host openshell-alpha'", - " echo ' HostName 127.0.0.1'", - " echo ' User sandbox'", - " exit 0", - "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync( - path.join(localBin, "ssh"), - [ - "#!/usr/bin/env bash", - `calls=${JSON.stringify(sshCalls)}`, - `state_file=${JSON.stringify(stateFile)}`, - 'cmd="${@: -1}"', - 'printf \'ARGS %s\\n\' "$*" >> "$calls"', - 'printf \'CMD %s\\n\' "$cmd" >> "$calls"', - 'if [[ "$cmd" == *"OPENCLAW="* ]]; then', - ' echo recovered > "$state_file"', - " echo 'GATEWAY_PID=456'", - " exit 0", - "fi", - 'if [[ "$cmd" == *"curl -so"* ]]; then', - ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', - " exit 0", - "fi", - "exit 1", - ].join("\n"), - { mode: 0o755 }, - ); + writeGatewayControlDockerStub(localBin, { + callsFile: dockerCalls, + stateFile, + recoveryStatus: 42, + }); + writeRecordingCommand(localBin, "ssh", sshCalls, 98); const r = runWithEnv("alpha connect --probe-only", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, }); - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); + expect(r.code).toBe(1); const openshellLog = fs.readFileSync(openshellCalls, "utf8"); - const sshLog = fs.readFileSync(sshCalls, "utf8"); expect(openshellLog).toContain("sandbox exec --name alpha -- sh -c"); - expect(openshellLog).toContain("sandbox ssh-config alpha"); + expect(openshellLog).not.toContain("sandbox ssh-config alpha"); expect(openshellLog).not.toContain("sandbox connect"); - expect(sshLog).toContain('OPENCLAW="$(command -v openclaw)"'); - expect(sshLog).not.toMatch(/(^|\s)-tt?(\s|$)/); + expect(fs.existsSync(sshCalls)).toBe(false); + expectGatewayControlRecovery(dockerCalls); }, ); it( - "connect --probe-only falls back to SSH when sandbox exec times out after starting", + "connect --probe-only does not fall back to SSH when sandbox exec times out after starting", testTimeoutOptions(15_000), () => { const home = fs.mkdtempSync( @@ -464,6 +609,7 @@ describe("CLI dispatch", () => { ); const localBin = path.join(home, "bin"); const openshellCalls = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); const sshCalls = path.join(home, "ssh-calls"); const stateFile = path.join(home, "probe-state"); fs.mkdirSync(localBin, { recursive: true }); @@ -489,37 +635,18 @@ describe("CLI dispatch", () => { " sleep 1", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "alpha" ]; then', - " echo 'Host openshell-alpha'", - " echo ' HostName 127.0.0.1'", - " echo ' User sandbox'", - " exit 0", - "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then echo "alpha 127.0.0.1 18789 12345 running"; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync( - path.join(localBin, "ssh"), - [ - "#!/usr/bin/env bash", - `calls=${JSON.stringify(sshCalls)}`, - `state_file=${JSON.stringify(stateFile)}`, - 'cmd="${@: -1}"', - 'printf \'CMD %s\\n\' "$cmd" >> "$calls"', - 'if [[ "$cmd" == *"OPENCLAW="* ]]; then', - ' echo recovered > "$state_file"', - " echo 'GATEWAY_PID=789'", - " exit 0", - "fi", - 'if [[ "$cmd" == *"curl -so"* ]]; then', - ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', - " exit 0", - "fi", - "exit 1", - ].join("\n"), - { mode: 0o755 }, - ); + writeGatewayControlDockerStub(localBin, { + callsFile: dockerCalls, + stateFile, + recoveryStatus: 42, + }); + writeRecordingCommand(localBin, "ssh", sshCalls, 98); const r = runWithEnv("alpha connect --probe-only", { HOME: home, @@ -527,20 +654,20 @@ describe("CLI dispatch", () => { NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS: "50", }); - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered OpenClaw gateway"); + expect(r.code).toBe(1); const openshellLog = fs.readFileSync(openshellCalls, "utf8"); - const sshLog = fs.readFileSync(sshCalls, "utf8"); expect(openshellLog).toContain("sandbox exec --name alpha -- sh -c"); - expect(openshellLog).toContain("sandbox ssh-config alpha"); - expect(sshLog).toContain('OPENCLAW="$(command -v openclaw)"'); + expect(openshellLog).not.toContain("sandbox ssh-config alpha"); + expect(fs.existsSync(sshCalls)).toBe(false); + expectGatewayControlRecovery(dockerCalls); }, ); - it("recovers non-OpenClaw agents over SSH instead of root sandbox exec", () => { + it("recovers stopped Hermes agents through privileged Docker control instead of SSH", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-probe-agent-")); const localBin = path.join(home, "bin"); const openshellCalls = path.join(home, "openshell-calls"); + const dockerCalls = path.join(home, "docker-calls"); const sshCalls = path.join(home, "ssh-calls"); const stateFile = path.join(home, "probe-state"); fs.mkdirSync(localBin, { recursive: true }); @@ -569,311 +696,38 @@ describe("CLI dispatch", () => { ' if [ "$(cat "$state_file")" = recovered ]; then echo RUNNING; else echo STOPPED; fi', " exit 0", " fi", - ' decoded="$cmd"', - ' if [[ "$cmd" == *"command -v base64"* ]]; then', - ' payload="${cmd% | base64 -d | sh}"', - ' payload="${payload##* }"', - ' payload="${payload#\\\'}"', - ' payload="${payload%\\\'}"', - ' decoded="$(printf \'%s\' "$payload" | base64 -d 2>/dev/null || true)"', - " fi", - ' if [[ "$decoded" == *"echo SECRET_BOUNDARY_OK"* ]]; then', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo SECRET_BOUNDARY_OK", - " exit 0", - " fi", - ' if [[ "$cmd" == *"HERMES_HOME=/sandbox/.hermes"* || "$cmd" == *"AGENT_BIN="* ]]; then', - " echo '__NEMOCLAW_SANDBOX_EXEC_STARTED__'", - " echo UNEXPECTED_ROOT_EXEC_RECOVERY", - " exit 1", - " fi", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "ssh-config" ] && [ "$3" = "alpha" ]; then', - " echo 'Host openshell-alpha'", - " echo ' HostName 127.0.0.1'", - " echo ' User sandbox'", - " exit 0", - "fi", - 'if [ "$1" = "forward" ]; then', - " exit 0", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - fs.writeFileSync( - path.join(localBin, "ssh"), - [ - "#!/usr/bin/env bash", - `calls=${JSON.stringify(sshCalls)}`, - `state_file=${JSON.stringify(stateFile)}`, - 'cmd="${@: -1}"', - 'printf \'ARGS %s\\n\' "$*" >> "$calls"', - 'printf \'CMD %s\\n\' "$cmd" >> "$calls"', - 'if [[ "$cmd" == *"AGENT_BIN=\'/usr/local/bin/hermes\'"* ]]; then', - ' echo recovered > "$state_file"', - " echo 'GATEWAY_PID=789'", - " exit 0", - "fi", - "exit 1", - ].join("\n"), - { mode: 0o755 }, - ); - - const r = runWithEnv("alpha connect --probe-only", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - }); - - expect(r.code).toBe(0); - expect(r.out).toContain("Probe complete: recovered Hermes Agent gateway"); - const openshellLog = fs.readFileSync(openshellCalls, "utf8"); - const sshLog = fs.readFileSync(sshCalls, "utf8"); - expect(openshellLog).toContain("sandbox exec --name alpha -- sh -c"); - expect(openshellLog).toContain("sandbox ssh-config alpha"); - expect(openshellLog).not.toContain("HERMES_HOME=/sandbox/.hermes"); - expect(openshellLog).not.toContain("AGENT_BIN="); - expect(openshellLog).not.toContain("sandbox connect"); - expect(sshLog).toContain("HERMES_HOME=/sandbox/.hermes"); - expect(sshLog).toContain("AGENT_BIN='/usr/local/bin/hermes'"); - expect(sshLog).not.toMatch(/(^|\s)-tt?(\s|$)/); - }); - - it("waits for sandbox readiness before connecting", testTimeoutOptions(15_000), () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-wait-")); - const localBin = path.join(home, "bin"); - const registryDir = path.join(home, ".nemoclaw"); - const markerFile = path.join(home, "openshell-calls"); - const stateFile = path.join(home, "sandbox-list-count"); - fs.mkdirSync(localBin, { recursive: true }); - fs.mkdirSync(registryDir, { recursive: true }); - fs.writeFileSync( - path.join(registryDir, "sandboxes.json"), - JSON.stringify({ - sandboxes: { - alpha: { - name: "alpha", - model: "test-model", - provider: "nvidia-prod", - gpuEnabled: false, - policies: [], - }, - }, - defaultSandbox: "alpha", - }), - { mode: 0o600 }, - ); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - `state_file=${JSON.stringify(stateFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Pending'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', - ' count=$(cat "$state_file" 2>/dev/null || echo 0)', - " count=$((count + 1))", - ' echo "$count" > "$state_file"', - ' if [ "$count" -eq 1 ]; then', - " echo 'alpha ContainerCreating 10s ago'", - " else", - " echo 'alpha Ready 20s ago'", - " fi", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', - " exit 0", + ' echo UNEXPECTED_SSH_CONFIG >> "$calls"', + " exit 1", "fi", + 'if [ "$1" = "forward" ] && [ "$2" = "list" ]; then { echo "alpha 127.0.0.1 18789 12345 running"; echo "alpha 127.0.0.1 8642 12346 running"; }; exit 0; fi', + 'if [ "$1" = "forward" ]; then exit 99; fi', "exit 0", ].join("\n"), { mode: 0o755 }, ); - fs.writeFileSync(path.join(localBin, "sleep"), ["#!/usr/bin/env bash", "exit 0"].join("\n"), { - mode: 0o755, - }); - // Healthy Docker so the connect readiness wait is not short-circuited by - // the #4428 docker-down fast-fail. - writeHealthyDockerStub(localBin); + writeGatewayControlDockerStub(localBin, { callsFile: dockerCalls, stateFile }); + writeRecordingCommand(localBin, "ssh", sshCalls, 98); + const stopForwardListeners = await startForwardListeners([18789, 8642]); - const r = runWithEnv( - "alpha connect", - { + try { + const r = runWithEnv("alpha connect --probe-only", { HOME: home, PATH: `${localBin}:${process.env.PATH || ""}`, - }, - execTimeout(30_000), - ); - - expect(r.code).toBe(0); - expect(r.out.includes("Waiting for sandbox 'alpha' to be ready")).toBeTruthy(); - expect(r.out.includes("Sandbox is ready. Connecting")).toBeTruthy(); - const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); - expect(calls.filter((call) => call === "sandbox list").length).toBeGreaterThanOrEqual(2); - expect(calls).toContain("sandbox connect alpha"); - }); - - it( - "fails fast with gateway recovery guidance when connect readiness sees a disconnected gateway", - () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-gateway-down-")); - const localBin = path.join(home, "bin"); - const registryDir = path.join(home, ".nemoclaw"); - const markerFile = path.join(home, "openshell-calls"); - fs.mkdirSync(localBin, { recursive: true }); - fs.mkdirSync(registryDir, { recursive: true }); - fs.writeFileSync( - path.join(registryDir, "sandboxes.json"), - JSON.stringify({ - sandboxes: { - alpha: { - name: "alpha", - model: "test-model", - provider: "nvidia-prod", - gpuEnabled: false, - policies: [], - }, - }, - defaultSandbox: "alpha", - }), - { mode: 0o600 }, - ); - writeHealthyDockerStub(localBin); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Pending'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', - " echo 'alpha unknown 103s ago'", - " exit 0", - "fi", - 'if [ "$1" = "status" ]; then', - " echo 'Server Status'", - " echo", - " echo ' Gateway: nemoclaw'", - " echo ' Status: Disconnected'", - " exit 0", - "fi", - 'if [ "$1" = "gateway" ] && [ "$2" = "info" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ]; then', - " echo 'Gateway Info'", - " echo", - " echo ' Gateway: nemoclaw'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', - " echo 'should-not-connect' >> \"$marker_file\"", - " exit 0", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - - const r = runWithEnv( - "alpha connect", - { - HOME: home, - NEMOCLAW_CONNECT_TIMEOUT: "1", - PATH: `${localBin}:${process.env.PATH || ""}`, - }, - execTimeout(10_000), - ); - - expect(r.code).toBe(1); - expect(r.out).toContain("OpenShell gateway is not running or unreachable"); - expect(r.out).toContain("nemoclaw onboard"); - expect(r.out).not.toContain("Timed out after 1s"); - const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("status"); - expect(calls).not.toContain("should-not-connect"); - }, - testTimeout(15_000), - ); - - it("prints recovery guidance when readiness polling hits a terminal sandbox state", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-connect-failed-")); - const localBin = path.join(home, "bin"); - const registryDir = path.join(home, ".nemoclaw"); - const markerFile = path.join(home, "openshell-calls"); - fs.mkdirSync(localBin, { recursive: true }); - fs.mkdirSync(registryDir, { recursive: true }); - fs.writeFileSync( - path.join(registryDir, "sandboxes.json"), - JSON.stringify({ - sandboxes: { - alpha: { - name: "alpha", - model: "test-model", - provider: "nvidia-prod", - gpuEnabled: false, - policies: [], - }, - }, - defaultSandbox: "alpha", - }), - { mode: 0o600 }, - ); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `marker_file=${JSON.stringify(markerFile)}`, - 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', - " echo 'Sandbox:'", - " echo", - " echo ' Id: abc'", - " echo ' Name: alpha'", - " echo ' Namespace: openshell'", - " echo ' Phase: Failed'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', - " echo 'alpha Failed 1m ago'", - " exit 0", - "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "connect" ] && [ "$3" = "alpha" ]; then', - " echo 'should-not-connect' >> \"$marker_file\"", - " exit 0", - "fi", - "exit 0", - ].join("\n"), - { mode: 0o755 }, - ); - - const r = runWithEnv("alpha connect", { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - }); + }); - expect(r.code).toBe(1); - expect(r.out.includes("Sandbox 'alpha' is in 'Failed' state")).toBeTruthy(); - expect(r.out.includes("nemoclaw alpha logs --follow")).toBeTruthy(); - expect(r.out.includes("nemoclaw alpha status")).toBeTruthy(); - const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); - expect(calls).toContain("sandbox list"); - expect(calls).not.toContain("should-not-connect"); + expect(r.code).toBe(0); + expect(r.out).toContain("Probe complete: recovered Hermes Agent gateway"); + const openshellLog = fs.readFileSync(openshellCalls, "utf8"); + expect(openshellLog).toContain("sandbox exec --name alpha -- sh -c"); + expect(openshellLog).not.toContain("sandbox ssh-config alpha"); + expect(openshellLog).not.toContain("sandbox connect"); + expect(fs.existsSync(sshCalls)).toBe(false); + expectGatewayControlRecovery(dockerCalls); + } finally { + await stopForwardListeners(); + } }); it("preserves the registry entry when connect targets a missing live sandbox (#4497)", () => { diff --git a/test/config-set-nested-ssrf.test.ts b/test/config-set-nested-ssrf.test.ts index a463af4285d..1f8229740bc 100644 --- a/test/config-set-nested-ssrf.test.ts +++ b/test/config-set-nested-ssrf.test.ts @@ -7,8 +7,19 @@ import { describe, expect, it, vi } from "vitest"; const require = createRequire(import.meta.url); const requireCache: Record = require.cache as any; -function installMockPrivilegedExec(privilegedExecPath: string): () => void { +type MockGuardRestore = (() => void) & { guardSpy: ReturnType }; + +function restoreCachedModule(modulePath: string, previous: unknown): void { + Reflect.deleteProperty(requireCache, modulePath); + Object.assign(requireCache, previous === undefined ? {} : { [modulePath]: previous }); +} + +function installMockPrivilegedExec(privilegedExecPath: string): MockGuardRestore { const priorPrivilegedExec = require.cache[privilegedExecPath]; + const timerBoundLockPath = require.resolve("../src/lib/shields/timer-bound-lock"); + const priorTimerBoundLock = require.cache[timerBoundLockPath]; + const openClawConfigLockPath = require.resolve("../src/lib/shields/openclaw-config-lock"); + const priorOpenClawConfigLock = require.cache[openClawConfigLockPath]; requireCache[privilegedExecPath] = { id: privilegedExecPath, filename: privilegedExecPath, @@ -19,11 +30,51 @@ function installMockPrivilegedExec(privilegedExecPath: string): () => void { privilegedSandboxExecArgv: (_sandboxName: string, cmd: readonly string[]) => [...cmd], }, } as any; + requireCache[timerBoundLockPath] = { + id: timerBoundLockPath, + filename: timerBoundLockPath, + loaded: true, + exports: { + // Transition-lock behavior has dedicated coverage. Keep this SSRF suite + // independent from host process-identity discovery while it mocks ps. + withTimerBoundShieldsMutationLock: ( + _sandboxName: string, + _command: string, + callback: () => unknown, + ) => callback(), + withTimerBoundShieldsMutationLockAsync: async ( + _sandboxName: string, + _command: string, + callback: () => Promise, + ) => callback(), + }, + } as any; + const guardSpy = vi.fn((_privileged: unknown, _action: string, options: { input?: string }) => ({ + issues: [], + chattrApplied: true, + configSha256: require("node:crypto") + .createHash("sha256") + .update(options.input ?? "") + .digest("hex"), + })); + requireCache[openClawConfigLockPath] = { + id: openClawConfigLockPath, + filename: openClawConfigLockPath, + loaded: true, + exports: { + // Config-guard protocol and transaction behavior have dedicated tests. + // This suite only needs a successful digest-bound write boundary. + runOpenClawConfigGuard: guardSpy, + }, + } as any; - return () => { - if (priorPrivilegedExec) requireCache[privilegedExecPath] = priorPrivilegedExec; - else delete requireCache[privilegedExecPath]; - }; + const restore = (() => { + restoreCachedModule(privilegedExecPath, priorPrivilegedExec); + restoreCachedModule(timerBoundLockPath, priorTimerBoundLock); + restoreCachedModule(openClawConfigLockPath, priorOpenClawConfigLock); + }) as MockGuardRestore; + restore.guardSpy = guardSpy; + return restore; } describe("config set nested URL SSRF enforcement", () => { @@ -253,7 +304,11 @@ describe("config set nested URL SSRF enforcement", () => { ).resolves.toBeUndefined(); expect(errorSpy).not.toHaveBeenCalled(); - expect(execSpy).toHaveBeenCalled(); + expect(restorePrivilegedExec.guardSpy).toHaveBeenCalledWith( + expect.anything(), + "write-config", + expect.objectContaining({ input: expect.any(String) }), + ); expect(appendAuditEntry).toHaveBeenCalledWith( expect.objectContaining({ action: "config_set", @@ -342,7 +397,11 @@ describe("config set nested URL SSRF enforcement", () => { ).resolves.toBeUndefined(); expect(errorSpy).not.toHaveBeenCalled(); - expect(execSpy).toHaveBeenCalled(); + expect(restorePrivilegedExec.guardSpy).toHaveBeenCalledWith( + expect.anything(), + "write-config", + expect.objectContaining({ input: expect.any(String) }), + ); } finally { exitSpy.mockRestore(); errorSpy.mockRestore(); @@ -423,7 +482,11 @@ describe("config set nested URL SSRF enforcement", () => { ).resolves.toBeUndefined(); expect(errorSpy).not.toHaveBeenCalled(); - expect(execSpy).toHaveBeenCalled(); + expect(restorePrivilegedExec.guardSpy).toHaveBeenCalledWith( + expect.anything(), + "write-config", + expect.objectContaining({ input: expect.any(String) }), + ); } finally { exitSpy.mockRestore(); errorSpy.mockRestore(); diff --git a/test/config-set.test.ts b/test/config-set.test.ts index 9e2f6f1d733..042e4f0a13f 100644 --- a/test/config-set.test.ts +++ b/test/config-set.test.ts @@ -15,8 +15,10 @@ const { validateUrlValue, validateUrlValueWithDns, rewriteConfigUrlsWithDnsPinning, + restartSandboxAgentAfterConfigSet, formatConfigValueForLogs, resolveAgentConfig, + buildConfigSetRestartGuidance, buildRecomputeSandboxConfigHashScript, } = require("../src/lib/sandbox/config"); const { selectDirectSandboxContainer } = require("../src/lib/sandbox/privileged-exec"); @@ -46,7 +48,7 @@ describe("resolveAgentConfig", () => { }); describe("buildRecomputeSandboxConfigHashScript", () => { - it("keeps OpenClaw on the mutable compatibility hash", () => { + it("does not run a pathname hash pass after an OpenClaw config transaction", () => { const script = buildRecomputeSandboxConfigHashScript({ agentName: "openclaw", configPath: "/sandbox/.openclaw/openclaw.json", @@ -56,13 +58,10 @@ describe("buildRecomputeSandboxConfigHashScript", () => { sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], }); - expect(script).toContain("cd '/sandbox/.openclaw'"); - expect(script).toContain("sha256sum 'openclaw.json' > .config-hash"); - expect(script).toContain("chown sandbox:sandbox .config-hash"); - expect(script).toContain("chmod 660 .config-hash"); + expect(script).toBeNull(); }); - it("updates Hermes strict and compatibility hashes with the expected permissions", () => { + it("does not run a second pathname-based hash pass after a Hermes config transaction", () => { const script = buildRecomputeSandboxConfigHashScript({ agentName: "hermes", configPath: "/sandbox/.hermes/config.yaml", @@ -72,21 +71,7 @@ describe("buildRecomputeSandboxConfigHashScript", () => { sensitiveFiles: ["/sandbox/.hermes/.config-hash", "/sandbox/.hermes/.env"], }); - expect(script).toContain("strict_hash='/etc/nemoclaw/hermes.config-hash'"); - expect(script).toContain('strict_tmp="${strict_hash}.tmp.$$"'); - expect(script).toContain("compat_hash='/sandbox/.hermes/.config-hash'"); - expect(script).toContain('compat_tmp="${compat_hash}.tmp.$$"'); - expect(script).toContain('trap \'rm -f "$strict_tmp" "$compat_tmp"\' EXIT HUP INT TERM'); - expect(script).toContain( - "sha256sum '/sandbox/.hermes/config.yaml' '/sandbox/.hermes/.env' > \"$strict_tmp\"", - ); - expect(script).toContain('chown root:root "$strict_tmp"'); - expect(script).toContain('chmod 444 "$strict_tmp"'); - expect(script).toContain('mv -f "$strict_tmp" "$strict_hash"'); - expect(script).toContain('cp "$strict_hash" "$compat_tmp"'); - expect(script).toContain('chown sandbox:sandbox "$compat_tmp"'); - expect(script).toContain('chmod 600 "$compat_tmp"'); - expect(script).toContain('mv -f "$compat_tmp" "$compat_hash"'); + expect(script).toBeNull(); }); }); @@ -119,6 +104,45 @@ describe("selectDirectSandboxContainer", () => { }); describe("config set helpers", () => { + describe("buildConfigSetRestartGuidance", () => { + it("keeps managed restart guidance for OpenClaw and Hermes", () => { + for (const agentName of ["openclaw", "hermes"]) { + const output = buildConfigSetRestartGuidance("alpha", agentName).join("\n"); + + expect(output).toContain("--restart"); + expect(output).toContain("nemoclaw 'alpha' gateway restart"); + } + }); + + it("uses runtime-specific guidance for custom agents", () => { + const output = buildConfigSetRestartGuidance("custom-box", "custom-agent").join("\n"); + + expect(output).toContain("Follow the restart procedure for 'custom-agent'"); + expect(output).toContain("NemoClaw does not manage restarts for this agent"); + expect(output).not.toContain("--restart"); + expect(output).not.toContain("gateway restart"); + }); + }); + + describe("restartSandboxAgentAfterConfigSet", () => { + it("routes --restart through the managed gateway supervisor flow", () => { + const calls: string[] = []; + + restartSandboxAgentAfterConfigSet("alpha", (sandboxName: string) => { + calls.push(sandboxName); + return { ok: true }; + }); + + expect(calls).toEqual(["alpha"]); + }); + + it("fails the config command when the managed restart fails", () => { + expect(() => restartSandboxAgentAfterConfigSet("alpha", () => ({ ok: false }))).toThrow( + "Config was updated, but the managed gateway restart failed for 'alpha'.", + ); + }); + }); + describe("extractDotpath", () => { it("extracts a top-level key", () => { expect(extractDotpath({ foo: "bar" }, "foo")).toBe("bar"); diff --git a/test/e2e-gateway-isolation.sh b/test/e2e-gateway-isolation.sh index 76d14d2d520..a363d587569 100755 --- a/test/e2e-gateway-isolation.sh +++ b/test/e2e-gateway-isolation.sh @@ -205,6 +205,44 @@ else fail "sandbox CAN kill gateway processes: $OUT" fi +# ── Test 13a: Final image enforces the gateway-control boundary ── + +info "13a. Final image keeps gateway control root-only with required group access" +# shellcheck disable=SC2016 # The container-side bash expands these expressions. +ROOT_CONTROL_OUT=$(run_as_root ' + set -eu + [ "$(stat -c "%U:%G %a" /usr/local/bin/nemoclaw-gateway-control)" = "root:root 700" ] + [ "$(stat -c "%U:%G %a" /usr/local/lib/nemoclaw/managed-gateway-control.py)" = "root:root 500" ] + [ "$(stat -c "%U:%G %a" /usr/local/lib/nemoclaw/state-dir-guard.py)" = "root:root 500" ] + [ "$(stat -c "%U:%G %a" /usr/local/lib/nemoclaw/openclaw-config-guard.py)" = "root:root 500" ] + [ "$(stat -c "%U:%G %a" /usr/local/lib/nemoclaw/gateway-supervisor.sh)" = "root:root 444" ] + echo META_OK + id -nG gateway | tr " " "\n" | grep -qx sandbox + id -nG root | tr " " "\n" | grep -qx sandbox + echo GROUPS_OK + nonce=$(printf "%064d" 0) + rc=0 + /usr/local/bin/nemoclaw-gateway-control probe "$nonce" >/tmp/gateway-control-probe.out 2>&1 || rc=$? + cat /tmp/gateway-control-probe.out + [ "$rc" -ne 0 ] + grep -qx SUPERVISOR_UNAVAILABLE /tmp/gateway-control-probe.out + echo ROOT_PROBE_OK +' 2>&1 || true) +# shellcheck disable=SC2016 # The container-side bash expands these expressions. +SANDBOX_CONTROL_OUT=$(run_as_sandbox ' + nonce=$(printf "%064d" 0) + /usr/local/bin/nemoclaw-gateway-control probe "$nonce" +' 2>&1 || true) +if echo "$ROOT_CONTROL_OUT" | grep -q META_OK \ + && echo "$ROOT_CONTROL_OUT" | grep -q GROUPS_OK \ + && echo "$ROOT_CONTROL_OUT" | grep -q ROOT_PROBE_OK \ + && echo "$SANDBOX_CONTROL_OUT" | grep -qi "permission denied" \ + && ! echo "$SANDBOX_CONTROL_OUT" | grep -q PRIVILEGED_CONTROL_UNAVAILABLE; then + pass "gateway control modes, group access, root probe, and sandbox-user refusal are enforced" +else + fail "gateway control boundary mismatch: root=[$ROOT_CONTROL_OUT] sandbox=[$SANDBOX_CONTROL_OUT]" +fi + # ── Test 14: Dangerous capabilities are dropped by entrypoint ──── info "14. Entrypoint drops the full issue #3280 dangerous-cap inventory from sandbox-user bounding set" diff --git a/test/e2e/live/gateway-guard-recovery.test.ts b/test/e2e/live/gateway-guard-recovery.test.ts index 6f5ce19a749..8eb3c94fb3a 100644 --- a/test/e2e/live/gateway-guard-recovery.test.ts +++ b/test/e2e/live/gateway-guard-recovery.test.ts @@ -4,10 +4,10 @@ /** * Live E2E: gateway guard-chain recovery after pod-recreate /tmp wipe. * - * Failing-test-first regression guard for NVIDIA/NemoClaw#2701. On `main` at - * the time this test landed, `buildOpenClawRecoveryScript()` takes a - * "warn-and-proceed" branch when `/tmp/nemoclaw-proxy-env.sh` is missing — - * it logs `[gateway-recovery] WARNING` and launches the gateway naked. On + * Regression guard for NVIDIA/NemoClaw#2701. The historical recovery shell + * took a "warn-and-proceed" branch when `/tmp/nemoclaw-proxy-env.sh` was + * missing: it logged `[gateway-recovery] WARNING` and launched the gateway + * naked. On * aarch64 / DGX Spark this triggers an infinite crash loop in * `@homebridge/ciao` (`os.networkInterfaces()` throws because the OpenShell * netns blocks the syscall). The only manual recovery is a 5-min @@ -25,8 +25,8 @@ * #2701 acceptance scope for this PR: * - Covered: the default OpenClaw production recovery route * (`nemoclaw connect --probe-only` → - * checkAndRecoverSandboxProcesses() → `openshell sandbox exec -- sh -c` - * buildOpenClawRecoveryScript()) after the pod-recreate-equivalent state + * checkAndRecoverSandboxProcesses() → authenticated PID 1 supervisor) + * after the pod-recreate-equivalent state * of an empty guard-chain `/tmp` plus no running gateway process. This * proves the user no longer needs `nemoclaw rebuild --yes` for * that recovered runtime state. @@ -80,7 +80,7 @@ test("gateway recovery restores /tmp guard chain after pod-recreate wipe (#2701) acceptanceCoverage: { covered: [ "production connect --probe-only recovery route", - "openshell sandbox exec -- sh -c OpenClaw recovery script", + "authenticated PID 1 OpenClaw recovery supervisor", "pod-recreate-equivalent empty /tmp guard chain plus missing gateway process", "no rebuild required for the recovered runtime state", ], @@ -124,13 +124,43 @@ test("gateway recovery restores /tmp guard chain after pod-recreate wipe (#2701) ...buildAvailabilityProbeEnv(), OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY ?? "nemoclaw", }, - timeoutMs: 90_000, + timeoutMs: 180_000, }); cleanup.add(`recovery-result-${instance.sandboxName}`, async () => { await artifacts.writeJson("recovery-result.json", { exitCode: recoveryResult.exitCode, }); }); + // Capture PID 1 and gateway evidence before the exit-code assertion can + // abort the scenario and cleanup destroys the sandbox. + const recoveryDiagnostics = await sandbox.exec( + instance.sandboxName, + [ + "sh", + "-c", + "printf '%s\\n' '== entrypoint log ==' ; " + + "tail -n 300 /tmp/nemoclaw-start.log 2>&1 || true; " + + "printf '%s\\n' '== gateway log ==' ; " + + "tail -n 300 /tmp/gateway.log 2>&1 || true; " + + "printf '%s\\n' '== direct gateway health ==' ; " + + "curl -so /dev/null -w 'HTTP %{http_code}\\n' --max-time 3 http://127.0.0.1:18789/health 2>&1 || true; " + + "printf '%s\\n' '== gateway pid record ==' ; " + + "cat /tmp/nemoclaw-gateway.pid 2>&1 || true; " + + "printf '%s\\n' '== supervisor status ==' ; " + + "cat /run/nemoclaw/gateway-control/status 2>&1 || true", + ], + { + artifactName: "gateway-recovery-diagnostics", + env: { + ...buildAvailabilityProbeEnv(), + OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY ?? "nemoclaw", + }, + }, + ); + expect( + recoveryResult.exitCode, + `connect --probe-only recovery failed\nstdout:\n${recoveryResult.stdout}\nstderr:\n${recoveryResult.stderr}`, + ).toBe(0); // ── Assert #2701 contract ──────────────────────────────────────── // After recovery completes, the guard chain MUST be restored. Before the @@ -141,8 +171,8 @@ test("gateway recovery restores /tmp guard chain after pod-recreate wipe (#2701) // A missing proxy-env file is still worth surfacing, but the warning must // describe trusted restoration instead of an unguarded launch. - await gateway.expectLogContains(instance, /restoring library guards from packaged preloads/); - await gateway.expectLogDoesNotContain(instance, /gateway launching without library guards/); + expect(recoveryDiagnostics.stdout).toMatch(/restoring library guards from packaged preloads/); + expect(recoveryDiagnostics.stdout).not.toMatch(/gateway launching without library guards/); // Gateway must be steady-state — no crash loop. This assertion is // the "would have caught DGX Spark" check, even on x86 runners, diff --git a/test/e2e/live/hermes-e2e.test.ts b/test/e2e/live/hermes-e2e.test.ts index 9f25916aaa0..0463235494b 100644 --- a/test/e2e/live/hermes-e2e.test.ts +++ b/test/e2e/live/hermes-e2e.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import { shellQuote } from "../fixtures/clients/command.ts"; import { trustedProviderEndpoint } from "../fixtures/clients/provider.ts"; import { trustedSandboxShellScript, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; @@ -25,7 +26,7 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; // This is intentionally a direct live Vitest test, not a new registry layer: // the contract is the real installer/onboard/runtime boundary for Hermes. // Vitest owns artifacts, cleanup, redaction, and timeouts while still spawning -// `bash install.sh --non-interactive`, `nemoclaw`, `openshell`, sandbox exec, +// `bash install.sh --non-interactive --fresh`, `nemoclaw`, `openshell`, sandbox exec, // direct NVIDIA Endpoints curl, and inference.local probes. const REPO_ROOT = path.resolve(import.meta.dirname, "../../.."); @@ -162,12 +163,15 @@ function readJsonFile(filePath: string): unknown { } function registryEntry(name: string): Record | undefined { - if (!fs.existsSync(REGISTRY_FILE)) return undefined; - const registry = readJsonFile(REGISTRY_FILE); - if (!registry || typeof registry !== "object") return undefined; - const sandboxes = (registry as { sandboxes?: unknown }).sandboxes; - if (!sandboxes || typeof sandboxes !== "object") return undefined; - const entry = (sandboxes as Record)[name]; + const registry = fs.existsSync(REGISTRY_FILE) ? readJsonFile(REGISTRY_FILE) : null; + const sandboxes = + registry && typeof registry === "object" + ? (registry as { sandboxes?: unknown }).sandboxes + : null; + const entry = + sandboxes && typeof sandboxes === "object" + ? (sandboxes as Record)[name] + : null; return entry && typeof entry === "object" ? (entry as Record) : undefined; } @@ -194,6 +198,16 @@ function forwardListHasRunningPort(output: string, sandboxName: string, port: st }); } +function parseGatewayProcess(output: string): { owner: string; pid: string; ppid: string } { + const [owner = "", pid = "", ppid = ""] = output.trim().split(/\s+/); + expect(owner, `expected gateway process owner, got ${JSON.stringify(output)}`).not.toBe(""); + expect(pid, `expected gateway process pid, got ${JSON.stringify(output)}`).toMatch(/^[0-9]+$/); + expect(ppid, `expected gateway process parent pid, got ${JSON.stringify(output)}`).toMatch( + /^[0-9]+$/, + ); + return { owner, pid, ppid }; +} + async function bestEffort(run: () => Promise): Promise { try { await run(); @@ -233,7 +247,7 @@ test.skipIf(!shouldRunLiveE2E())( await artifacts.writeJson("target.json", { id: "hermes-e2e", runner: "vitest", - boundary: "install.sh --non-interactive + Hermes sandbox runtime", + boundary: "install.sh --non-interactive --fresh + Hermes sandbox runtime", sandboxName: SANDBOX_NAME, dashboardEnabled: hermesDashboardE2eEnabled(), securityPostureEnabled: securityPostureEnabled(), @@ -301,13 +315,38 @@ test.skipIf(!shouldRunLiveE2E())( expect(Number(reachabilityStatus), resultText(providerReachability)).toBeLessThan(500); // Phase 2: real installer + non-interactive Hermes onboard. - const install = await host.command("bash", ["install.sh", "--non-interactive"], { + const install = await host.command("bash", ["install.sh", "--non-interactive", "--fresh"], { artifactName: "phase-2-install-hermes", cwd: REPO_ROOT, env, redactionValues, timeoutMs: 60 * 60_000, }); + await (install.exitCode === 0 + ? Promise.resolve() + : bestEffort(() => + sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + String.raw` + printf '%s\n' '== pid 1 ==' + tr '\0' ' ' /dev/null || true + printf '\n%s\n' '== process tree ==' + ps -eo user=,pid=,ppid=,stat=,args= 2>&1 || true + printf '%s\n' '== entrypoint log ==' + tail -n 300 /tmp/nemoclaw-start.log 2>&1 || true + printf '%s\n' '== gateway log ==' + tail -n 300 /tmp/gateway.log 2>&1 || true + `.trim(), + ), + { + artifactName: "phase-2-hermes-startup-failure-diagnostics", + env: commandEnv(), + redactionValues, + timeoutMs: 30_000, + }, + ), + )); expect(install.exitCode, resultText(install)).toBe(0); const cliProbe = await host.command( @@ -487,7 +526,651 @@ test.skipIf(!shouldRunLiveE2E())( expect(httpStatusOk(dashboardInternal.stdout)).toBe(true); } - // Phase 5: live inference through both the external provider and the + // Phase 5: host-mediated Hermes gateway restart. This validates the + // runtime contract behind #2426 against a real OpenShell/Hermes sandbox: + // The installed supervision tree controls the gateway process, direct + // sandbox config drift is refused rather than adopted, the public bridges + // and dashboard process recover together, and both PID 1 and the startup + // supervisor remain stable throughout. + const gatewayProcessScript = trustedSandboxShellScript( + [ + "ps -eo user=,pid=,ppid=,args= |", + String.raw`awk '($4 ~ /(^|\/)(hermes|hermes[.]real|python|python3)$/) && (index($0, "hermes gateway run") || index($0, "hermes.real gateway run")) { print $1 " " $2 " " $3; found = 1; exit } END { exit found ? 0 : 1 }'`, + ].join(" "), + ); + const beforeRestartProcess = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-hermes-gateway-process-before-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(beforeRestartProcess.exitCode, resultText(beforeRestartProcess)).toBe(0); + const beforeGateway = parseGatewayProcess(beforeRestartProcess.stdout); + const rootSupervisorTopology = beforeGateway.owner === "gateway"; + let recoveredGateway = beforeGateway; + + const pid1IdentityScript = trustedSandboxShellScript( + String.raw`python3 -c 'from pathlib import Path; text=Path("/proc/1/stat").read_text(); tail=text.rsplit(")", 1)[1].split(); cmd=Path("/proc/1/cmdline").read_bytes().replace(b"\0", b" ").decode(); print("1 " + tail[19] + " " + cmd)'`, + ); + const beforePid1 = await sandbox.execShell(SANDBOX_NAME, pid1IdentityScript, { + artifactName: "phase-5-pid1-before-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(beforePid1.exitCode, resultText(beforePid1)).toBe(0); + + if (rootSupervisorTopology) { + expect(beforeGateway.owner).toBe("gateway"); + + const envMarker = `issue_2426_${Date.now()}`; + const envBackup = `/tmp/hermes-e2e-env-before-${Date.now()}`; + const mutateEnv = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `marker=${shellQuote(envMarker)}`, + `backup=${shellQuote(envBackup)}`, + "command -v gosu >/dev/null 2>&1", + 'gosu sandbox cp /sandbox/.hermes/.env "$backup"', + 'gosu sandbox sh -lc \'printf "\\nNEMOCLAW_E2E_RESTART_MARKER=%s\\n" "$1" >> /sandbox/.hermes/.env\' sh "$marker"', + ].join("; "), + ), + { + artifactName: "phase-5-mutate-hermes-env-as-sandbox-user", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(mutateEnv.exitCode, resultText(mutateEnv)).toBe(0); + + const refuseMutableDrift = await host.command( + "nemohermes", + [SANDBOX_NAME, "gateway", "restart", "--quiet"], + { + artifactName: "phase-5-refuse-untrusted-hermes-env-drift", + env: commandEnv(), + timeoutMs: 180_000, + }, + ); + expect(refuseMutableDrift.exitCode, resultText(refuseMutableDrift)).not.toBe(0); + expect(resultText(refuseMutableDrift)).toMatch( + /config hash mismatch|GATEWAY_CONFIG_HASH_MISMATCH/, + ); + + const afterMutableRefusalProcess = await sandbox.execShell( + SANDBOX_NAME, + gatewayProcessScript, + { + artifactName: "phase-5-hermes-gateway-after-mutable-drift-refusal", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(afterMutableRefusalProcess.exitCode, resultText(afterMutableRefusalProcess)).toBe(0); + expect(parseGatewayProcess(afterMutableRefusalProcess.stdout).pid).toBe(beforeGateway.pid); + + const restoreMutableEnv = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `backup=${shellQuote(envBackup)}`, + 'gosu sandbox sh -c \'cat "$1" > /sandbox/.hermes/.env && rm -f "$1"\' sh "$backup"', + "sha256sum -c /etc/nemoclaw/hermes.config-hash --status", + "echo ENV_RESTORED", + ].join("; "), + ), + { + artifactName: "phase-5-restore-hermes-env-after-refusal", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(restoreMutableEnv.exitCode, resultText(restoreMutableEnv)).toBe(0); + expect(restoreMutableEnv.stdout).toContain("ENV_RESTORED"); + + const stopApiForward = await sandbox.openshell(["forward", "stop", "8642", SANDBOX_NAME], { + artifactName: "phase-5-stop-hermes-api-forward-before-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(stopApiForward.exitCode, resultText(stopApiForward)).toBe(0); + + const restart = await host.command("nemohermes", [SANDBOX_NAME, "gateway", "restart"], { + artifactName: "phase-5-nemohermes-gateway-restart", + env: commandEnv(), + timeoutMs: 180_000, + }); + expect(restart.exitCode, resultText(restart)).toBe(0); + expect(resultText(restart)).toContain("Gateway restarted"); + expect(resultText(restart)).toContain("health passed"); + expect(resultText(restart)).toContain("forwards checked/recovered"); + + const afterRestartProcess = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-hermes-gateway-process-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRestartProcess.exitCode, resultText(afterRestartProcess)).toBe(0); + const afterGateway = parseGatewayProcess(afterRestartProcess.stdout); + expect(afterGateway.owner).toBe("gateway"); + expect(afterGateway.pid).not.toBe(beforeGateway.pid); + + const afterRestartPid1 = await sandbox.execShell(SANDBOX_NAME, pid1IdentityScript, { + artifactName: "phase-5-pid1-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRestartPid1.exitCode, resultText(afterRestartPid1)).toBe(0); + expect(afterRestartPid1.stdout.trim()).toBe(beforePid1.stdout.trim()); + + const restartHashCheck = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + "sha256sum -c /etc/nemoclaw/hermes.config-hash --status && sha256sum -c /sandbox/.hermes/.config-hash --status && echo OK", + ), + { + artifactName: "phase-5-hermes-config-hashes-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(restartHashCheck.exitCode, resultText(restartHashCheck)).toBe(0); + expect(restartHashCheck.stdout).toContain("OK"); + + const restartHostHealth = await host.command( + "curl", + ["-sf", "--max-time", "10", HERMES_HOST_HEALTH_URL], + { + artifactName: "phase-5-hermes-host-health-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(restartHostHealth.exitCode, resultText(restartHostHealth)).toBe(0); + expect(resultText(restartHostHealth)).toMatch(/"ok"/i); + + const restartForwardList = await sandbox.openshell(["forward", "list"], { + artifactName: "phase-5-forward-list-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(restartForwardList.exitCode, resultText(restartForwardList)).toBe(0); + expect(forwardListHasRunningPort(restartForwardList.stdout, SANDBOX_NAME, "8642")).toBe(true); + for (const dashboardPort of hermesDashboardE2eEnabled() ? [HERMES_DASHBOARD_PORT] : []) { + expect( + forwardListHasRunningPort(restartForwardList.stdout, SANDBOX_NAME, dashboardPort), + ).toBe(true); + } + + // Regression precondition for #5253: Hermes deliberately uses a Python + // gateway, so its proxy-env and gateway process do not carry OpenClaw's + // Node safety-net/ciao preloads. The old generic recovery path treated + // this valid state as unsafe and refused to relaunch Hermes. + const issue5253Precondition = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `pid=${shellQuote(afterGateway.pid)}`, + "test -f /tmp/nemoclaw-proxy-env.sh", + "! grep -Eq 'NODE_OPTIONS|nemoclaw-sandbox-safety-net|nemoclaw-ciao-network-guard' /tmp/nemoclaw-proxy-env.sh", + `python3 -c 'from pathlib import Path; import sys; env=Path("/proc/" + sys.argv[1] + "/environ").read_bytes(); sys.exit(1 if b"nemoclaw-sandbox-safety-net" in env or b"nemoclaw-ciao-network-guard" in env else 0)' "$pid"`, + "echo ISSUE_5253_PRECONDITION_OK", + ].join("; "), + ), + { + artifactName: "phase-5-issue-5253-missing-node-guards-precondition", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(issue5253Precondition.exitCode, resultText(issue5253Precondition)).toBe(0); + expect(issue5253Precondition.stdout).toContain("ISSUE_5253_PRECONDITION_OK"); + + // Deliberately terminate the exact tracked PID instead of invoking + // `hermes gateway stop`: upstream's graceful command writes a planned-stop + // marker and can return while a split-UID gateway is still alive. This + // injects the stronger stopped-process state that recovery must repair. + const stopGatewayForRecover = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `pid=${shellQuote(afterGateway.pid)}`, + 'kill -TERM "$pid" 2>/dev/null || true', + 'for _i in 1 2 3 4 5; do state=$(ps -p "$pid" -o stat= 2>/dev/null || true); case "$state" in \'\'|Z*) echo GATEWAY_STOPPED; exit 0 ;; esac; sleep 1; done', + 'kill -KILL "$pid" 2>/dev/null || true', + 'for _i in 1 2 3 4 5; do state=$(ps -p "$pid" -o stat= 2>/dev/null || true); case "$state" in \'\'|Z*) echo GATEWAY_STOPPED; exit 0 ;; esac; sleep 1; done', + 'echo GATEWAY_STOP_FAILED; ps -p "$pid" -o pid,stat,args=; exit 1', + ].join("; "), + ), + { + artifactName: "phase-5-stop-hermes-gateway-before-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(stopGatewayForRecover.exitCode, resultText(stopGatewayForRecover)).toBe(0); + expect(stopGatewayForRecover.stdout).toContain("GATEWAY_STOPPED"); + + const stopHermesAuxiliaries = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `dashboard_public=${shellQuote(HERMES_DASHBOARD_PORT)}`, + `dashboard_internal=${shellQuote(HERMES_DASHBOARD_INTERNAL_PORT)}`, + 'pids=$(ps -eo pid=,comm=,args= | awk -v dp="$dashboard_public" -v di="$dashboard_internal" \'($2 == "socat" && (index($0, "TCP-LISTEN:8642") || index($0, "TCP-LISTEN:" dp))) || ($2 ~ /^(hermes|hermes[.]real|python|python3)$/ && index($0, "hermes dashboard") && index($0, "--port " di)) { print $1 }\')', + "set -- $pids", + '[ "$#" -ge 3 ] || { echo "EXPECTED_AT_LEAST_3_AUXILIARIES, found $#" >&2; ps -eo pid,comm,args; exit 1; }', + 'for pid in "$@"; do kill -TERM "$pid" 2>/dev/null || true; done', + "sleep 2", + 'for pid in "$@"; do kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true; done', + 'echo "AUXILIARIES_STOPPED=$#"', + ].join("; "), + ), + { + artifactName: "phase-5-stop-hermes-auxiliaries-before-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(stopHermesAuxiliaries.exitCode, resultText(stopHermesAuxiliaries)).toBe(0); + expect(stopHermesAuxiliaries.stdout).toMatch(/AUXILIARIES_STOPPED=[3-9]/); + + const recoverStoppedGateway = await host.command("nemohermes", [SANDBOX_NAME, "recover"], { + artifactName: "phase-5-nemohermes-recover-stopped-gateway", + env: commandEnv(), + timeoutMs: 180_000, + }); + expect(recoverStoppedGateway.exitCode, resultText(recoverStoppedGateway)).toBe(0); + + const afterRecoverProcess = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-hermes-gateway-process-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRecoverProcess.exitCode, resultText(afterRecoverProcess)).toBe(0); + recoveredGateway = parseGatewayProcess(afterRecoverProcess.stdout); + expect(recoveredGateway.owner).toBe("gateway"); + expect(recoveredGateway.pid).not.toBe(afterGateway.pid); + + const recoveredIssue5253Env = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `pid=${shellQuote(recoveredGateway.pid)}`, + `python3 -c 'from pathlib import Path; import sys; entries=Path("/proc/" + sys.argv[1] + "/environ").read_bytes().split(b"\\0"); env=dict(item.split(b"=", 1) for item in entries if b"=" in item); node_options=env.get(b"NODE_OPTIONS", b""); ok=env.get(b"HERMES_HOME") == b"/sandbox/.hermes" and env.get(b"HTTP_PROXY", b"").startswith(b"http://") and b"nemoclaw-sandbox-safety-net" not in node_options and b"nemoclaw-ciao-network-guard" not in node_options; sys.exit(0 if ok else 1)' "$pid"`, + "echo ISSUE_5253_RECOVERED_ENV_OK", + ].join("; "), + ), + { + artifactName: "phase-5-issue-5253-recovered-gateway-environment", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(recoveredIssue5253Env.exitCode, resultText(recoveredIssue5253Env)).toBe(0); + expect(recoveredIssue5253Env.stdout).toContain("ISSUE_5253_RECOVERED_ENV_OK"); + + const afterRecoverPid1 = await sandbox.execShell(SANDBOX_NAME, pid1IdentityScript, { + artifactName: "phase-5-pid1-after-both-down-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRecoverPid1.exitCode, resultText(afterRecoverPid1)).toBe(0); + expect(afterRecoverPid1.stdout.trim()).toBe(beforePid1.stdout.trim()); + + const recoverHostHealth = await host.command( + "curl", + ["-sf", "--max-time", "10", HERMES_HOST_HEALTH_URL], + { + artifactName: "phase-5-hermes-host-health-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(recoverHostHealth.exitCode, resultText(recoverHostHealth)).toBe(0); + expect(resultText(recoverHostHealth)).toMatch(/"ok"/i); + + const afterBothDownForwardList = await sandbox.openshell(["forward", "list"], { + artifactName: "phase-5-forward-list-after-both-down-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterBothDownForwardList.exitCode, resultText(afterBothDownForwardList)).toBe(0); + expect(forwardListHasRunningPort(afterBothDownForwardList.stdout, SANDBOX_NAME, "8642")).toBe( + true, + ); + expect( + forwardListHasRunningPort( + afterBothDownForwardList.stdout, + SANDBOX_NAME, + HERMES_DASHBOARD_PORT, + ), + ).toBe(true); + + for (const dashboardPort of hermesDashboardE2eEnabled() ? [HERMES_DASHBOARD_PORT] : []) { + const stopDashboardForward = await sandbox.openshell( + ["forward", "stop", dashboardPort, SANDBOX_NAME], + { + artifactName: "phase-5-stop-hermes-dashboard-forward-before-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(stopDashboardForward.exitCode, resultText(stopDashboardForward)).toBe(0); + + const dashboardDown = await host.command( + "curl", + ["-sf", "--max-time", "3", `http://127.0.0.1:${dashboardPort}/`], + { + artifactName: "phase-5-hermes-dashboard-host-down-after-forward-stop", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(dashboardDown.exitCode, resultText(dashboardDown)).not.toBe(0); + + const recoverDashboardForward = await host.command( + "nemohermes", + [SANDBOX_NAME, "recover"], + { + artifactName: "phase-5-nemohermes-recover-dashboard-forward", + env: commandEnv(), + timeoutMs: 180_000, + }, + ); + expect(recoverDashboardForward.exitCode, resultText(recoverDashboardForward)).toBe(0); + + const recoveredDashboard = await host.command( + "curl", + [ + "-sS", + "-L", + "--max-time", + "10", + "-o", + "/tmp/hermes-dashboard-recovered-vitest-body", + "-w", + "%{http_code}", + `http://127.0.0.1:${dashboardPort}/`, + ], + { + artifactName: "phase-5-hermes-dashboard-host-after-forward-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(recoveredDashboard.exitCode, resultText(recoveredDashboard)).toBe(0); + expect(httpStatusOk(recoveredDashboard.stdout)).toBe(true); + + const recoveredDashboardBody = await host.command( + "sh", + ["-lc", "cat /tmp/hermes-dashboard-recovered-vitest-body"], + { + artifactName: "phase-5-hermes-dashboard-host-after-forward-recover-body", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(recoveredDashboardBody.exitCode, resultText(recoveredDashboardBody)).toBe(0); + expect(resultText(recoveredDashboardBody)).toMatch( + /([^<]*Hermes|id=["']root["']|Hermes Dashboard|<html)/i, + ); + + const statusAfterDashboardRecover = await host.command( + "nemohermes", + [SANDBOX_NAME, "status"], + { + artifactName: "phase-5-nemohermes-status-after-dashboard-forward-recover", + env: commandEnv(), + timeoutMs: 60_000, + }, + ); + expect(statusAfterDashboardRecover.exitCode, resultText(statusAfterDashboardRecover)).toBe( + 0, + ); + expect(resultText(statusAfterDashboardRecover)).toMatch(/Ready/i); + expect(resultText(statusAfterDashboardRecover)).toMatch( + /Inference(?: \([^)]+\))?: healthy/i, + ); + } + } else { + expect(beforePid1.stdout).toContain("/opt/openshell/bin/openshell-sandbox"); + expect(beforeGateway.owner).toBe("sandbox"); + + const startupSupervisor = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + String.raw`ps -eo user=,pid=,ppid=,args= | awk '$1 == "sandbox" && $3 == 1 && ($4 ~ /(^|\/)(bash|nemoclaw-start)$/) && index($0, "nemoclaw-start") { print $1 " " $2 " " $3; found = 1; exit } END { exit found ? 0 : 1 }'`, + ), + { + artifactName: "phase-5-openshell-managed-hermes-supervisor", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(startupSupervisor.exitCode, resultText(startupSupervisor)).toBe(0); + const supervisor = parseGatewayProcess(startupSupervisor.stdout); + expect(supervisor.owner).toBe("sandbox"); + expect(supervisor.ppid).toBe("1"); + expect(beforeGateway.ppid).toBe(supervisor.pid); + const supervisorIdentityScript = trustedSandboxShellScript( + `python3 -c 'from pathlib import Path; import sys; pid=sys.argv[1]; text=Path("/proc/" + pid + "/stat").read_text(); tail=text.rsplit(")", 1)[1].split(); cmd=Path("/proc/" + pid + "/cmdline").read_bytes().replace(b"\\0", b" ").decode(); print(pid + " " + tail[19] + " " + cmd)' ${shellQuote(supervisor.pid)}`, + ); + const beforeSupervisorIdentity = await sandbox.execShell( + SANDBOX_NAME, + supervisorIdentityScript, + { + artifactName: "phase-5-managed-supervisor-identity-before-restart", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(beforeSupervisorIdentity.exitCode, resultText(beforeSupervisorIdentity)).toBe(0); + + const managedEnvBackup = `/tmp/hermes-managed-env-before-${Date.now()}`; + const introduceManagedRawSecret = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `backup=${shellQuote(managedEnvBackup)}`, + 'cp /sandbox/.hermes/.env "$backup"', + 'printf "\\nNEMOCLAW_E2E_SECRET_TOKEN=raw-managed-restart-secret\\n" >> /sandbox/.hermes/.env', + ].join("; "), + ), + { + artifactName: "phase-5-managed-hermes-introduce-raw-secret", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(introduceManagedRawSecret.exitCode, resultText(introduceManagedRawSecret)).toBe(0); + + const refuseManagedRawSecret = await host.command( + "nemohermes", + [SANDBOX_NAME, "gateway", "restart", "--quiet"], + { + artifactName: "phase-5-managed-hermes-refuse-raw-secret-restart", + env: commandEnv(), + timeoutMs: 180_000, + }, + ); + expect(refuseManagedRawSecret.exitCode, resultText(refuseManagedRawSecret)).not.toBe(0); + expect(resultText(refuseManagedRawSecret)).toMatch( + /secret.boundary refusal|SECRET_BOUNDARY_REFUSED/i, + ); + + const afterManagedRefusal = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-managed-hermes-gateway-after-boundary-refusal", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterManagedRefusal.exitCode, resultText(afterManagedRefusal)).toBe(0); + expect(parseGatewayProcess(afterManagedRefusal.stdout).pid).toBe(beforeGateway.pid); + + const restoreManagedEnv = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `backup=${shellQuote(managedEnvBackup)}`, + 'cat "$backup" > /sandbox/.hermes/.env', + 'rm -f "$backup"', + ].join("; "), + ), + { + artifactName: "phase-5-managed-hermes-restore-env", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(restoreManagedEnv.exitCode, resultText(restoreManagedEnv)).toBe(0); + + const stopApiForward = await sandbox.openshell(["forward", "stop", "8642", SANDBOX_NAME], { + artifactName: "phase-5-stop-managed-hermes-api-forward", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(stopApiForward.exitCode, resultText(stopApiForward)).toBe(0); + + const restartManagedGateway = await host.command( + "nemohermes", + [SANDBOX_NAME, "gateway", "restart"], + { + artifactName: "phase-5-restart-openshell-managed-hermes-gateway", + env: commandEnv(), + timeoutMs: 180_000, + }, + ); + expect(restartManagedGateway.exitCode, resultText(restartManagedGateway)).toBe(0); + expect(resultText(restartManagedGateway)).toContain("Gateway restarted"); + expect(resultText(restartManagedGateway)).toContain("health passed"); + expect(resultText(restartManagedGateway)).toContain("forwards checked/recovered"); + + const afterManagedRestart = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-managed-hermes-gateway-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterManagedRestart.exitCode, resultText(afterManagedRestart)).toBe(0); + const restartedManagedGateway = parseGatewayProcess(afterManagedRestart.stdout); + expect(restartedManagedGateway.owner).toBe("sandbox"); + expect(restartedManagedGateway.ppid).toBe(supervisor.pid); + expect(restartedManagedGateway.pid).not.toBe(beforeGateway.pid); + + const afterManagedRestartPid1 = await sandbox.execShell(SANDBOX_NAME, pid1IdentityScript, { + artifactName: "phase-5-managed-pid1-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterManagedRestartPid1.exitCode, resultText(afterManagedRestartPid1)).toBe(0); + expect(afterManagedRestartPid1.stdout.trim()).toBe(beforePid1.stdout.trim()); + const afterManagedRestartSupervisor = await sandbox.execShell( + SANDBOX_NAME, + supervisorIdentityScript, + { + artifactName: "phase-5-managed-supervisor-identity-after-restart", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect( + afterManagedRestartSupervisor.exitCode, + resultText(afterManagedRestartSupervisor), + ).toBe(0); + expect(afterManagedRestartSupervisor.stdout.trim()).toBe( + beforeSupervisorIdentity.stdout.trim(), + ); + + const stopGateway = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `pid=${shellQuote(restartedManagedGateway.pid)}`, + 'kill -TERM "$pid"', + 'for _i in 1 2 3 4 5; do state=$(ps -p "$pid" -o stat= 2>/dev/null || true); case "$state" in \'\'|Z*) echo GATEWAY_STOPPED; exit 0 ;; esac; sleep 1; done', + "echo GATEWAY_STOP_FAILED >&2; exit 1", + ].join("; "), + ), + { + artifactName: "phase-5-stop-managed-hermes-gateway", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(stopGateway.exitCode, resultText(stopGateway)).toBe(0); + expect(stopGateway.stdout).toContain("GATEWAY_STOPPED"); + + const recoverManagedGateway = await host.command("nemohermes", [SANDBOX_NAME, "recover"], { + artifactName: "phase-5-recover-openshell-managed-hermes-gateway", + env: commandEnv(), + timeoutMs: 180_000, + }); + expect(recoverManagedGateway.exitCode, resultText(recoverManagedGateway)).toBe(0); + + const afterRecoverProcess = await sandbox.execShell(SANDBOX_NAME, gatewayProcessScript, { + artifactName: "phase-5-managed-hermes-gateway-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRecoverProcess.exitCode, resultText(afterRecoverProcess)).toBe(0); + recoveredGateway = parseGatewayProcess(afterRecoverProcess.stdout); + expect(recoveredGateway.owner).toBe("sandbox"); + expect(recoveredGateway.ppid).toBe(supervisor.pid); + expect(recoveredGateway.pid).not.toBe(restartedManagedGateway.pid); + + const afterRecoverPid1 = await sandbox.execShell(SANDBOX_NAME, pid1IdentityScript, { + artifactName: "phase-5-managed-pid1-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(afterRecoverPid1.exitCode, resultText(afterRecoverPid1)).toBe(0); + expect(afterRecoverPid1.stdout.trim()).toBe(beforePid1.stdout.trim()); + const afterRecoverSupervisor = await sandbox.execShell( + SANDBOX_NAME, + supervisorIdentityScript, + { + artifactName: "phase-5-managed-supervisor-identity-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(afterRecoverSupervisor.exitCode, resultText(afterRecoverSupervisor)).toBe(0); + expect(afterRecoverSupervisor.stdout.trim()).toBe(beforeSupervisorIdentity.stdout.trim()); + + const managedHealth = await host.command( + "curl", + ["-sf", "--max-time", "10", HERMES_HOST_HEALTH_URL], + { + artifactName: "phase-5-managed-hermes-host-health-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(managedHealth.exitCode, resultText(managedHealth)).toBe(0); + expect(resultText(managedHealth)).toMatch(/"ok"/i); + + const managedForwardList = await sandbox.openshell(["forward", "list"], { + artifactName: "phase-5-managed-forward-list-after-recover", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(managedForwardList.exitCode, resultText(managedForwardList)).toBe(0); + expect(forwardListHasRunningPort(managedForwardList.stdout, SANDBOX_NAME, "8642")).toBe(true); + for (const dashboardPort of hermesDashboardE2eEnabled() ? [HERMES_DASHBOARD_PORT] : []) { + expect( + forwardListHasRunningPort(managedForwardList.stdout, SANDBOX_NAME, dashboardPort), + ).toBe(true); + } + } + + // Phase 6: live inference through both the external provider and the // sandbox's inference.local route. const directChat = await retryHostedInference( "direct NVIDIA Endpoints chat", @@ -497,7 +1180,7 @@ test.skipIf(!shouldRunLiveE2E())( allowedHosts: ["inference-api.nvidia.com"], }), { - artifactName: `phase-5-direct-nvidia-chat-attempt-${attempt}`, + artifactName: `phase-6-direct-nvidia-chat-attempt-${attempt}`, body: chatPayload( hosted.model, "Reply with exactly one word: PONG", @@ -539,7 +1222,7 @@ test.skipIf(!shouldRunLiveE2E())( "https://inference.local/v1/chat/completions", ], { - artifactName: `phase-5-inference-local-chat-attempt-${attempt}`, + artifactName: `phase-6-inference-local-chat-attempt-${attempt}`, env: commandEnv(), timeoutMs: 120_000, }, @@ -563,9 +1246,9 @@ test.skipIf(!shouldRunLiveE2E())( ); expectPong("Hermes sandbox inference.local chat", sandboxChatJson); - // Phase 6: CLI operations and agent manifest regression. + // Phase 7: CLI operations and agent manifest regression. const logs = await host.command("nemoclaw", [SANDBOX_NAME, "logs"], { - artifactName: "phase-6-nemoclaw-logs", + artifactName: "phase-7-nemoclaw-logs", env: commandEnv(), timeoutMs: 60_000, }); @@ -583,7 +1266,7 @@ test.skipIf(!shouldRunLiveE2E())( `console.log('hermes_display:', loadAgent('hermes').displayName);`, ], { - artifactName: "phase-6-agent-manifest-check", + artifactName: "phase-7-agent-manifest-check", env: commandEnv(), timeoutMs: 30_000, }, @@ -593,21 +1276,114 @@ test.skipIf(!shouldRunLiveE2E())( expect(manifestCheck.stdout).toMatch(/hermes_display:.*Hermes/); expect(manifestCheck.stdout).toMatch(/agents:.*(openclaw.*hermes|hermes.*openclaw)/); + // Phase 8: locked Hermes config drift is refused instead of adopted by the + // documented root-entrypoint lifecycle-control topology. The managed + // topology proves explicit restart plus boundary refusal above; this phase + // retains the stronger root-owned restart-seal drift contract. + if (rootSupervisorTopology) { + const shieldsUp = await host.command("nemohermes", [SANDBOX_NAME, "shields", "up"], { + artifactName: "phase-8-nemohermes-shields-up", + env: commandEnv(), + timeoutMs: 120_000, + }); + expect(shieldsUp.exitCode, resultText(shieldsUp)).toBe(0); + + const lockedDriftMarker = `issue_2426_locked_${Date.now()}`; + try { + const introduceLockedDrift = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + `marker=${shellQuote(lockedDriftMarker)}`, + 'for path in /sandbox/.hermes /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash; do chattr -i "$path" 2>/dev/null || true; done', + "chmod u+w /sandbox/.hermes/.env", + 'printf "\\nNEMOCLAW_E2E_LOCKED_DRIFT_MARKER=%s\\n" "$marker" >> /sandbox/.hermes/.env', + "chown root:root /sandbox/.hermes /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + "chmod 755 /sandbox/.hermes", + "chmod 444 /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + "echo LOCKED_DRIFT_READY", + ].join("; "), + ), + { + artifactName: "phase-8-introduce-locked-hermes-drift", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(introduceLockedDrift.exitCode, resultText(introduceLockedDrift)).toBe(0); + expect(introduceLockedDrift.stdout).toContain("LOCKED_DRIFT_READY"); + + const lockedRestart = await host.command( + "nemohermes", + [SANDBOX_NAME, "gateway", "restart", "--quiet"], + { + artifactName: "phase-8-nemohermes-gateway-restart-locked-drift", + env: commandEnv(), + timeoutMs: 180_000, + }, + ); + expect(lockedRestart.exitCode, resultText(lockedRestart)).not.toBe(0); + expect(resultText(lockedRestart)).toMatch( + /config hash mismatch|GATEWAY_CONFIG_HASH_MISMATCH/, + ); + + const afterLockedRefusalProcess = await sandbox.execShell( + SANDBOX_NAME, + gatewayProcessScript, + { + artifactName: "phase-8-hermes-gateway-process-after-locked-refusal", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(afterLockedRefusalProcess.exitCode, resultText(afterLockedRefusalProcess)).toBe(0); + const gatewayAfterLockedRefusal = parseGatewayProcess(afterLockedRefusalProcess.stdout); + expect(gatewayAfterLockedRefusal.owner).toBe("gateway"); + expect(gatewayAfterLockedRefusal.pid).toBe(recoveredGateway.pid); + } finally { + const restoreLockedDrift = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript( + [ + "set -eu", + 'for path in /sandbox/.hermes /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash; do chattr -i "$path" 2>/dev/null || true; done', + "chmod u+w /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + 'python3 -c \'from pathlib import Path; p=Path("/sandbox/.hermes/.env"); lines=[line for line in p.read_text(encoding="utf-8").splitlines() if not line.startswith("NEMOCLAW_E2E_LOCKED_DRIFT_MARKER=")]; p.write_text("\\n".join(lines).rstrip()+"\\n", encoding="utf-8")\'', + "sha256sum /sandbox/.hermes/config.yaml /sandbox/.hermes/.env > /etc/nemoclaw/hermes.config-hash", + "sha256sum /sandbox/.hermes/config.yaml /sandbox/.hermes/.env > /sandbox/.hermes/.config-hash", + "chown root:root /sandbox/.hermes /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + "chmod 755 /sandbox/.hermes", + "chmod 444 /sandbox/.hermes/config.yaml /sandbox/.hermes/.env /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + "echo OK", + ].join("; "), + ), + { + artifactName: "phase-8-restore-locked-hermes-drift", + env: commandEnv(), + timeoutMs: 30_000, + }, + ); + expect(restoreLockedDrift.exitCode, resultText(restoreLockedDrift)).toBe(0); + expect(restoreLockedDrift.stdout).toContain("OK"); + } + } + const securityPosture = securityPostureEnabled() ? await assertSecurityPosture(host, sandbox, SANDBOX_NAME, "hermes") : null; - // Phase 8: explicit cleanup and post-destroy registry proof. + // Phase 9: explicit cleanup and post-destroy registry proof. if (process.env.NEMOCLAW_E2E_KEEP_SANDBOX !== "1") { const destroy = await host.command("nemoclaw", [SANDBOX_NAME, "destroy", "--yes"], { - artifactName: "phase-8-nemoclaw-destroy", + artifactName: "phase-9-nemoclaw-destroy", env: commandEnv(), timeoutMs: 120_000, }); expect(destroy.exitCode, resultText(destroy)).toBe(0); await bestEffort(() => sandbox.openshell(["gateway", "destroy", "-g", "nemoclaw"], { - artifactName: "phase-8-openshell-gateway-destroy", + artifactName: "phase-9-openshell-gateway-destroy", env: commandEnv(), timeoutMs: 60_000, }), diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index 5fb72b05212..6c06d22f813 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -81,6 +81,8 @@ test.skipIf(!shouldRunLiveE2E())( : []; const switched = await runHermesInferenceSetWithRetry(host, apiKey, compatibleMetadataArgs); expect(switched.exitCode, resultText(switched)).toBe(0); + expect(resultText(switched)).not.toContain("writing the in-sandbox config failed"); + expect(resultText(switched)).toContain(`Inference route synced for '${SANDBOX_NAME}'`); const pidAfter = await hermesGatewayPid(sandbox, "pid-after"); maybeAssertPidStable(pidBefore, pidAfter, (actual, expected) => expect(actual).toBe(expected)); diff --git a/test/e2e/live/hermes-sandbox-secret-boundary.test.ts b/test/e2e/live/hermes-sandbox-secret-boundary.test.ts index 5569931ea66..1f261e44115 100644 --- a/test/e2e/live/hermes-sandbox-secret-boundary.test.ts +++ b/test/e2e/live/hermes-sandbox-secret-boundary.test.ts @@ -14,6 +14,7 @@ import { expect, test } from "../fixtures/e2e-test.ts"; const BUILD_TIMEOUT_MS = 10 * 60_000; const RUN_TIMEOUT_MS = 60_000; +const CONTROL_NONCE = "0".repeat(64); const RAW_SECRET_SENTINEL = "SENTINEL_RAW_SECRET_VALUE"; const RAW_REFRESH_TOKEN = "raw-refresh-token"; @@ -281,10 +282,6 @@ if missing_config: const RUNTIME_API_KEY_PROBE_SCRIPT = String.raw` set -euo pipefail - if ! /usr/local/bin/nemoclaw-start true >/tmp/nemoclaw-start-api-key-probe.log 2>&1; then - cat /tmp/nemoclaw-start-api-key-probe.log >&2 - exit 1 - fi python3 - <<'PY' import hashlib import json @@ -495,6 +492,61 @@ async function inspectImageBoundary(probe: DockerProbe, image: string): Promise< ).toBe(0); } +async function inspectGatewayControlBoundary(probe: DockerProbe, image: string): Promise<void> { + const rootProbe = await probe.run( + [ + "run", + "--rm", + "--user", + "root", + "--entrypoint", + "/bin/sh", + image, + "-lc", + String.raw` +set -eu +[ "$(stat -c '%U:%G %a' /usr/local/bin/nemoclaw-gateway-control)" = "root:root 700" ] +[ "$(stat -c '%U:%G %a' /usr/local/lib/nemoclaw/managed-gateway-control.py)" = "root:root 500" ] +[ "$(stat -c '%U:%G %a' /usr/local/lib/nemoclaw/state-dir-guard.py)" = "root:root 500" ] +[ "$(stat -c '%U:%G %a' /usr/local/lib/nemoclaw/gateway-supervisor.sh)" = "root:root 444" ] +id -nG gateway | tr ' ' '\n' | grep -qx sandbox +id -nG root | tr ' ' '\n' | grep -qx sandbox +rc=0 +/usr/local/bin/nemoclaw-gateway-control probe '${CONTROL_NONCE}' >/tmp/gateway-control-probe.out 2>&1 || rc=$? +cat /tmp/gateway-control-probe.out +[ "$rc" -ne 0 ] +grep -qx SUPERVISOR_UNAVAILABLE /tmp/gateway-control-probe.out +`, + ], + { artifactName: "inspect-hermes-gateway-control-root-boundary", timeoutMs: RUN_TIMEOUT_MS }, + ); + expect( + rootProbe.exitCode, + `Hermes image should preserve root-only helper modes, group access, and root probe execution\n${resultText(rootProbe)}`, + ).toBe(0); + + const sandboxProbe = await probe.run( + [ + "run", + "--rm", + "--user", + "sandbox", + "--entrypoint", + "/usr/local/bin/nemoclaw-gateway-control", + image, + "probe", + CONTROL_NONCE, + ], + { artifactName: "inspect-hermes-gateway-control-sandbox-refusal", timeoutMs: RUN_TIMEOUT_MS }, + ); + expect( + sandboxProbe.exitCode, + "Hermes sandbox user must not execute the root-only gateway control helper", + ).not.toBe(0); + expect(resultText(sandboxProbe)).toMatch(/permission denied/iu); + expect(resultText(sandboxProbe)).not.toContain("PRIVILEGED_CONTROL_UNAVAILABLE"); +} + async function inspectManagedToolBoundary(probe: DockerProbe, image: string): Promise<void> { const result = await probe.run( ["run", "--rm", "--entrypoint", "python3", image, "-c", MANAGED_TOOL_INSPECTION_SCRIPT], @@ -621,7 +673,16 @@ async function probeRuntimeApiServerKey( label: string, ): Promise<RuntimeApiKeyProbe> { const result = await probe.run( - ["run", "--rm", "--entrypoint", "/bin/bash", image, "-lc", RUNTIME_API_KEY_PROBE_SCRIPT], + [ + "run", + "--rm", + "--entrypoint", + "/usr/local/bin/nemoclaw-start", + image, + "/bin/bash", + "-lc", + RUNTIME_API_KEY_PROBE_SCRIPT, + ], { artifactName: `runtime-api-server-key-${label}`, returnRaw: true, @@ -700,6 +761,7 @@ liveTest( "Hermes .env in the sandbox image is a real file with no baked API_SERVER_KEY or raw external secret-shaped values", "Hermes final image imports python-multipart from /opt/hermes/.venv and has no gcc, g++, or make commands", "Hermes final image can allocate a PTY through /dev/pts", + "Hermes final image enforces root-only gateway-control modes and sandbox group membership", "Hermes startup mints a unique API_SERVER_KEY per sandbox and refreshes strict and compatibility config hashes", "Hermes config preserves api_server remote platform toolsets and does not use no_mcp", "managed-tool image keeps gateway auth tokens out of sandbox env/config while preserving gateway URLs/config", @@ -742,6 +804,7 @@ liveTest( }); await inspectImageBoundary(probe, image); + await inspectGatewayControlBoundary(probe, image); await inspectManagedToolBoundary(probe, managedImage); await expectRuntimeApiServerKeyPerSandbox(probe, image); await expectStartupRejectsEnvFileEntry( @@ -786,6 +849,7 @@ liveTest( managedImage, assertions: { imageEnvSecretBoundaryVerified: true, + gatewayControlImageBoundaryVerified: true, runtimeApiServerKeyPerSandboxVerified: true, imageRemoteToolsetsVerified: true, managedToolGatewayAuthBoundaryVerified: true, diff --git a/test/e2e/live/sandbox-operations.test.ts b/test/e2e/live/sandbox-operations.test.ts index 35e030a1f83..d0472fa7657 100644 --- a/test/e2e/live/sandbox-operations.test.ts +++ b/test/e2e/live/sandbox-operations.test.ts @@ -208,7 +208,11 @@ function parseOpenClawAgentText(raw: string): string { return parts.join("\n"); } -async function assertAgentCanAnswer(host: HostCliClient, sandboxName: string): Promise<void> { +async function assertAgentCanAnswer( + host: HostCliClient, + sandboxName: string, + artifactName = "tc-sbx-02-nemoclaw-agent-json", +): Promise<void> { const sessionId = `e2e-sbx-02-${Date.now()}-${process.pid}`; const result = await host.nemoclaw( [ @@ -223,7 +227,7 @@ async function assertAgentCanAnswer(host: HostCliClient, sandboxName: string): P "What is 6 multiplied by 7? Reply with only the integer, no extra words.", ], { - artifactName: "tc-sbx-02-nemoclaw-agent-json", + artifactName, env: buildAvailabilityProbeEnv(), timeoutMs: 120_000, }, @@ -233,6 +237,72 @@ async function assertAgentCanAnswer(host: HostCliClient, sandboxName: string): P expect(containsInteger42Answer(reply), resultText(result)).toBe(true); } +async function assertForcedGatewayRestart( + host: HostCliClient, + sandbox: SandboxClient, + sandboxName: string, +): Promise<void> { + const identityScript = [ + "set -eu", + "read -r pid starttime extra </tmp/nemoclaw-gateway.pid", + "case \"$pid\" in ''|*[!0-9]*) echo INVALID_GATEWAY_PID >&2; exit 1 ;; esac", + "case \"$starttime\" in ''|*[!0-9]*) echo INVALID_GATEWAY_STARTTIME >&2; exit 1 ;; esac", + '[ -z "$extra" ] || { echo INVALID_GATEWAY_PID_RECORD >&2; exit 1; }', + 'actual_start=$(python3 -c \'import sys; from pathlib import Path; text=Path(f"/proc/{sys.argv[1]}/stat").read_text(); tail=text.rsplit(")", 1)[1].split(); print(tail[19])\' "$pid")', + '[ "$actual_start" = "$starttime" ] || { echo GATEWAY_PID_REUSED >&2; exit 1; }', + "pid1_argv0=$(tr '\\0' '\\n' </proc/1/cmdline | sed -n '1p')", + "pid1_cmdline=$(tr '\\0' ' ' </proc/1/cmdline)", + 'if [ "$pid1_argv0" = /opt/openshell/bin/openshell-sandbox ]; then expected_user=sandbox; topology=openshell-managed; else case "$pid1_cmdline" in *nemoclaw-start*) expected_user=gateway; topology=direct-root ;; *) echo "UNEXPECTED_PID1=$pid1_cmdline" >&2; exit 1 ;; esac; fi', + 'user=$(ps -p "$pid" -o user= | tr -d " ")', + '[ "$user" = "$expected_user" ] || { echo "UNEXPECTED_GATEWAY_USER=$user EXPECTED=$expected_user TOPOLOGY=$topology" >&2; exit 1; }', + 'comm=$(ps -p "$pid" -o comm= | tr -d " ")', + 'case "$comm" in openclaw*) ;; *) echo "UNEXPECTED_GATEWAY_COMM=$comm" >&2; exit 1 ;; esac', + 'python3 -c \'from pathlib import Path; text=Path("/proc/1/stat").read_text(); tail=text.rsplit(")", 1)[1].split(); print("PID1_START=" + tail[19])\'', + 'printf "TOPOLOGY=%s\\n" "$topology"', + 'printf "GATEWAY=%s:%s:%s\\n" "$user" "$pid" "$starttime"', + ].join("; "); + const before = await execInSandbox( + sandbox, + sandboxName, + identityScript, + "tc-sbx-08b-gateway-identity-before-forced-restart", + ); + expectExitZero(before, "OpenClaw gateway identity before forced restart"); + expect(before.stdout, resultText(before)).toMatch(/GATEWAY=(?:gateway|sandbox):[0-9]+:[0-9]+/); + + const restart = await host.nemoclaw([sandboxName, "gateway", "restart"], { + artifactName: "tc-sbx-08b-openclaw-forced-gateway-restart", + env: buildAvailabilityProbeEnv(), + timeoutMs: 180_000, + }); + expectExitZero(restart, `nemoclaw ${sandboxName} gateway restart`); + expect(resultText(restart)).toContain("Gateway restarted"); + expect(resultText(restart)).toContain("health passed"); + + const after = await execInSandbox( + sandbox, + sandboxName, + identityScript, + "tc-sbx-08b-gateway-identity-after-forced-restart", + ); + expectExitZero(after, "OpenClaw gateway identity after forced restart"); + expect(after.stdout, resultText(after)).toMatch(/GATEWAY=(?:gateway|sandbox):[0-9]+:[0-9]+/); + + const beforeGateway = before.stdout.match(/GATEWAY=(gateway|sandbox):([0-9]+:[0-9]+)/); + const afterGateway = after.stdout.match(/GATEWAY=(gateway|sandbox):([0-9]+:[0-9]+)/); + const beforeIdentity = beforeGateway?.[2]; + const afterIdentity = afterGateway?.[2]; + const beforePid1 = before.stdout.match(/PID1_START=([0-9]+)/)?.[1]; + const afterPid1 = after.stdout.match(/PID1_START=([0-9]+)/)?.[1]; + expect(beforeIdentity).toBeTruthy(); + expect(afterIdentity).toBeTruthy(); + expect(afterGateway?.[1]).toBe(beforeGateway?.[1]); + expect(afterIdentity).not.toBe(beforeIdentity); + expect(afterPid1).toBe(beforePid1); + + await assertAgentCanAnswer(host, sandboxName, "tc-sbx-08b-agent-json-after-forced-restart"); +} + async function assertAgentJsonNonzeroExit(host: HostCliClient, sandboxName: string): Promise<void> { const invalidFlag = await host.nemoclaw( [sandboxName, "agent", "--json", "--nemoclaw-e2e-invalid-openclaw-agent-flag"], @@ -351,12 +421,31 @@ async function assertProcessRecovery( sandbox: SandboxClient, sandboxName: string, ): Promise<void> { - await execInSandbox( + const kill = await execInSandbox( sandbox, sandboxName, - "pkill -9 -f 'openclaw gateway' 2>/dev/null || kill -9 $(pgrep -f 'openclaw gateway') 2>/dev/null || ps aux | awk '/openclaw.*gateway/ && !/awk/ {print $2}' | xargs -r kill -9 2>/dev/null; echo PROCESS_KILL_PROBED", + [ + "set -eu", + "read -r pid starttime extra </tmp/nemoclaw-gateway.pid", + "case \"$pid\" in ''|*[!0-9]*) echo INVALID_GATEWAY_PID >&2; exit 1 ;; esac", + "case \"$starttime\" in ''|*[!0-9]*) echo INVALID_GATEWAY_STARTTIME >&2; exit 1 ;; esac", + '[ -z "$extra" ] || { echo INVALID_GATEWAY_PID_RECORD >&2; exit 1; }', + 'actual_start=$(python3 -c \'import sys; from pathlib import Path; text=Path(f"/proc/{sys.argv[1]}/stat").read_text(); tail=text.rsplit(")", 1)[1].split(); print(tail[19])\' "$pid")', + '[ "$actual_start" = "$starttime" ] || { echo GATEWAY_PID_REUSED >&2; exit 1; }', + "pid1_argv0=$(tr '\\0' '\\n' </proc/1/cmdline | sed -n '1p')", + "pid1_cmdline=$(tr '\\0' ' ' </proc/1/cmdline)", + 'if [ "$pid1_argv0" = /opt/openshell/bin/openshell-sandbox ]; then expected_user=sandbox; else case "$pid1_cmdline" in *nemoclaw-start*) expected_user=gateway ;; *) echo "UNEXPECTED_PID1=$pid1_cmdline" >&2; exit 1 ;; esac; fi', + 'user=$(ps -p "$pid" -o user= | tr -d " ")', + '[ "$user" = "$expected_user" ] || { echo "UNEXPECTED_GATEWAY_USER=$user EXPECTED=$expected_user" >&2; exit 1; }', + 'comm=$(ps -p "$pid" -o comm= | tr -d " ")', + 'case "$comm" in openclaw*) ;; *) echo "UNEXPECTED_GATEWAY_COMM=$comm" >&2; exit 1 ;; esac', + 'kill -9 "$pid"', + 'printf "KILLED_GATEWAY=%s:%s:%s\\n" "$user" "$pid" "$starttime"', + ].join("; "), "tc-sbx-08-kill-openclaw-gateway", ); + expectExitZero(kill, "kill exact OpenClaw gateway identity"); + expect(kill.stdout, resultText(kill)).toMatch(/KILLED_GATEWAY=(?:gateway|sandbox):[0-9]+:[0-9]+/); await new Promise((resolve) => setTimeout(resolve, 5_000)); const status = await host.nemoclaw([sandboxName, "status"], { artifactName: "tc-sbx-08-status-recovers-process", @@ -529,6 +618,7 @@ liveTest( "TC-SBX-06 status recovers after gateway container kill", "TC-SBX-07 list rebuilds registry from live state", "TC-SBX-08 status recovers killed in-sandbox OpenClaw gateway process", + "TC-SBX-08b forced OpenClaw gateway restart replaces only the gateway and preserves live inference", "TC-SBX-09 tmux and PTY lifecycle work inside sandbox", "TC-SBX-10 two sandboxes list with model/provider metadata", "TC-SBX-11 sandboxes cannot reach each other by hostname", @@ -566,6 +656,7 @@ liveTest( await assertLogsStream(host, SANDBOX_A); await assertTmuxPtyFlow(sandbox, SANDBOX_A); await assertRegistryRebuild(host, SANDBOX_A); + await assertForcedGatewayRestart(host, sandbox, SANDBOX_A); await assertProcessRecovery(host, sandbox, SANDBOX_A); await onboardSandbox(host, cleanup, SANDBOX_B, "tc-sbx-10-onboard-sandbox-b", hosted, { diff --git a/test/e2e/live/sandbox-rebuild.test.ts b/test/e2e/live/sandbox-rebuild.test.ts index fc0d478bb90..292042dae8a 100644 --- a/test/e2e/live/sandbox-rebuild.test.ts +++ b/test/e2e/live/sandbox-rebuild.test.ts @@ -33,7 +33,6 @@ const SANDBOX_NAME = .filter(Boolean) .join("-"); const TEST_TIMEOUT_MS = Number(process.env.NEMOCLAW_E2E_TIMEOUT_SECONDS ?? 1_200) * 1_000; -const CONNECT_PROBE_TIMEOUT_MS = 30_000; const STATUS_TIMEOUT_MS = 60_000; const ONBOARD_TIMEOUT_MS = TEST_TIMEOUT_MS; const REBUILD_TIMEOUT_MS = TEST_TIMEOUT_MS; @@ -181,28 +180,14 @@ test.skipIf(!shouldRunLiveE2E())( agentVersion: readRegistrySandboxEntry(SANDBOX_NAME).agentVersion, }); - const connect = await host.command( - "bash", - [ - "-lc", - 'timeout 10 "$1" "$2" connect <<<"exit"', - "connect-stale", - host.commandPath, - SANDBOX_NAME, - ], - { - artifactName: "phase-4-connect-stale-warning", - env: sandboxRebuildEnv(apiKey), - redactionValues: [apiKey], - timeoutMs: CONNECT_PROBE_TIMEOUT_MS, - }, - ); - if (!/rebuild/i.test(resultText(connect))) { - await artifacts.writeText( - "phase-4-connect-stale-warning-note.txt", - "No rebuild warning was observed; former bash treated this as acceptable when the sandbox is not live.\n", - ); - } + const staleStatus = await host.nemoclaw([SANDBOX_NAME, "status"], { + artifactName: "phase-4-status-stale-warning", + env: sandboxRebuildEnv(apiKey), + redactionValues: [apiKey], + timeoutMs: STATUS_TIMEOUT_MS, + }); + expect(staleStatus.exitCode, resultText(staleStatus)).toBe(0); + expect(resultText(staleStatus)).toMatch(/rebuild/i); await lifecycle.rebuildSandbox(instance, { artifactName: "phase-5-nemoclaw-rebuild", diff --git a/test/e2e/support/hermes-dashboard-workflow-boundary.test.ts b/test/e2e/support/hermes-dashboard-workflow-boundary.test.ts index ae2ab4ca614..3726080edea 100644 --- a/test/e2e/support/hermes-dashboard-workflow-boundary.test.ts +++ b/test/e2e/support/hermes-dashboard-workflow-boundary.test.ts @@ -37,6 +37,12 @@ describe("Hermes dashboard workflow boundary", () => { "hermes-dashboard must enable Hermes dashboard coverage", ); + const misplacedDashboardMode = readHermesDashboardWorkflow(); + misplacedDashboardMode.jobs["hermes-e2e"].env!.NEMOCLAW_E2E_HERMES_DASHBOARD = "1"; + expect(validateHermesDashboardWorkflow(misplacedDashboardMode)).toContain( + "only hermes-dashboard may enable Hermes dashboard E2E coverage (found on hermes-e2e)", + ); + const execution = readHermesDashboardWorkflow(); execution.jobs["hermes-dashboard"].steps!.find( (step) => step.name === "Run Hermes dashboard live Vitest test", diff --git a/test/gateway-pid-recording.test.ts b/test/gateway-pid-recording.test.ts index 3ec77349b39..eece4e007c6 100644 --- a/test/gateway-pid-recording.test.ts +++ b/test/gateway-pid-recording.test.ts @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 // Producer-side coverage for the #4952 HEALTHCHECK fix: nemoclaw-start must -// record the live gateway PID in /tmp/nemoclaw-gateway.pid so the Docker -// HEALTHCHECK can confirm the actual gateway process is alive (not merely some -// process named `openclaw`) when the in-container curl probe cannot reach the -// dashboard port. The consumer side (the HEALTHCHECK reading this file) is +// record the live gateway PID/starttime in /tmp/nemoclaw-gateway.pid so the +// Docker HEALTHCHECK can confirm the actual gateway process is alive, rather +// than merely some process named `openclaw`, when the in-container curl probe +// cannot reach the dashboard port. The consumer side (the HEALTHCHECK reading this file) is // covered in test/sandbox-provisioning.test.ts. import { spawnSync } from "node:child_process"; @@ -35,7 +35,7 @@ function safeTmpHelpers(src: string): string { } describe("nemoclaw-start gateway PID recording for HEALTHCHECK (#4952)", () => { - it("record_gateway_pid writes the gateway PID to the file the HEALTHCHECK reads", () => { + it("record_gateway_pid writes the gateway PID and starttime the HEALTHCHECK reads", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gw-pid-")); try { @@ -46,13 +46,13 @@ describe("nemoclaw-start gateway PID recording for HEALTHCHECK (#4952)", () => { safeTmpHelpers(src), `GATEWAY_PID_FILE=${JSON.stringify(pidPath)}`, fn, - 'record_gateway_pid "12345"', + 'record_gateway_pid "12345" "987654"', ].join("\n"); const result = spawnSync("bash", ["-c", script], { encoding: "utf-8", timeout: 5000 }); expect(result.status).toBe(0); - expect(fs.readFileSync(pidPath, "utf-8").trim()).toBe("12345"); + expect(fs.readFileSync(pidPath, "utf-8").trim()).toBe("12345 987654"); expect((fs.statSync(pidPath).mode & 0o777).toString(8)).toBe("600"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); @@ -69,7 +69,7 @@ describe("nemoclaw-start gateway PID recording for HEALTHCHECK (#4952)", () => { safeTmpHelpers(src), "GATEWAY_PID_FILE=/nonexistent-dir/nemoclaw-gateway.pid", fn, - 'record_gateway_pid "12345"', + 'record_gateway_pid "12345" "987654"', ].join("\n"); const result = spawnSync("bash", ["-c", script], { encoding: "utf-8", timeout: 5000 }); diff --git a/test/gateway-supervisor-control.test.ts b/test/gateway-supervisor-control.test.ts new file mode 100644 index 00000000000..9099cb80c58 --- /dev/null +++ b/test/gateway-supervisor-control.test.ts @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +const REPO_ROOT = join(import.meta.dirname, ".."); +const SUPERVISOR_LIBRARY = join(REPO_ROOT, "scripts/lib/gateway-supervisor.sh"); +const CONTROL_HELPER = join(REPO_ROOT, "scripts/gateway-control.sh"); +const VALID_NONCE = "a".repeat(64); + +type CommandResult = { + status: number | null; + stdout: string; + stderr: string; +}; + +const temporaryDirectories: string[] = []; + +function temporaryDirectory(prefix: string): string { + const directory = mkdtempSync(join(tmpdir(), prefix)); + temporaryDirectories.push(directory); + return directory; +} + +function runSupervisorLibrary( + body: string, + request?: string, +): CommandResult & { controlDirectory: string } { + const controlDirectory = temporaryDirectory("nemoclaw-gateway-supervisor-"); + chmodSync(controlDirectory, 0o700); + for (const pendingRequest of request === undefined ? [] : [request]) { + writeFileSync(join(controlDirectory, "request"), pendingRequest, { mode: 0o600 }); + } + + const script = [ + "set -euo pipefail", + `export NEMOCLAW_GATEWAY_CONTROL_DIR=${JSON.stringify(controlDirectory)}`, + `source ${JSON.stringify(SUPERVISOR_LIBRARY)}`, + body, + ].join("\n"); + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + return { + controlDirectory, + status: result.status, + stdout: result.stdout.trim(), + stderr: result.stderr.trim(), + }; +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +describe("gateway supervisor request protocol", () => { + it.each([ + "restart", + "probe", + ])("accepts an exact versioned %s request and publishes a nonce-bound status", (action) => { + const result = runSupervisorLibrary( + [ + "GATEWAY_CONTROL_SIGNAL_PENDING=1", + "gateway_control_take_request", + 'printf "%s %s\\n" "$GATEWAY_CONTROL_NONCE" "$GATEWAY_CONTROL_ACTION"', + ].join("\n"), + `v1 ${VALID_NONCE} ${action}\n`, + ); + + expect(result).toMatchObject({ + status: 0, + stdout: `${VALID_NONCE} ${action}`, + stderr: "", + }); + const statusPath = join(result.controlDirectory, "status"); + expect(readFileSync(statusPath, "utf-8")).toBe(`v1 ${VALID_NONCE} accepted\n`); + expect(statSync(statusPath).mode & 0o777).toBe(0o600); + }); + + it.each([ + ["unsupported version", `v2 ${VALID_NONCE} restart\n`], + ["short nonce", "v1 abc restart\n"], + ["uppercase nonce", `v1 ${"A".repeat(64)} restart\n`], + ["unknown action", `v1 ${VALID_NONCE} replace\n`], + ["extra field", `v1 ${VALID_NONCE} recover unexpected\n`], + ])("rejects %s without accepting the request", (_label, request) => { + const result = runSupervisorLibrary( + [ + "GATEWAY_CONTROL_SIGNAL_PENDING=1", + "if gateway_control_take_request; then exit 90; fi", + 'test ! -e "$NEMOCLAW_GATEWAY_CONTROL_STATUS"', + 'printf "rejected\\n"', + ].join("\n"), + request, + ); + + expect(result).toMatchObject({ status: 0, stdout: "rejected", stderr: "" }); + }); + + it.each([ + ["recover", "ok", 101, 202], + ["probe", "already-running", 101, 101], + ])("publishes %s completion with the request nonce and removes the request", (action, detail, oldPid, newPid) => { + const result = runSupervisorLibrary( + [ + "GATEWAY_CONTROL_SIGNAL_PENDING=1", + "gateway_control_take_request", + `gateway_control_complete ${detail} ${oldPid} ${newPid}`, + 'test ! -e "$NEMOCLAW_GATEWAY_CONTROL_REQUEST"', + 'cat "$NEMOCLAW_GATEWAY_CONTROL_STATUS"', + ].join("\n"), + `v1 ${VALID_NONCE} ${action}\n`, + ); + + expect(result).toMatchObject({ + status: 0, + stdout: `v1 ${VALID_NONCE} complete ${detail} ${oldPid} ${newPid}`, + stderr: "", + }); + }); + + it("maps an unknown failure detail to the closed internal status", () => { + const result = runSupervisorLibrary( + [ + "GATEWAY_CONTROL_SIGNAL_PENDING=1", + "gateway_control_take_request", + "gateway_control_fail attacker-controlled 303", + 'cat "$NEMOCLAW_GATEWAY_CONTROL_STATUS"', + ].join("\n"), + `v1 ${VALID_NONCE} restart\n`, + ); + + expect(result).toMatchObject({ + status: 0, + stdout: `v1 ${VALID_NONCE} failed internal 303 0`, + stderr: "", + }); + }); +}); + +describe("gateway supervisor tracked PID handling", () => { + it("terminates only the exact tracked child PID", () => { + const result = runSupervisorLibrary( + [ + "sleep 30 & target_pid=$!", + "sleep 30 & sibling_pid=$!", + 'cleanup_children() { kill "$target_pid" "$sibling_pid" 2>/dev/null || true; }', + "trap cleanup_children EXIT", + 'target_identity="$(gateway_control_pid_start_identity "$target_pid")"', + 'test -n "$target_identity"', + 'gateway_control_stop_tracked_pid "$target_pid" "$target_identity"', + 'if kill -0 "$target_pid" 2>/dev/null; then exit 91; fi', + 'kill -0 "$sibling_pid"', + 'printf "%s\\n" "$sibling_pid"', + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(result.stderr).toBe(""); + expect(result.stdout).toMatch(/^\d+$/); + }); + + it("never sends a signal for sentinel or non-PID values", () => { + const result = runSupervisorLibrary( + [ + "calls=()", + 'kill() { calls+=("kill:$*"); return 1; }', + 'wait() { calls+=("wait:$*"); return 0; }', + "gateway_control_stop_tracked_pid 0", + "gateway_control_stop_tracked_pid 1", + "gateway_control_stop_tracked_pid not-a-pid", + 'test "${#calls[@]}" -eq 0', + ].join("\n"), + ); + + expect(result).toMatchObject({ status: 0, stdout: "", stderr: "" }); + }); + + it("requires a captured identity for a numeric PID without signaling or waiting", () => { + const result = runSupervisorLibrary( + [ + "calls=()", + 'kill() { calls+=("kill:$*"); return 1; }', + 'wait() { calls+=("wait:$*"); return 0; }', + "if gateway_control_stop_tracked_pid 4242 ''; then exit 92; fi", + 'test "${#calls[@]}" -eq 0', + ].join("\n"), + ); + + expect(result).toMatchObject({ status: 0, stdout: "", stderr: "" }); + }); + + it("does not KILL or wait for a PID whose start identity changes after TERM", () => { + const procRoot = join(temporaryDirectory("nemoclaw-gateway-stop-proc-"), "proc"); + const result = runSupervisorLibrary( + [ + `_NEMOCLAW_PROC_ROOT=${JSON.stringify(procRoot)}`, + 'mkdir -p "$_NEMOCLAW_PROC_ROOT/4242"', + "write_proc_stat() {", + ' local start="$1"', + " printf '4242 (tracked-child) S 1'", + " for _ in {1..17}; do printf ' 0'; done", + ' printf " %s\\n" "$start"', + "}", + 'write_proc_stat 111 >"$_NEMOCLAW_PROC_ROOT/4242/stat"', + "calls=()", + "kill() {", + ' calls+=("kill:$*")', + ' if [ "$1" = "-TERM" ]; then', + ' write_proc_stat 222 >"$_NEMOCLAW_PROC_ROOT/4242/stat"', + " fi", + " return 0", + "}", + 'wait() { calls+=("wait:$*"); return 0; }', + "sleep() { :; }", + "gateway_control_stop_tracked_pid 4242 111", + 'printf "%s\\n" "${calls[@]}"', + ].join("\n"), + ); + + expect(result).toMatchObject({ status: 0, stdout: "kill:-TERM 4242", stderr: "" }); + }); +}); + +describe("gateway supervisor listener ownership", () => { + it.each([ + ["IPv4 listener fd owned by the tracked PID", "tcp", "0A", "12345", "owned"], + ["IPv6 listener fd owned by the tracked PID", "tcp6", "0A", "12345", "owned"], + ["listener inode absent from the tracked PID fds", "tcp", "0A", "99999", "rejected"], + ["matching socket inode in a non-LISTEN state", "tcp", "01", "12345", "rejected"], + ])("classifies %s", (_label, table, state, fdInode, expected) => { + const procRoot = join(temporaryDirectory("nemoclaw-gateway-proc-"), "proc"); + const result = runSupervisorLibrary( + [ + `PROC_ROOT=${JSON.stringify(procRoot)}`, + 'mkdir -p "$PROC_ROOT/net" "$PROC_ROOT/$$/fd"', + ': >"$PROC_ROOT/net/tcp"', + ': >"$PROC_ROOT/net/tcp6"', + `printf '%s\\n' '0: 0100007F:4A38 00000000:0000 ${state} 00000000:00000000 00:00000000 00000000 4242 0 12345' >>"$PROC_ROOT/net/${table}"`, + `ln -s 'socket:[${fdInode}]' "$PROC_ROOT/$$/fd/7"`, + 'if gateway_control_pid_owns_tcp_listener "$$" 19000 "$PROC_ROOT"; then', + ' printf "owned\\n"', + "else", + ' printf "rejected\\n"', + "fi", + ].join("\n"), + ); + + expect(result).toMatchObject({ status: 0, stdout: expected, stderr: "" }); + }); +}); + +describe("root-only gateway control helper", () => { + it.each([ + "restart", + "probe", + ])("enters managed %s control with isolated Python before user-site startup hooks", (action) => { + const root = temporaryDirectory("nemoclaw-managed-python-isolation-"); + const userBase = join(root, "attacker-userbase"); + const marker = join(root, "pth-loaded"); + const attackEnv: NodeJS.ProcessEnv = { ...process.env, PYTHONUSERBASE: userBase }; + delete attackEnv.PYTHONNOUSERSITE; + const userSite = spawnSync( + "python3", + ["-c", "import site; print(site.getusersitepackages())"], + { encoding: "utf-8", env: attackEnv }, + ); + expect(userSite.status, userSite.stderr).toBe(0); + const sitePackages = userSite.stdout.trim(); + mkdirSync(sitePackages, { recursive: true }); + writeFileSync( + join(sitePackages, "attacker.pth"), + `import pathlib; pathlib.Path(${JSON.stringify(marker)}).write_text("loaded")\n`, + ); + const vulnerable = spawnSync("python3", ["-c", "pass"], { env: attackEnv }); + expect(vulnerable.status).toBe(0); + expect(existsSync(marker)).toBe(true); + rmSync(marker); + + const procRoot = join(root, "proc"); + mkdirSync(join(procRoot, "1"), { recursive: true }); + writeFileSync( + join(procRoot, "1", "cmdline"), + Buffer.from("/opt/openshell/bin/openshell-sandbox\0--managed\0"), + ); + const managedHelper = join(root, "managed-gateway-control.py"); + writeFileSync( + managedHelper, + [ + "#!/usr/bin/env python3", + "import json", + "import sys", + 'print(json.dumps({"isolated": sys.flags.isolated, "args": sys.argv[1:]}))', + ].join("\n"), + { mode: 0o755 }, + ); + const isolated = spawnSync(CONTROL_HELPER, [action, VALID_NONCE], { + encoding: "utf-8", + env: { + ...attackEnv, + NEMOCLAW_TEST_GATEWAY_CONTROL_PROC_ROOT: procRoot, + NEMOCLAW_TEST_MANAGED_GATEWAY_CONTROL_HELPER: managedHelper, + NEMOCLAW_TEST_GATEWAY_CONTROL_CALLER_UID: "0", + }, + }); + expect(isolated.status, isolated.stderr).toBe(0); + expect(JSON.parse(isolated.stdout)).toEqual({ + isolated: 1, + args: [action, VALID_NONCE], + }); + expect(existsSync(marker)).toBe(false); + }); + + it.each([ + ["bad action", ["replace", VALID_NONCE], "SUPERVISOR_INVALID_ACTION"], + ["short nonce", ["restart", "abcd"], "SUPERVISOR_INVALID_NONCE"], + ["uppercase nonce", ["recover", "B".repeat(64)], "SUPERVISOR_INVALID_NONCE"], + ])("rejects %s before touching the control directory", (_label, args, marker) => { + const result = spawnSync(CONTROL_HELPER, args, { + encoding: "utf-8", + timeout: 5000, + env: { + ...process.env, + NEMOCLAW_GATEWAY_CONTROL_DIR: join( + temporaryDirectory("nemoclaw-gateway-helper-invalid-"), + "absent", + ), + }, + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr.trim()).toBe(marker); + }); + + it("refuses a valid request from a non-root caller", () => { + const fakeBin = temporaryDirectory("nemoclaw-gateway-helper-path-"); + const fakeId = join(fakeBin, "id"); + writeFileSync(fakeId, '#!/bin/sh\nprintf "1000\\n"\n', { mode: 0o755 }); + const result = spawnSync(CONTROL_HELPER, ["restart", VALID_NONCE], { + encoding: "utf-8", + timeout: 5000, + env: { + ...process.env, + PATH: `${fakeBin}:${process.env.PATH ?? "/usr/bin:/bin"}`, + NEMOCLAW_GATEWAY_CONTROL_DIR: join(fakeBin, "absent"), + }, + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr.trim()).toBe("PRIVILEGED_CONTROL_UNAVAILABLE"); + }); +}); diff --git a/test/hermes-config-transaction-wiring.test.ts b/test/hermes-config-transaction-wiring.test.ts new file mode 100644 index 00000000000..5d64e6728e8 --- /dev/null +++ b/test/hermes-config-transaction-wiring.test.ts @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const SOURCE_REQUIRE_HOOK = path.join(import.meta.dirname, "helpers", "onboard-script-mocks.cjs"); + +describe("Hermes host config transaction wiring", () => { + it("passes the exact read digest and serialized update to the sealed write transaction", () => { + const rawConfig = "model:\n default: trusted-model\n"; + const expectedDigest = createHash("sha256").update(rawConfig).digest("hex"); + const script = String.raw` +const Module = require("node:module"); +const path = require("node:path"); +const root = process.cwd(); +const source = (...parts) => "./" + path.join("src", "lib", ...parts); +function installMock(filename, exports) { + const resolved = require.resolve(filename); + const replacement = new Module(resolved); + replacement.filename = resolved; + replacement.loaded = true; + replacement.exports = exports; + require.cache[resolved] = replacement; +} + +const rawConfig = ${JSON.stringify(rawConfig)}; +let captured = null; +let capturedPrivilegedExec = null; +installMock(source("runner.js"), { validateName: () => undefined, ROOT: root }); +installMock(source("state", "registry.js"), { + getSandbox: () => ({ name: "alpha", agent: "hermes" }), +}); +installMock(source("agent", "defs.js"), { + loadAgent: () => ({ + configPaths: { dir: "/sandbox/.hermes", configFile: "config.yaml", format: "yaml" }, + }), +}); +installMock(source("adapters", "openshell", "client.js"), { + captureOpenshellCommand: () => ({ status: 0, output: rawConfig }), + runOpenshellCommand: () => ({ status: 0 }), +}); +installMock(source("sandbox", "privileged-exec.js"), { + privilegedSandboxExecArgv: (sandboxName, command, stdin, sanitizeEnvironment) => { + capturedPrivilegedExec = { command, sanitizeEnvironment }; + return ["docker", "exec", ...(stdin ? ["-i"] : []), sandboxName, ...command]; + }, +}); +installMock(source("adapters", "docker", "exec.js"), { + dockerExecFileSync: (argv, options) => { + captured = { argv, options }; + return "updated=1\n"; + }, +}); + +const config = require(source("sandbox", "config.js")); +const target = config.resolveAgentConfig("alpha"); +const parsed = config.readSandboxConfig("alpha", target); +parsed.model.default = "trusted-model-v2"; +config.writeSandboxConfig("alpha", target, parsed); +process.stdout.write(JSON.stringify({ ...captured, privilegedExec: capturedPrivilegedExec })); +`; + + const result = spawnSync(process.execPath, ["--require", SOURCE_REQUIRE_HOOK, "-e", script], { + cwd: path.join(import.meta.dirname, ".."), + encoding: "utf-8", + env: { ...process.env, NODE_OPTIONS: "" }, + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + const captured = JSON.parse(result.stdout) as { + argv: string[]; + options: { input: string; timeout: number; stdio: string[] }; + privilegedExec: { command: string[]; sanitizeEnvironment: boolean }; + }; + const digestFlag = captured.argv.indexOf("--expected-config-sha256"); + expect(captured.argv).toEqual( + expect.arrayContaining([ + "-i", + "timeout", + "--signal=TERM", + "--kill-after=5s", + "2m", + "/opt/hermes/.venv/bin/python", + "-I", + "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "write-config", + "--hermes-dir", + "/sandbox/.hermes", + "--hash-file", + "/etc/nemoclaw/hermes.config-hash", + "--state-file", + "/run/nemoclaw/hermes-restart-seal.json", + ]), + ); + expect(digestFlag).toBeGreaterThanOrEqual(0); + expect(captured.argv[digestFlag + 1]).toBe(expectedDigest); + expect(captured.options.input).toContain("default: trusted-model-v2"); + expect(captured.options.timeout).toBe(150000); + expect(captured.options.stdio).toEqual(["pipe", "pipe", "pipe"]); + expect(captured.privilegedExec.sanitizeEnvironment).toBe(true); + expect(captured.privilegedExec.command).toEqual( + expect.arrayContaining([ + "/opt/hermes/.venv/bin/python", + "-I", + "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "write-config", + ]), + ); + }); +}); diff --git a/test/hermes-doctor-config-hash.test.ts b/test/hermes-doctor-config-hash.test.ts index 63e5d71b6b9..75a66be7cd7 100644 --- a/test/hermes-doctor-config-hash.test.ts +++ b/test/hermes-doctor-config-hash.test.ts @@ -12,6 +12,81 @@ const ROOT = path.resolve(import.meta.dirname, ".."); const HERMES_DOCKERFILE = path.join(ROOT, "agents", "hermes", "Dockerfile"); describe("Hermes doctor and config hash boundary", () => { + it("locks trusted gateway recovery preloads as image-owned read-only files", () => { + const dockerfile = fs.readFileSync(HERMES_DOCKERFILE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-preload-lock-")); + const binDir = path.join(tmp, "usr-local-bin"); + const libDir = path.join(tmp, "usr-local-lib-nemoclaw"); + const preloadsDir = path.join(libDir, "preloads"); + const nestedDir = path.join(preloadsDir, "nested"); + const profileDir = path.join(tmp, "etc-profile.d"); + const bashrcPath = path.join(tmp, "bash.bashrc"); + const chownLogPath = path.join(tmp, "chown.log"); + const mode = (entry: string) => (fs.statSync(entry).mode & 0o777).toString(8); + + try { + fs.mkdirSync(binDir, { recursive: true }); + fs.mkdirSync(nestedDir, { recursive: true, mode: 0o777 }); + fs.mkdirSync(profileDir, { recursive: true }); + for (const relativePath of [ + path.join(binDir, "nemoclaw-start"), + path.join(binDir, "nemoclaw-gateway-control"), + path.join(libDir, "sandbox-init.sh"), + path.join(libDir, "gateway-supervisor.sh"), + path.join(libDir, "validate-hermes-env-secret-boundary.py"), + path.join(libDir, "seed-hermes-dashboard-config.py"), + path.join(libDir, "hermes-runtime-config-guard.py"), + path.join(libDir, "state-dir-guard.py"), + path.join(libDir, "managed-gateway-control.py"), + path.join(libDir, "sandbox-rlimits.sh"), + path.join(preloadsDir, "gateway-safety-net.js"), + path.join(nestedDir, "ciao-preload.js"), + bashrcPath, + ]) { + fs.mkdirSync(path.dirname(relativePath), { recursive: true }); + fs.writeFileSync(relativePath, "test\n", { mode: 0o666 }); + } + + const lockCommand = dockerRunCommandBetween( + dockerfile, + "# Dockerfile.base is the source of truth for rlimit hooks.", + "# Flatten stale published base images", + ) + .replaceAll("/usr/local/bin", binDir) + .replaceAll("/usr/local/lib/nemoclaw", libDir) + .replaceAll("/etc/profile.d", profileDir) + .replaceAll("/etc/bash.bashrc", bashrcPath); + const script = [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `chown_log=${JSON.stringify(chownLogPath)}`, + 'chown() { printf "%s\\n" "$*" >> "$chown_log"; }', + lockCommand, + ].join("\n"); + const result = spawnSync("bash", ["-c", script], { encoding: "utf-8", timeout: 5000 }); + + expect(result.status).toBe(0); + expect(result.stderr).toBe(""); + expect(fs.readFileSync(chownLogPath, "utf-8")).toBe( + [ + `root:root ${path.join(binDir, "nemoclaw-gateway-control")} ${path.join(libDir, "gateway-supervisor.sh")} ${path.join(libDir, "state-dir-guard.py")} ${path.join(libDir, "managed-gateway-control.py")}`, + `-R 0:0 ${preloadsDir}`, + "", + ].join("\n"), + ); + expect(mode(path.join(binDir, "nemoclaw-gateway-control"))).toBe("700"); + expect(mode(path.join(libDir, "gateway-supervisor.sh"))).toBe("444"); + expect(mode(path.join(libDir, "state-dir-guard.py"))).toBe("500"); + expect(mode(path.join(libDir, "managed-gateway-control.py"))).toBe("500"); + expect(mode(preloadsDir)).toBe("755"); + expect(mode(nestedDir)).toBe("755"); + expect(mode(path.join(preloadsDir, "gateway-safety-net.js"))).toBe("444"); + expect(mode(path.join(nestedDir, "ciao-preload.js"))).toBe("444"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("keeps upstream doctor changes out of generated config hash inputs", () => { const dockerfile = fs.readFileSync(HERMES_DOCKERFILE, "utf-8"); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-doctor-lock-")); @@ -66,6 +141,11 @@ describe("Hermes doctor and config hash boundary", () => { "# Pin config hash at build time", "# Backward-compatible marker", ).replaceAll("/etc/nemoclaw", etcDir); + const compatHashCommand = dockerRunCommandBetween( + dockerfile, + "# Backward-compatible marker", + "# OpenShell's macOS VM backend", + ); try { const doctorAndGenerate = spawnSync("bash", ["-c", doctorAndGenerateCommand], { @@ -93,6 +173,17 @@ describe("Hermes doctor and config hash boundary", () => { timeout: 5000, }); expect(verifyHash.status).toBe(0); + + const compatHash = runDockerShell(compatHashCommand, sandboxRoot); + expect(compatHash.result.status).toBe(0); + expect(compatHash.result.stderr).toBe(""); + expect(mode(path.join(hermesDir, ".config-hash"))).toBe("640"); + const verifyCompatHash = spawnSync( + "sha256sum", + ["-c", path.join(hermesDir, ".config-hash")], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(verifyCompatHash.status).toBe(0); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } diff --git a/test/hermes-env-secret-boundary-hardening.test.ts b/test/hermes-env-secret-boundary-hardening.test.ts new file mode 100644 index 00000000000..8d8fc9e2a31 --- /dev/null +++ b/test/hermes-env-secret-boundary-hardening.test.ts @@ -0,0 +1,386 @@ +// 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 VALIDATOR = path.join( + import.meta.dirname, + "..", + "agents", + "hermes", + "validate-env-secret-boundary.py", +); +const START_SCRIPT = path.join(import.meta.dirname, "..", "agents", "hermes", "start.sh"); +const MAX_ENV_BYTES = 4 * 1024 * 1024; +const MAX_ENV_LINE_BYTES = 256 * 1024; +const MAX_ENV_LINES = 65_536; +const hasGnuTimeout = + spawnSync("timeout", ["--version"], { encoding: "utf-8", timeout: 5000 }).status === 0; + +function runValidator(envPath: string) { + return spawnSync("python3", [VALIDATOR, "env-file", envPath], { + encoding: "utf-8", + timeout: 5000, + env: { HOME: os.tmpdir(), PATH: process.env.PATH ?? "" }, + }); +} + +function extractShellFunction(source: string, name: string): string { + const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const match = source.match(new RegExp(`${escaped}\\(\\) \\{([\\s\\S]*?)^\\}`, "m")); + const resolved = + match ?? + (() => { + throw new Error(`Missing ${name} in start.sh`); + })(); + return `${name}() {${resolved[1]}\n}`; +} + +function runStartEnvValidation(hermesDir: string) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const runDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-start-check-")); + const script = path.join(runDir, "run.sh"); + try { + fs.writeFileSync( + script, + [ + "#!/usr/bin/env bash", + "set -u", + "_HERMES_BOUNDARY_TIMEOUT=()", + `_HERMES_BOUNDARY_VALIDATOR=${JSON.stringify(VALIDATOR)}`, + `HERMES_DIR=${JSON.stringify(hermesDir)}`, + extractShellFunction(source, "validate_hermes_env_secret_boundary"), + "validate_hermes_env_secret_boundary", + ].join("\n"), + { mode: 0o700 }, + ); + return spawnSync("bash", [script], { + encoding: "utf-8", + timeout: 5000, + env: { HOME: os.tmpdir(), PATH: process.env.PATH ?? "" }, + }); + } finally { + fs.rmSync(runDir, { recursive: true, force: true }); + } +} + +describe("Hermes env secret-boundary resource limits", () => { + it("accepts the normal 0640 mutable env-file mode", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-mode-")); + const envPath = path.join(root, ".env"); + try { + fs.writeFileSync(envPath, "SAFE=1\n", { mode: 0o640 }); + fs.chmodSync(envPath, 0o640); + const result = runValidator(envPath); + expect(result.status, result.stderr).toBe(0); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("accepts canonical sandbox ownership only with the installed 0640 posture", () => { + const result = spawnSync( + "python3", + [ + "-c", + `import importlib.util, stat, sys +from types import SimpleNamespace +spec = importlib.util.spec_from_file_location("validator", sys.argv[1]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.__file__ = module.INSTALLED_BOUNDARY_VALIDATOR +module._sandbox_identity = lambda: (1234, 5678) +def metadata(mode): + return SimpleNamespace(st_mode=stat.S_IFREG | mode, st_uid=1234, st_gid=5678, st_nlink=1) +module._validate_env_file_metadata("/sandbox/.hermes/.env", metadata(0o640)) +try: + module._validate_env_file_metadata("/sandbox/.hermes/.env", metadata(0o600)) +except module.UnsafeEnvInputError: + print("0640=accepted 0600=rejected")`, + VALIDATOR, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("0640=accepted 0600=rejected\n"); + }); + + it("rejects an oversized sparse env before reading its logical payload", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-cap-")); + const envPath = path.join(root, ".env"); + try { + fs.writeFileSync(envPath, "SAFE=1\n", { mode: 0o600 }); + fs.truncateSync(envPath, MAX_ENV_BYTES + 1); + const result = runValidator(envPath); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`${MAX_ENV_BYTES}-byte limit`); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a FIFO env path without blocking the privileged validator", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-fifo-")); + const envPath = path.join(root, ".env"); + try { + const created = spawnSync("mkfifo", [envPath], { encoding: "utf-8", timeout: 5000 }); + expect(created.status, created.stderr).toBe(0); + const result = runValidator(envPath); + expect(result.status, result.stderr).toBe(1); + expect(result.stderr).toContain("not a regular file"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a single oversized line within the total byte cap", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-line-cap-")); + const envPath = path.join(root, ".env"); + try { + fs.writeFileSync(envPath, `SAFE=${"x".repeat(MAX_ENV_LINE_BYTES + 1)}\n`, { mode: 0o600 }); + const result = runValidator(envPath); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`${MAX_ENV_LINE_BYTES}-byte limit`); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects too many individually bounded lines", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-line-count-")); + const envPath = path.join(root, ".env"); + try { + fs.writeFileSync(envPath, "#\n".repeat(MAX_ENV_LINES + 1), { mode: 0o600 }); + const result = runValidator(envPath); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`${MAX_ENV_LINES}-line limit`); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("caps secret diagnostics while retaining the total omitted count", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-diagnostics-cap-")); + const envPath = path.join(root, ".env"); + try { + const lines = Array.from({ length: 100 }, (_, index) => `SECRET_${index}=raw-${index}`); + fs.writeFileSync(envPath, `${lines.join("\n")}\n`, { mode: 0o600 }); + const result = runValidator(envPath); + expect(result.status).toBe(1); + expect(result.stderr.match(/^\[SECURITY\] SECRET_/gm)).toHaveLength(64); + expect(result.stderr).toContain("36 additional violation(s) omitted"); + expect(result.stderr).not.toContain("raw-99"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); + +describe("Hermes env secret-boundary namespace pinning", () => { + it("anchors installed validation at sandbox when Landlock denies opening root", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-landlock-root-")); + const sandbox = path.join(root, "sandbox"); + const hermes = path.join(sandbox, ".hermes"); + const envPath = path.join(hermes, ".env"); + fs.mkdirSync(hermes, { recursive: true }); + fs.chmodSync(sandbox, 0o770); + // Hermes tightens its own home to 0700 after startup in managed non-root + // mode; the boundary must still validate that stricter same-owner posture. + fs.chmodSync(hermes, 0o700); + fs.writeFileSync(envPath, "SAFE=1\n", { mode: 0o640 }); + fs.chmodSync(envPath, 0o640); + try { + const result = spawnSync( + "python3", + [ + "-c", + `import errno, importlib.util, os, sys +spec = importlib.util.spec_from_file_location("validator", sys.argv[1]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.__file__ = module.INSTALLED_BOUNDARY_VALIDATOR +module.INSTALLED_ENV_ROOT = sys.argv[2] +module.INSTALLED_ENV_PATH = sys.argv[3] +module._sandbox_identity = lambda: (os.geteuid(), os.getegid()) +original_open = module.os.open +def landlock_open(path, *args, **kwargs): + if path == os.sep: + raise PermissionError(errno.EACCES, "Landlock denied root", path) + return original_open(path, *args, **kwargs) +module.os.open = landlock_open +raise SystemExit(module.validate_env_file(sys.argv[3]))`, + VALIDATOR, + sandbox, + envPath, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(result.status, result.stderr).toBe(0); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("makes startup fail closed for a missing env or broken ancestor", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-missing-")); + const missingEnvHome = path.join(root, "missing-env"); + const brokenHome = path.join(root, "broken", ".hermes"); + fs.mkdirSync(missingEnvHome); + fs.symlinkSync(path.join(root, "absent-target"), path.join(root, "broken")); + try { + const missing = runStartEnvValidation(missingEnvHome); + const broken = runStartEnvValidation(brokenHome); + expect(missing.status).not.toBe(0); + expect(broken.status).not.toBe(0); + expect(missing.stderr).toContain("expected env path disappeared"); + expect(broken.stderr).toContain("expected env path disappeared"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects an ancestor symlink in installed-validator mode", () => { + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-ancestor-"))); + const target = path.join(root, "target"); + const linked = path.join(root, "sandbox"); + fs.mkdirSync(path.join(target, ".hermes"), { recursive: true }); + fs.writeFileSync(path.join(target, ".hermes", ".env"), "SECRET_TOKEN=never-print-this\n", { + mode: 0o600, + }); + fs.symlinkSync(target, linked); + try { + const result = spawnSync( + "python3", + [ + "-c", + `import importlib.util, os, sys +spec = importlib.util.spec_from_file_location("validator", sys.argv[1]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.__file__ = module.INSTALLED_BOUNDARY_VALIDATOR +module.INSTALLED_ENV_ROOT = os.path.dirname(os.path.dirname(sys.argv[2])) +module.INSTALLED_ENV_PATH = sys.argv[2] +raise SystemExit(module.validate_env_file(sys.argv[2]))`, + VALIDATOR, + path.join(linked, ".hermes", ".env"), + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain("symlink or non-directory ancestor"); + expect(result.stderr).not.toContain("never-print-this"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects a canonical ancestor rename after the descriptor read", () => { + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-race-"))); + const sandbox = path.join(root, "sandbox"); + const hermes = path.join(sandbox, ".hermes"); + fs.mkdirSync(hermes, { recursive: true }); + fs.chmodSync(sandbox, 0o770); + fs.chmodSync(hermes, 0o3770); + fs.writeFileSync(path.join(hermes, ".env"), "SAFE=1\n", { mode: 0o640 }); + fs.chmodSync(path.join(hermes, ".env"), 0o640); + try { + const result = spawnSync( + "python3", + [ + "-c", + `import importlib.util, os, sys +spec = importlib.util.spec_from_file_location("validator", sys.argv[1]) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +module.__file__ = module.INSTALLED_BOUNDARY_VALIDATOR +module.INSTALLED_ENV_ROOT = os.path.dirname(os.path.dirname(sys.argv[2])) +module.INSTALLED_ENV_PATH = sys.argv[2] +module._sandbox_identity = lambda: (os.geteuid(), os.getegid()) +original = module._read_bounded_env +def racing_read(fd, identity): + payload = original(fd, identity) + os.rename(sys.argv[3], sys.argv[4]) + os.mkdir(sys.argv[3], 0o700) + with open(os.path.join(sys.argv[3], ".env"), "w", encoding="utf-8") as handle: + handle.write("SECRET_TOKEN=never-print-this\\n") + os.chmod(os.path.join(sys.argv[3], ".env"), 0o600) + return payload +module._read_bounded_env = racing_read +raise SystemExit(module.validate_env_file(sys.argv[2]))`, + VALIDATOR, + path.join(hermes, ".env"), + hermes, + path.join(sandbox, ".hermes-moved"), + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain("ancestor changed while it was read"); + expect(result.stderr).not.toContain("never-print-this"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); + +describe.skipIf(!hasGnuTimeout)("Hermes PID 1 boundary-validator timeout", () => { + it("waits for timeout cleanup and leaves no validator process behind", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-timeout-")); + const bin = path.join(root, "bin"); + const hermes = path.join(root, ".hermes"); + const pidFile = path.join(root, "pids"); + fs.mkdirSync(bin); + fs.mkdirSync(hermes); + fs.writeFileSync(path.join(hermes, ".env"), "SAFE=1\n", { mode: 0o600 }); + fs.writeFileSync( + path.join(bin, "python3"), + `#!/bin/sh +sleep 30 & +child=$! +printf '%s %s\n' "$$" "$child" >${JSON.stringify(pidFile)} +wait "$child" +`, + { mode: 0o700 }, + ); + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const script = path.join(root, "run.sh"); + fs.writeFileSync( + script, + [ + "#!/usr/bin/env bash", + "set -u", + "_HERMES_BOUNDARY_TIMEOUT=(timeout --signal=TERM --kill-after=0.2s 2s)", + `_HERMES_BOUNDARY_VALIDATOR=${JSON.stringify(VALIDATOR)}`, + `HERMES_DIR=${JSON.stringify(hermes)}`, + extractShellFunction(source, "validate_hermes_env_secret_boundary"), + "rc=0", + "validate_hermes_env_secret_boundary || rc=$?", + `read -r parent child <${JSON.stringify(pidFile)}`, + "for _ in {1..100}; do", + ' parent_alive=0; kill -0 "$parent" 2>/dev/null && parent_alive=1', + ' child_alive=0; kill -0 "$child" 2>/dev/null && child_alive=1', + ' [ "$parent_alive" -eq 0 ] && [ "$child_alive" -eq 0 ] && break', + " sleep 0.01", + "done", + 'printf "rc=%s parent=%s child=%s\\n" "$rc" "$parent_alive" "$child_alive"', + ].join("\n"), + { mode: 0o700 }, + ); + try { + const result = spawnSync("bash", [script], { + encoding: "utf-8", + timeout: 5000, + env: { HOME: root, PATH: `${bin}:${process.env.PATH ?? ""}` }, + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("rc=124 parent=0 child=0\n"); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-gateway-supervisor-recovery.test.ts b/test/hermes-gateway-supervisor-recovery.test.ts new file mode 100644 index 00000000000..28d7e9f55b7 --- /dev/null +++ b/test/hermes-gateway-supervisor-recovery.test.ts @@ -0,0 +1,1344 @@ +// 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, "..", "agents", "hermes", "start.sh"); +const SUPERVISOR_LIB = path.join( + import.meta.dirname, + "..", + "scripts", + "lib", + "gateway-supervisor.sh", +); + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function extractShellFunction(source: string, name: string): string { + const match = source.match(new RegExp(`${escapeRegExp(name)}\\(\\) \\{([\\s\\S]*?)^\\}`, "m")); + const resolved = + match ?? + (() => { + throw new Error(`Expected ${name} in agents/hermes/start.sh`); + })(); + return `${name}() {${resolved[1]}\n}`; +} + +function runBashHarness(lines: string[], configure?: (tmpDir: string) => Record<string, string>) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-supervisor-test-")); + const script = path.join(tmpDir, "run.sh"); + fs.writeFileSync(script, ["#!/usr/bin/env bash", "set -uo pipefail", ...lines].join("\n"), { + mode: 0o700, + }); + + try { + return spawnSync("bash", [script], { + encoding: "utf-8", + timeout: 5000, + env: { ...process.env, ...configure?.(tmpDir) }, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} + +function runHermesHealthyGatewayRecovery(integrityStatus: 0 | 1) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + return runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "gateway_control_take_request() { GATEWAY_CONTROL_ACTION=recover; trace take-request; }", + 'gateway_control_pid_is_live() { trace "pid-live:$1"; return 0; }', + "hermes_gateway_healthy() { trace gateway-healthy; return 0; }", + "validate_running_hermes_boundary() { trace boundary-validation; return 0; }", + `verify_hermes_config_integrity() { trace strict-integrity; return ${integrityStatus}; }`, + "hermes_auxiliaries_need_recovery() { trace auxiliaries-needed; return 0; }", + "seal_hermes_restart_inputs() { trace seal-inputs; return 0; }", + "unseal_hermes_restart_inputs() { trace unseal-inputs; return 0; }", + "ensure_hermes_supervised_auxiliaries() { trace auxiliaries; return 0; }", + "refresh_hermes_supervised_child_pids() { trace refresh-child-pids; }", + 'gateway_control_complete() { trace "complete:$1:$2:$3"; }', + 'gateway_control_fail() { trace "fail:$1:$2"; }', + 'gateway_control_stop_tracked_pid() { trace "unexpected-stop:$1"; return 0; }', + "mark_hermes_gateway_stopped() { trace unexpected-mark-stopped; }", + extractShellFunction(source, "prepare_hermes_gateway_restart"), + extractShellFunction(source, "handle_hermes_gateway_control_request"), + "GATEWAY_PID=4242", + "HERMES_RESTART_FAILURE_CODE=internal", + 'if handle_hermes_gateway_control_request; then trace "handler-rc:0"; else trace "handler-rc:$?"; fi', + ]); +} + +function runHermesGatewayProbe(opts: { + prepareStatus: 0 | 1; + healthStatus: 0 | 1; + auxiliariesStatus: 0 | 1; +}) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + return runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "gateway_control_take_request() { GATEWAY_CONTROL_ACTION=probe; trace take-request; }", + `prepare_hermes_gateway_restart() { HERMES_RESTART_FAILURE_CODE=hash-mismatch; trace preflight; return ${opts.prepareStatus}; }`, + 'gateway_control_pid_is_live() { trace "pid-live:$1"; return 0; }', + `hermes_gateway_healthy() { trace "gateway-healthy:$1"; return ${opts.healthStatus}; }`, + `hermes_auxiliaries_need_recovery() { trace auxiliaries-check; return ${opts.auxiliariesStatus}; }`, + 'gateway_control_complete() { trace "complete:$1:$2:$3"; }', + 'gateway_control_fail() { trace "fail:$1:$2"; }', + "seal_hermes_restart_inputs() { trace unexpected-seal; }", + "unseal_hermes_restart_inputs() { trace unexpected-unseal; }", + "ensure_hermes_supervised_auxiliaries() { trace unexpected-launch-auxiliaries; }", + "stop_hermes_gateway_fail_closed() { trace unexpected-stop; }", + "mark_hermes_gateway_stopped() { trace unexpected-mark-stopped; }", + "kill() { trace unexpected-signal; }", + extractShellFunction(source, "handle_hermes_gateway_control_request"), + "GATEWAY_PID=4242", + "HERMES_RESTART_FAILURE_CODE=internal", + 'if handle_hermes_gateway_control_request; then trace "handler-rc:0"; else trace "handler-rc:$?"; fi', + ]); +} + +function runHermesOrphanedSealCheck(opts: { + sandboxMetadata: string; + stateFileExists?: boolean; + hashValid?: boolean; +}) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + return runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + 'stat() { if [ "${3:-}" = "/sandbox" ]; then printf "%s\\n" "$SANDBOX_METADATA"; return 0; fi; command stat "$@"; }', + `verify_hermes_config_integrity() { trace verify-hash; return ${opts.hashValid === false ? 1 : 0}; }`, + extractShellFunction(source, "hermes_restart_seal_orphaned"), + 'HERMES_RESTART_SEAL_STATE="$STATE_PATH"', + "if hermes_restart_seal_orphaned; then trace orphaned; else trace normal; fi", + ], + (tmpDir) => { + const statePath = path.join(tmpDir, "hermes-restart-seal.json"); + for (const _present of opts.stateFileExists ? [true] : []) { + fs.writeFileSync(statePath, "fixture\n"); + } + return { SANDBOX_METADATA: opts.sandboxMetadata, STATE_PATH: statePath }; + }, + ); +} + +function runHermesStartupReadiness(gatewayInitStatus: 0 | 1) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const start = source.indexOf("if ! gateway_control_init; then"); + const print = source.indexOf("print_dashboard_urls", start); + const blockStart = + start >= 0 && print >= 0 + ? start + : (() => { + throw new Error("Hermes root startup control block not found"); + })(); + const end = source.indexOf("\n", print); + const block = source.slice(blockStart, end < 0 ? source.length : end); + return runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + `gateway_control_init() { trace gateway-control-init; return ${gatewayInitStatus}; }`, + 'HERMES_DIR="/sandbox/.hermes"', + '_HERMES_PYTHON="hermes-python"', + '_HERMES_RUNTIME_CONFIG_GUARD="runtime-guard"', + 'hermes-python() { printf "publish:%s\\n" "$*" >&2; return 0; }', + "print_dashboard_urls() { trace dashboard-urls; }", + block, + ]); +} + +describe("Hermes PID 1 supervisor recovery", () => { + it("publishes startup readiness through isolated Python when gateway-control init fails", () => { + const result = runHermesStartupReadiness(1); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["gateway-control-init", "dashboard-urls"]); + expect(result.stderr).toContain( + "publish:-I runtime-guard publish-startup-ready --hermes-dir /sandbox/.hermes --startup-owner", + ); + expect(result.stderr).toContain("privileged gateway control unavailable"); + }); + + it("validates the strict trust anchor before healthy-recover auxiliaries", () => { + const result = runHermesHealthyGatewayRecovery(0); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "take-request", + "pid-live:4242", + "gateway-healthy", + "boundary-validation", + "strict-integrity", + "auxiliaries-needed", + "seal-inputs", + "boundary-validation", + "strict-integrity", + "auxiliaries", + "unseal-inputs", + "refresh-child-pids", + "complete:already-running:4242:4242", + "handler-rc:0", + ]); + }); + + it("does not start healthy-recover auxiliaries when strict validation fails", () => { + const result = runHermesHealthyGatewayRecovery(1); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "take-request", + "pid-live:4242", + "gateway-healthy", + "boundary-validation", + "strict-integrity", + "fail:hash-mismatch:4242", + "handler-rc:1", + ]); + expect(result.stdout).not.toContain("auxiliaries"); + }); + + it.each([ + { + label: "reports the existing gateway and auxiliaries healthy", + prepareStatus: 0 as const, + healthStatus: 0 as const, + auxiliariesStatus: 1 as const, + expected: [ + "take-request", + "preflight", + "pid-live:4242", + "gateway-healthy:4242", + "auxiliaries-check", + "complete:already-running:4242:4242", + "handler-rc:0", + ], + }, + { + label: "rejects failed preflight before checking processes", + prepareStatus: 1 as const, + healthStatus: 0 as const, + auxiliariesStatus: 1 as const, + expected: ["take-request", "preflight", "fail:hash-mismatch:4242", "handler-rc:1"], + }, + { + label: "reports an unhealthy gateway", + prepareStatus: 0 as const, + healthStatus: 1 as const, + auxiliariesStatus: 1 as const, + expected: [ + "take-request", + "preflight", + "pid-live:4242", + "gateway-healthy:4242", + "fail:health-timeout:4242", + "handler-rc:1", + ], + }, + { + label: "reports auxiliaries that need recovery", + prepareStatus: 0 as const, + healthStatus: 0 as const, + auxiliariesStatus: 0 as const, + expected: [ + "take-request", + "preflight", + "pid-live:4242", + "gateway-healthy:4242", + "auxiliaries-check", + "fail:health-timeout:4242", + "handler-rc:1", + ], + }, + ])("keeps the authenticated probe read-only when it $label", ({ + prepareStatus, + healthStatus, + auxiliariesStatus, + expected, + }) => { + const result = runHermesGatewayProbe({ prepareStatus, healthStatus, auxiliariesStatus }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(expected); + expect(result.stdout).not.toContain("unexpected-"); + }); + + it("routes a secret-boundary refusal through whole-container gateway revocation", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "gateway_control_take_request() { GATEWAY_CONTROL_ACTION=restart; trace take-request; }", + "prepare_hermes_gateway_restart() { HERMES_RESTART_FAILURE_CODE=secret-boundary-refusal; trace boundary-refusal; return 1; }", + "stop_hermes_gateway_fail_closed() { trace fail-closed-stop; }", + 'gateway_control_fail() { trace "fail:$1:$2"; }', + "mark_hermes_gateway_stopped() { trace unexpected-direct-mark; }", + extractShellFunction(source, "handle_hermes_gateway_control_request"), + "GATEWAY_PID=4242", + "HERMES_RESTART_FAILURE_CODE=internal", + 'if handle_hermes_gateway_control_request; then trace "handler-rc:0"; else trace "handler-rc:$?"; fi', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "take-request", + "boundary-refusal", + "fail-closed-stop", + "fail:secret-boundary-refusal:4242", + "handler-rc:1", + ]); + expect(result.stdout).not.toContain("unexpected-direct-mark"); + }); + + it("does not unseal or stop the gateway when a foreign config transaction owns restart state", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + "install_hermes_restart_seal_traps() { trace install-traps; }", + "restore_hermes_runtime_traps() { trace restore-traps; }", + "unseal_hermes_restart_inputs() { trace unexpected-unseal; return 0; }", + "stop_hermes_gateway_fail_closed() { trace unexpected-stop; }", + extractShellFunction(source, "seal_hermes_restart_inputs"), + '_HERMES_PYTHON="$FAKE_PYTHON"', + '_HERMES_RUNTIME_CONFIG_GUARD="/trusted/runtime-config-guard.py"', + 'HERMES_DIR="/sandbox/.hermes"', + 'HERMES_HASH_FILE="/etc/nemoclaw/hermes.config-hash"', + 'HERMES_RESTART_SEAL_STATE="/run/nemoclaw/hermes-restart-seal.json"', + 'GATEWAY_CONTROL_NONCE="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"', + "HERMES_RESTART_FAILURE_CODE=internal", + "HERMES_RESTART_SEALED=0", + 'if seal_hermes_restart_inputs; then trace unexpected-success; else trace "seal-failed:$HERMES_RESTART_SEALED"; fi', + 'if [ "$HERMES_RESTART_SEALED" -eq 1 ]; then stop_hermes_gateway_fail_closed; fi', + ], + (tmpDir) => { + const fakePython = path.join(tmpDir, "python"); + fs.writeFileSync( + fakePython, + `#!/usr/bin/env bash +[ "$1" = "-I" ] || { echo "runtime guard did not use isolated Python" >&2; exit 98; } +[ "$2" = "/trusted/runtime-config-guard.py" ] || { echo "unexpected guard path: $2" >&2; exit 98; } +case "$3" in + seal-restart) echo "Hermes config mutation is already in progress" >&2; exit 1 ;; + inspect-mutation-owner) echo "state=1 lock=1 owner_active=1 token_match=0 original_locked=0 recovery_safe=1" ;; + *) exit 99 ;; +esac +`, + { mode: 0o700 }, + ); + return { FAKE_PYTHON: fakePython }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "install-traps", + "restore-traps", + "seal-failed:0", + ]); + expect(result.stdout).not.toContain("unexpected-unseal"); + expect(result.stdout).not.toContain("unexpected-stop"); + }); +}); + +describe("Hermes orphaned restart seal detection", () => { + it("detects a frozen root-owned parent even when child sealing was only partial", () => { + // Ownership changes before the final 0755 mode. A crash between those + // syscalls leaves the original mutable mode but is still an orphaned seal. + const result = runHermesOrphanedSealCheck({ sandboxMetadata: "0:0 770" }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["verify-hash", "orphaned"]); + }); + + it("keeps the orphan classification when partial child state also fails hash validation", () => { + const result = runHermesOrphanedSealCheck({ + sandboxMetadata: "0:0 755", + hashValid: false, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["verify-hash", "orphaned"]); + expect(result.stderr).toContain("Orphaned Hermes restart seal also failed strict hash"); + }); + + it("does not infer an orphan when a recovery token exists or the parent is sandbox-owned", () => { + const tokenPresent = runHermesOrphanedSealCheck({ + sandboxMetadata: "0:0 755", + stateFileExists: true, + }); + const mutableParent = runHermesOrphanedSealCheck({ sandboxMetadata: "1000:1000 770" }); + + expect(tokenPresent.status, tokenPresent.stderr).toBe(0); + expect(tokenPresent.stdout.trim()).toBe("normal"); + expect(mutableParent.status, mutableParent.stderr).toBe(0); + expect(mutableParent.stdout.trim()).toBe("normal"); + }); +}); + +describe("Hermes startup mutation ownership", () => { + it("cold-resumes a pending 0500 shields clamp through recursive verification", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + "install_hermes_restart_seal_traps() { trace unexpected-install-traps; }", + "unseal_hermes_restart_inputs() { trace unexpected-unseal; return 0; }", + extractShellFunction(source, "resume_startup_hermes_shields_lock"), + extractShellFunction(source, "recover_startup_hermes_mutation"), + '_HERMES_PYTHON="$FAKE_PYTHON"', + '_HERMES_RUNTIME_CONFIG_GUARD="/trusted/runtime-config-guard.py"', + "_HERMES_GUARD_TIMEOUT=()", + 'HERMES_DIR="/sandbox/.hermes"', + 'HERMES_HASH_FILE="/etc/nemoclaw/hermes.config-hash"', + 'HERMES_CONFIG_MUTATION_LOCK="$LOCK_PATH"', + 'HERMES_RESTART_SEAL_STATE="$STATE_PATH"', + "if recover_startup_hermes_mutation; then trace recovered; else trace failed; fi", + 'cat "$TRACE_FILE"', + ], + (tmpDir) => { + const statePath = path.join(tmpDir, "state.json"); + const lockPath = path.join(tmpDir, "lock"); + const traceFile = path.join(tmpDir, "trace"); + fs.writeFileSync(statePath, "state\n"); + fs.writeFileSync(lockPath, "lock\n"); + const fakePython = path.join(tmpDir, "python"); + fs.writeFileSync( + fakePython, + `#!/usr/bin/env bash +[ "$1" = "-I" ] || { echo "runtime guard did not use isolated Python" >&2; exit 98; } +[ "$2" = "/trusted/runtime-config-guard.py" ] || { echo "unexpected guard path: $2" >&2; exit 98; } +case "$3" in + inspect-mutation-owner) + echo inspect >>"$TRACE_FILE" + echo "state=1 lock=1 owner_active=1 token_match=0 original_locked=0 recovery_safe=0 resumable_lock=1" + ;; + begin-shields-transition) + echo begin >>"$TRACE_FILE" + echo "lock_token=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa original_locked=0" + ;; + run-state-dir-transition) echo state-lock >>"$TRACE_FILE" ;; + apply-shields-transition) echo apply >>"$TRACE_FILE" ;; + finish-shields-transition) + echo finish >>"$TRACE_FILE" + rm -f "$STATE_PATH" "$LOCK_PATH" + ;; + *) echo "unexpected action: $3" >&2; exit 99 ;; +esac +`, + { mode: 0o700 }, + ); + return { + FAKE_PYTHON: fakePython, + STATE_PATH: statePath, + LOCK_PATH: lockPath, + TRACE_FILE: traceFile, + }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "recovered", + "inspect", + "begin", + "state-lock", + "apply", + "finish", + ]); + expect(result.stderr).toContain("Resumed interrupted Hermes shields lock"); + }); + + it("waits for a live host transaction to finish instead of consuming its state", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + "install_hermes_restart_seal_traps() { trace unexpected-install-traps; }", + "unseal_hermes_restart_inputs() { trace unexpected-unseal; return 0; }", + extractShellFunction(source, "recover_startup_hermes_mutation"), + '_HERMES_PYTHON="$FAKE_PYTHON"', + '_HERMES_RUNTIME_CONFIG_GUARD="/trusted/runtime-config-guard.py"', + 'HERMES_DIR="/sandbox/.hermes"', + 'HERMES_CONFIG_MUTATION_LOCK="$LOCK_PATH"', + 'HERMES_RESTART_SEAL_STATE="$STATE_PATH"', + "if recover_startup_hermes_mutation; then trace recovered; else trace failed; fi", + ], + (tmpDir) => { + const statePath = path.join(tmpDir, "state.json"); + const lockPath = path.join(tmpDir, "lock"); + fs.writeFileSync(statePath, "state\n"); + fs.writeFileSync(lockPath, "lock\n"); + const fakePython = path.join(tmpDir, "python"); + fs.writeFileSync( + fakePython, + `#!/usr/bin/env bash +rm -f "$STATE_PATH" "$LOCK_PATH" +echo "state=1 lock=1 owner_active=1 token_match=0 original_locked=0 recovery_safe=1" +`, + { mode: 0o700 }, + ); + return { FAKE_PYTHON: fakePython, STATE_PATH: statePath, LOCK_PATH: lockPath }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("recovered"); + expect(result.stdout).not.toContain("unexpected-unseal"); + }); + + it("fails closed instead of guessing how to recover an interrupted shields transition", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + "install_hermes_restart_seal_traps() { trace unexpected-install-traps; }", + "unseal_hermes_restart_inputs() { trace unexpected-unseal; return 0; }", + extractShellFunction(source, "recover_startup_hermes_mutation"), + '_HERMES_PYTHON="$FAKE_PYTHON"', + '_HERMES_RUNTIME_CONFIG_GUARD="/trusted/runtime-config-guard.py"', + 'HERMES_DIR="/sandbox/.hermes"', + 'HERMES_CONFIG_MUTATION_LOCK="$LOCK_PATH"', + 'HERMES_RESTART_SEAL_STATE="$STATE_PATH"', + "if recover_startup_hermes_mutation; then trace unexpected-success; else trace failed-closed; fi", + ], + (tmpDir) => { + const statePath = path.join(tmpDir, "state.json"); + const lockPath = path.join(tmpDir, "lock"); + fs.writeFileSync(statePath, "state\n"); + fs.writeFileSync(lockPath, "lock\n"); + const fakePython = path.join(tmpDir, "python"); + fs.writeFileSync( + fakePython, + '#!/usr/bin/env bash\necho "state=1 lock=1 owner_active=0 token_match=0 original_locked=1 recovery_safe=0"\n', + { mode: 0o700 }, + ); + return { FAKE_PYTHON: fakePython, STATE_PATH: statePath, LOCK_PATH: lockPath }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("failed-closed"); + expect(result.stdout).not.toContain("unexpected-unseal"); + expect(result.stderr).toContain("HERMES_CONFIG_MUTATION_ORPHANED"); + }); +}); + +describe("Hermes supervised auxiliary recovery", () => { + it("re-prepares runtime inputs and retries a refused non-root gateway respawn", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'hermes_tracked_role_is_current() { [ "$2" = "6262" ] && { trace "supervised:$2"; exit 0; }; return 1; }', + 'wait() { trace "wait:$1"; return 143; }', + "mark_hermes_gateway_stopped() { trace mark-stopped; GATEWAY_PID=0; }", + "hermes_managed_gateway_exit_was_host_authorized() { return 1; }", + 'date() { printf "100\\n"; }', + "sleep() { :; }", + "prepare_calls=0", + "launch_calls=0", + 'prepare_hermes_nonroot_runtime() { prepare_calls=$((prepare_calls + 1)); trace "prepare:$prepare_calls"; [ "$prepare_calls" -ne 2 ]; }', + 'launch_hermes_gateway_current_user() { launch_calls=$((launch_calls + 1)); [ "$launch_calls" -eq 1 ] && GATEWAY_PID=5252 || GATEWAY_PID=6262; trace "launch:$GATEWAY_PID"; }', + 'wait_for_hermes_gateway_internal() { trace "health:$1"; }', + "ensure_hermes_supervised_auxiliaries() { trace auxiliaries; }", + 'refresh_hermes_supervised_child_pids() { trace "refresh:$GATEWAY_PID"; }', + "hermes_gateway_healthy() { return 0; }", + 'hermes_stop_tracked_role() { trace "unexpected-stop:$2"; return 1; }', + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "recover_hermes_gateway_current_user"), + extractShellFunction(source, "supervise_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=()", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=0", + "GATEWAY_PID=4242", + "supervise_hermes_gateway_current_user", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "wait:4242", + "mark-stopped", + "prepare:1", + "launch:5252", + "health:5252", + "auxiliaries", + "refresh:5252", + "wait:5252", + "mark-stopped", + "prepare:2", + "prepare:3", + "launch:6262", + "health:6262", + "auxiliaries", + "refresh:6262", + "supervised:6262", + ]); + expect(result.stderr).toContain("Hermes gateway respawned (pid 5252)"); + }); + + it("quarantines after five gateway exits in one minute without a sixth launch", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "hermes_tracked_role_is_current() { return 1; }", + 'wait() { trace "wait:$1"; return 137; }', + "mark_hermes_gateway_stopped() { GATEWAY_PID=0; }", + "hermes_managed_gateway_exit_was_host_authorized() { return 1; }", + 'date() { printf "100\\n"; }', + 'sleep() { [ "$1" = "60" ] && { trace quarantine; exit 0; }; }', + 'recover_hermes_gateway_current_user() { recover_calls=$((recover_calls + 1)); GATEWAY_PID=$((5000 + recover_calls)); trace "recover:$GATEWAY_PID"; }', + "recover_calls=0", + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "supervise_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=()", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=0", + "GATEWAY_PID=4242", + "supervise_hermes_gateway_current_user", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.match(/^recover:/gm)).toHaveLength(4); + expect(result.stdout).toContain("recover:5004"); + expect(result.stdout).not.toContain("recover:5005"); + expect(result.stdout).toContain("quarantine"); + expect(result.stderr).toContain("relaunch is quarantined until sandbox recreation"); + }); + + it.each([ + ["health validation", 1, 0], + ["auxiliary validation", 0, 1], + ])("counts repeated %s failures and never launches a sixth candidate", (_label, health, auxiliaries) => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "prepare_hermes_nonroot_runtime() { return 0; }", + 'launch_hermes_gateway_current_user() { launch_calls=$((launch_calls + 1)); GATEWAY_PID=$((6000 + launch_calls)); trace "launch:$GATEWAY_PID"; }', + `wait_for_hermes_gateway_internal() { return ${health}; }`, + `ensure_hermes_supervised_auxiliaries() { return ${auxiliaries}; }`, + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + "mark_hermes_gateway_stopped() { GATEWAY_PID=0; }", + "refresh_hermes_supervised_child_pids() { :; }", + 'date() { printf "100\\n"; }', + 'sleep() { [ "$1" = "60" ] && { trace quarantine; exit 0; }; }', + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "recover_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=()", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=0", + "launch_calls=0", + "recover_hermes_gateway_current_user", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.match(/^launch:/gm)).toHaveLength(5); + expect(result.stdout).toContain("launch:6005"); + expect(result.stdout).not.toContain("launch:6006"); + expect(result.stdout.match(/^stop:/gm)).toHaveLength(5); + expect(result.stdout).toContain("quarantine"); + expect(result.stderr).toContain("5 exits in 60s window"); + }); + + it("does not count preparation refusals or launch before preparation succeeds", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'prepare_hermes_nonroot_runtime() { prepare_calls=$((prepare_calls + 1)); trace "prepare:$prepare_calls"; [ "$prepare_calls" -ge 3 ]; }', + 'launch_hermes_gateway_current_user() { launch_calls=$((launch_calls + 1)); GATEWAY_PID=7001; trace "launch:$GATEWAY_PID"; }', + "wait_for_hermes_gateway_internal() { return 0; }", + "ensure_hermes_supervised_auxiliaries() { return 0; }", + "refresh_hermes_supervised_child_pids() { trace refresh; }", + 'date() { trace unexpected-exit-record; printf "100\\n"; }', + 'sleep() { trace "sleep:$1"; }', + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "recover_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=()", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=0", + "prepare_calls=0", + "launch_calls=0", + "recover_hermes_gateway_current_user", + 'trace "launch-count:$launch_calls"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "prepare:1", + "sleep:5", + "prepare:2", + "sleep:5", + "prepare:3", + "launch:7001", + "refresh", + "launch-count:1", + ]); + expect(result.stdout).not.toContain("unexpected-exit-record"); + }); + + it("keeps the initial non-root supervisor alive and recovers a failed first child", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'launch_hermes_gateway_current_user() { GATEWAY_PID=4100; trace "launch:$GATEWAY_PID"; }', + "start_gateway_log_stream() { trace log-stream; }", + 'refresh_hermes_supervised_child_pids() { trace "refresh:$GATEWAY_PID"; }', + "wait_for_hermes_gateway_internal() { trace initial-health-failed; return 1; }", + "ensure_hermes_supervised_auxiliaries() { trace unexpected-auxiliaries; return 0; }", + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + "mark_hermes_gateway_stopped() { trace mark-stopped; GATEWAY_PID=0; }", + 'recover_hermes_gateway_current_user() { GATEWAY_PID=4200; trace "recover:$GATEWAY_PID"; }', + 'date() { printf "100\\n"; }', + 'sleep() { trace "sleep:$1"; }', + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "bootstrap_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=()", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=0", + "bootstrap_hermes_gateway_current_user", + 'trace "final:$GATEWAY_PID"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "launch:4100", + "log-stream", + "refresh:4100", + "initial-health-failed", + "stop:4100", + "mark-stopped", + "sleep:2", + "recover:4200", + "refresh:4200", + "final:4200", + ]); + expect(result.stdout).not.toContain("unexpected-auxiliaries"); + expect(result.stderr).toContain("stopping the exact child for supervised recovery"); + }); + + it("quarantines instead of orphaning an unhealthy child whose exact stop fails", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "hermes_tracked_role_is_current() { return 0; }", + 'hermes_gateway_healthy() { health_calls=$((health_calls + 1)); trace "unhealthy:$health_calls"; return 1; }', + "ensure_hermes_supervised_auxiliaries() { trace unexpected-auxiliaries; }", + "refresh_hermes_supervised_child_pids() { :; }", + 'hermes_stop_tracked_role() { trace "stop-refused:$2"; return 1; }', + 'sleep() { [ "$1" = "60" ] && { trace quarantine; exit 0; }; }', + 'wait() { trace "unexpected-wait:$1"; }', + "recover_hermes_gateway_current_user() { trace unexpected-recover; }", + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "supervise_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "GATEWAY_PID=4242", + "health_calls=0", + "supervise_hermes_gateway_current_user", + "trace unexpected-return", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "unhealthy:1", + "unhealthy:2", + "unhealthy:3", + "unhealthy:4", + "stop-refused:4242", + "quarantine", + ]); + expect(result.stderr).toContain("managed supervisor is quarantined without another launch"); + expect(result.stdout).not.toContain("unexpected-wait"); + expect(result.stdout).not.toContain("unexpected-recover"); + expect(result.stdout).not.toContain("unexpected-return"); + }); + + it("refreshes exact role identities and clears a stale gateway wait PID before cleanup", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "refresh_hermes_supervised_child_pids() { trace refresh-identities; SANDBOX_CHILD_PIDS=(202); }", + "hermes_tracked_role_is_current() { trace gateway-identity-mismatch; return 1; }", + 'cleanup_on_signal() { trace "cleanup:wait=${SANDBOX_WAIT_PID:-}:children=${SANDBOX_CHILD_PIDS[*]:-}"; }', + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n"; }', + extractShellFunction(source, "hermes_cleanup_on_signal"), + "GATEWAY_PID=4242", + "INTERNAL_PORT=18642", + "SANDBOX_WAIT_PID=4242", + "SANDBOX_CHILD_PIDS=(4242 202)", + "hermes_cleanup_on_signal", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "refresh-identities", + "gateway-identity-mismatch", + "cleanup:wait=:children=202", + ]); + }); + + it("binds a tracked role to the startup supervisor parent, effective uid, cmdline, and start time", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + 'trace() { printf "%s\\n" "$*"; }', + "gateway_control_pid_is_live() { return 0; }", + 'hermes_expected_service_uid() { printf "1000"; }', + extractShellFunction(source, "hermes_process_start_identity"), + extractShellFunction(source, "hermes_process_role_identity"), + '_HERMES_PROC_ROOT="$PROC_ROOT"', + "HERMES_STARTUP_SUPERVISOR_PID=77", + 'identity="$(hermes_process_role_identity dashboard 4242 sandbox 19119)"', + 'trace "valid:$identity"', + 'cp "$BAD_STAT" "$PROC_ROOT/4242/stat"', + "if hermes_process_role_identity dashboard 4242 sandbox 19119 >/dev/null; then trace unexpected-ppid; else trace rejected-ppid; fi", + 'cp "$GOOD_STAT" "$PROC_ROOT/4242/stat"', + 'printf "socat\\0TCP-LISTEN:19119,bind=0.0.0.0\\0" >"$PROC_ROOT/4242/cmdline"', + "if hermes_process_role_identity dashboard 4242 sandbox 19119 >/dev/null; then trace unexpected-role; else trace rejected-role; fi", + ], + (tmpDir) => { + const procRoot = path.join(tmpDir, "proc"); + const pidRoot = path.join(procRoot, "4242"); + fs.mkdirSync(pidRoot, { recursive: true }); + const makeStat = (ppid: number) => + `4242 (hermes dashboard) ${["S", String(ppid), ...Array(17).fill("0"), "777"].join(" ")}\n`; + const goodStat = path.join(tmpDir, "good.stat"); + const badStat = path.join(tmpDir, "bad.stat"); + fs.writeFileSync(goodStat, makeStat(77)); + fs.writeFileSync(badStat, makeStat(1)); + fs.copyFileSync(goodStat, path.join(pidRoot, "stat")); + fs.writeFileSync(path.join(pidRoot, "status"), "Uid:\t1000\t1000\t1000\t1000\n"); + fs.writeFileSync( + path.join(pidRoot, "cmdline"), + Buffer.from(["/usr/local/bin/hermes", "dashboard", "--port", "19119", ""].join("\0")), + ); + return { PROC_ROOT: procRoot, GOOD_STAT: goodStat, BAD_STAT: badStat }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "valid:777", + "rejected-ppid", + "rejected-role", + ]); + }); + + it("refuses to forget or signal a live PID whose start identity was reused", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "hermes_tracked_role_is_current() { trace identity-mismatch; return 1; }", + 'hermes_process_start_identity() { printf "new-start-time"; }', + 'gateway_control_stop_tracked_pid() { trace "unexpected-signal:$1"; return 0; }', + 'wait() { trace "unexpected-wait:$1"; return 0; }', + extractShellFunction(source, "hermes_role_identity_value"), + extractShellFunction(source, "hermes_set_role_identity"), + extractShellFunction(source, "hermes_stop_tracked_role"), + 'GATEWAY_PID_START_IDENTITY="old-start-time"', + "rc=0; hermes_stop_tracked_role gateway 4242 gateway 18642 || rc=$?", + 'trace "rc:$rc"', + 'trace "identity:${GATEWAY_PID_START_IDENTITY:-cleared}"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "identity-mismatch", + "rc:1", + "identity:old-start-time", + ]); + expect(result.stderr).toContain("was reused"); + expect(result.stdout).not.toContain("unexpected-signal"); + expect(result.stdout).not.toContain("unexpected-wait"); + }); + + it("forgets a tracked child only after proving the numeric PID is gone", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "hermes_tracked_role_is_current() { trace role-gone; return 1; }", + "hermes_process_start_identity() { return 1; }", + 'kill() { [ "$1" = "-0" ] && return 1; trace "unexpected-signal:$*"; }', + 'gateway_control_stop_tracked_pid() { trace "unexpected-stop:$1"; return 0; }', + extractShellFunction(source, "hermes_role_identity_value"), + extractShellFunction(source, "hermes_set_role_identity"), + extractShellFunction(source, "hermes_stop_tracked_role"), + 'GATEWAY_PID_START_IDENTITY="old-start-time"', + "hermes_stop_tracked_role gateway 4242 gateway 18642", + 'trace "identity:${GATEWAY_PID_START_IDENTITY:-cleared}"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["role-gone", "identity:cleared"]); + expect(result.stdout).not.toContain("unexpected-signal"); + expect(result.stdout).not.toContain("unexpected-stop"); + }); + + it("passes the captured start identity through every tracked stop", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'hermes_role_identity_value() { printf "777"; }', + "hermes_tracked_role_is_current() { return 0; }", + 'gateway_control_stop_tracked_pid() { trace "stop:$1:$2"; }', + 'hermes_set_role_identity() { trace "clear:$1:$2"; }', + extractShellFunction(source, "hermes_stop_tracked_role"), + "hermes_stop_tracked_role gateway 4242 gateway 18642", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("stop:4242:777\nclear:gateway:\n"); + }); + + it("does not accept a tracked-stop success while the numeric PID remains live", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'hermes_role_identity_value() { printf "777"; }', + "hermes_tracked_role_is_current() { return 0; }", + 'gateway_control_stop_tracked_pid() { trace "stop:$1:$2"; return 0; }', + 'kill() { [ "$1" = "-0" ] && return 0; trace "unexpected-signal:$*"; }', + 'hermes_set_role_identity() { trace "unexpected-clear:$1:$2"; }', + extractShellFunction(source, "hermes_stop_tracked_role"), + "rc=0; hermes_stop_tracked_role gateway 4242 gateway 18642 || rc=$?", + 'trace "rc:$rc"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["stop:4242:777", "rc:1"]); + expect(result.stderr).toContain("remains live after tracked stop"); + expect(result.stdout).not.toContain("unexpected-clear"); + expect(result.stdout).not.toContain("unexpected-signal"); + }); + + it("does not signal a launched child whose role identity was never proven", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "tail() { :; }", + "sed() { :; }", + "hermes_capture_tracked_role() { return 1; }", + 'gateway_control_stop_tracked_pid() { trace "unexpected-signal:$1"; }', + extractShellFunction(source, "hermes_fatal_unproven_child"), + extractShellFunction(source, "start_gateway_log_stream"), + "HERMES_STARTUP_SUPERVISOR_PID=1", + "start_gateway_log_stream", + "trace unexpected-return", + ]); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("failed exact role identity capture"); + expect(result.stderr).toContain("exiting PID 1"); + expect(result.stdout).not.toContain("unexpected-signal"); + expect(result.stdout).not.toContain("unexpected-return"); + }); + + it("quarantines a managed supervisor until an unproven direct child is reaped", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'wait() { trace "wait:$1"; return 143; }', + 'sleep() { trace "quarantine-sleep:$1"; exit 0; }', + 'kill() { trace "unexpected-signal:$*"; return 1; }', + extractShellFunction(source, "hermes_fatal_unproven_child"), + "HERMES_STARTUP_SUPERVISOR_PID=77", + "hermes_fatal_unproven_child gateway 4242", + "trace unexpected-return", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["wait:4242", "quarantine-sleep:60"]); + expect(result.stderr).toContain("quarantining the managed startup supervisor"); + expect(result.stderr).toContain("remains quarantined until sandbox recreation"); + expect(result.stdout).not.toContain("unexpected-signal"); + expect(result.stdout).not.toContain("unexpected-return"); + }); + + it("refuses to reap a live recycled gateway PID", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + 'hermes_process_start_identity() { printf "888"; }', + "gateway_control_pid_is_live() { return 0; }", + 'wait() { trace "unexpected-wait:$1"; }', + "mark_hermes_gateway_stopped() { trace unexpected-mark; }", + extractShellFunction(source, "hermes_reap_exited_gateway"), + "rc=0; hermes_reap_exited_gateway || rc=$?", + 'trace "rc:$rc"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("rc:2\n"); + expect(result.stderr).toContain("refusing to poll or reap it"); + expect(result.stdout).not.toContain("unexpected-wait"); + expect(result.stdout).not.toContain("unexpected-mark"); + }); + + it("refuses to wait on a live gateway when role proof becomes unavailable", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + 'hermes_process_start_identity() { printf "777"; }', + 'kill() { [ "$1" = "-0" ] && return 0; trace "unexpected-signal:$*"; }', + 'gateway_control_pid_state() { printf "S"; }', + 'wait() { trace "unexpected-wait:$1"; }', + "mark_hermes_gateway_stopped() { trace unexpected-mark; }", + "GATEWAY_CONTROL_SIGNAL_PENDING=0", + extractShellFunction(source, "hermes_reap_exited_gateway"), + "rc=0; hermes_reap_exited_gateway || rc=$?", + 'trace "rc:$rc"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("rc:2\n"); + expect(result.stderr).toContain("cannot be proven exited"); + expect(result.stdout).not.toContain("unexpected-wait"); + expect(result.stdout).not.toContain("unexpected-mark"); + }); + + it("reaps only an exact matching zombie gateway", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + 'hermes_process_start_identity() { printf "777"; }', + 'kill() { [ "$1" = "-0" ] && return 0; trace "unexpected-signal:$*"; }', + 'gateway_control_pid_state() { printf "Z"; }', + 'wait() { trace "wait:$1"; return 7; }', + "mark_hermes_gateway_stopped() { trace mark-stopped; }", + "GATEWAY_CONTROL_SIGNAL_PENDING=0", + extractShellFunction(source, "hermes_reap_exited_gateway"), + "rc=0; hermes_reap_exited_gateway || rc=$?", + 'trace "rc:$rc"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(["wait:4242", "mark-stopped", "rc:0"]); + expect(result.stderr).toContain("exited (rc=7)"); + expect(result.stdout).not.toContain("unexpected-signal"); + }); + + it("defers reaping a still-proven gateway to a pending authenticated request", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + 'hermes_process_start_identity() { printf "777"; }', + 'kill() { [ "$1" = "-0" ] && return 0; trace "unexpected-signal:$*"; }', + 'gateway_control_pid_state() { printf "S"; }', + "hermes_tracked_role_is_current() { return 0; }", + 'wait() { trace "unexpected-wait:$1"; }', + "mark_hermes_gateway_stopped() { trace unexpected-mark; }", + "GATEWAY_CONTROL_SIGNAL_PENDING=1", + 'INTERNAL_PORT="18642"', + extractShellFunction(source, "hermes_reap_exited_gateway"), + "rc=0; hermes_reap_exited_gateway || rc=$?", + 'trace "rc:$rc"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("rc:3\n"); + expect(result.stdout).not.toContain("unexpected-wait"); + expect(result.stdout).not.toContain("unexpected-mark"); + }); + + it("exits PID 1 instead of marking an unproven gateway stopped", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + "hermes_stop_tracked_role() { trace stop-refused; return 1; }", + "mark_hermes_gateway_stopped() { trace unexpected-mark; }", + extractShellFunction(source, "stop_hermes_gateway_fail_closed"), + "GATEWAY_PID=4242", + 'INTERNAL_PORT="18642"', + "stop_hermes_gateway_fail_closed", + "trace unexpected-return", + ]); + + expect(result.status).toBe(1); + expect(result.stdout).toBe("stop-refused\n"); + expect(result.stderr).toContain("exiting PID 1 for whole-container cleanup"); + expect(result.stdout).not.toContain("unexpected-mark"); + expect(result.stdout).not.toContain("unexpected-return"); + }); + + it("replaces a live but listener-less reused dashboard PID and its stale bridge", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n"; }', + 'gateway_control_pid_is_live() { trace "live:$1"; return 0; }', + 'hermes_tracked_role_is_current() { gateway_control_pid_is_live "$2"; }', + 'gateway_control_pid_owns_tcp_listener() { trace "listener:$1:$2"; [ "$1:$2" = "101:8642" ] || [ "$1:$2" = "303:18789" ]; }', + 'hermes_tracked_service_owns_listener() { trace "service-listener:$1:$2:$3"; return 1; }', + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + "start_hermes_dashboard_sandbox_user() { trace start-dashboard; DASHBOARD_PID=404; DASHBOARD_SOCAT_PID=505; }", + 'start_socat_forwarder() { trace "start-forward:$*"; return 0; }', + "ensure_gateway_log_stream() { trace gateway-log; }", + extractShellFunction(source, "hermes_socat_bridge_healthy"), + extractShellFunction(source, "hermes_dashboard_healthy"), + extractShellFunction(source, "ensure_hermes_supervised_auxiliaries"), + "PUBLIC_PORT=8642", + "INTERNAL_PORT=18642", + "DASHBOARD_PUBLIC_PORT=18789", + "DASHBOARD_INTERNAL_PORT=19119", + "SOCAT_PID=101", + "DASHBOARD_PID=202", + "DASHBOARD_SOCAT_PID=303", + "GATEWAY_PID=4242", + 'if ensure_hermes_supervised_auxiliaries; then trace success; else trace "failure:$?"; fi', + 'trace "final-dashboard:$DASHBOARD_PID"', + 'trace "final-bridge:$DASHBOARD_SOCAT_PID"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "live:101", + "listener:101:8642", + "live:202", + "service-listener:202:19119:sandbox", + "stop:303", + "stop:202", + "start-dashboard", + "gateway-log", + "success", + "final-dashboard:404", + "final-bridge:505", + ]); + }); + + it("replaces a live API bridge PID that owns no public listener", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n"; }', + 'gateway_control_pid_is_live() { trace "live:$1"; return 0; }', + 'hermes_tracked_role_is_current() { gateway_control_pid_is_live "$2"; }', + 'gateway_control_pid_owns_tcp_listener() { trace "listener:$1:$2"; [ "$1:$2" != "101:8642" ]; }', + "hermes_tracked_service_owns_listener() { return 0; }", + 'curl() { printf "200"; }', + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + 'start_socat_forwarder() { trace "start-forward:$*"; printf -v "$4" 111; return 0; }', + "start_hermes_dashboard_sandbox_user() { trace unexpected-dashboard-start; return 1; }", + "ensure_gateway_log_stream() { trace gateway-log; }", + extractShellFunction(source, "hermes_socat_bridge_healthy"), + extractShellFunction(source, "hermes_dashboard_healthy"), + extractShellFunction(source, "ensure_hermes_supervised_auxiliaries"), + "PUBLIC_PORT=8642", + "INTERNAL_PORT=18642", + "DASHBOARD_PUBLIC_PORT=18789", + "DASHBOARD_INTERNAL_PORT=19119", + "SOCAT_PID=101", + "DASHBOARD_PID=202", + "DASHBOARD_SOCAT_PID=303", + "GATEWAY_PID=4242", + 'if ensure_hermes_supervised_auxiliaries; then trace success; else trace "failure:$?"; fi', + 'trace "final-api-bridge:$SOCAT_PID"', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "live:101", + "listener:101:8642", + "stop:101", + "start-forward:8642 18642 API SOCAT_PID 4242 gateway", + "live:202", + "live:303", + "listener:303:18789", + "gateway-log", + "success", + "final-api-bridge:111", + ]); + }); + + it("restarts a dashboard that owns its listener but fails HTTP health", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n"; }', + 'gateway_control_pid_is_live() { trace "live:$1"; return 0; }', + 'hermes_tracked_role_is_current() { gateway_control_pid_is_live "$2"; }', + 'gateway_control_pid_owns_tcp_listener() { trace "listener:$1:$2"; return 0; }', + 'hermes_tracked_service_owns_listener() { trace "service-listener:$1:$2:$3"; return 0; }', + 'curl() { trace dashboard-http; printf "500"; }', + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + "start_hermes_dashboard_sandbox_user() { trace start-dashboard; DASHBOARD_PID=404; DASHBOARD_SOCAT_PID=505; }", + 'start_socat_forwarder() { trace "unexpected-forward:$*"; return 1; }', + "ensure_gateway_log_stream() { trace gateway-log; }", + extractShellFunction(source, "hermes_socat_bridge_healthy"), + extractShellFunction(source, "hermes_dashboard_healthy"), + extractShellFunction(source, "ensure_hermes_supervised_auxiliaries"), + "PUBLIC_PORT=8642", + "INTERNAL_PORT=18642", + "DASHBOARD_PUBLIC_PORT=18789", + "DASHBOARD_INTERNAL_PORT=19119", + "SOCAT_PID=101", + "DASHBOARD_PID=202", + "DASHBOARD_SOCAT_PID=303", + "GATEWAY_PID=4242", + 'if ensure_hermes_supervised_auxiliaries; then trace success; else trace "failure:$?"; fi', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "live:101", + "listener:101:8642", + "live:202", + "service-listener:202:19119:sandbox", + "stop:303", + "stop:202", + "start-dashboard", + "gateway-log", + "success", + ]); + }); + + it("propagates API bridge startup failure without touching the dashboard", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n"; }', + 'gateway_control_pid_is_live() { trace "live:$1"; return 1; }', + 'hermes_tracked_role_is_current() { gateway_control_pid_is_live "$2"; }', + "gateway_control_pid_owns_tcp_listener() { return 1; }", + 'start_socat_forwarder() { trace "start-forward:$*"; return 1; }', + "start_hermes_dashboard_sandbox_user() { trace unexpected-dashboard-start; return 0; }", + 'hermes_stop_tracked_role() { trace "stop:$2"; return 0; }', + "ensure_gateway_log_stream() { trace unexpected-gateway-log; }", + extractShellFunction(source, "hermes_socat_bridge_healthy"), + extractShellFunction(source, "ensure_hermes_supervised_auxiliaries"), + "PUBLIC_PORT=8642", + "INTERNAL_PORT=18642", + "DASHBOARD_PUBLIC_PORT=18789", + "DASHBOARD_INTERNAL_PORT=19119", + "SOCAT_PID=101", + "DASHBOARD_PID=202", + "DASHBOARD_SOCAT_PID=303", + "GATEWAY_PID=4242", + 'if ensure_hermes_supervised_auxiliaries; then trace success; else trace "failure:$?"; fi', + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "live:101", + "stop:101", + "start-forward:8642 18642 API SOCAT_PID 4242 gateway", + "failure:1", + ]); + }); +}); + +describe("Hermes socat bridge startup", () => { + it("fails promptly when the exact service owner exits during readiness", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + "INTERNAL_PORT=18642", + "DASHBOARD_INTERNAL_PORT=19119", + 'trace() { printf "%s\\n" "$*"; }', + 'sleep() { trace "unexpected-sleep:$1"; }', + 'hermes_tracked_role_is_current() { trace "owner-check:$1:$2:$3:$4"; return 1; }', + 'hermes_tracked_service_owns_listener() { trace "unexpected-listener-check"; return 1; }', + "hermes_capture_tracked_role() { return 0; }", + extractShellFunction(source, "start_socat_forwarder"), + 'SOCAT_PID=""', + "if start_socat_forwarder 8642 18642 API SOCAT_PID 4242 current; then rc=0; else rc=$?; fi", + 'printf "RC=%s PID=%s\\n" "$rc" "$SOCAT_PID"', + ], + (tmpDir) => { + const binDir = path.join(tmpDir, "bin"); + fs.mkdirSync(binDir); + fs.writeFileSync(path.join(binDir, "socat"), "#!/usr/bin/env bash\nexit 0\n", { + mode: 0o700, + }); + return { PATH: `${binDir}:${process.env.PATH ?? ""}` }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "owner-check:gateway:4242:current:18642", + "RC=1 PID=", + ]); + expect(result.stdout).not.toContain("unexpected-sleep"); + expect(result.stdout).not.toContain("unexpected-listener-check"); + expect(result.stderr).toContain( + "API service owner pid 4242 exited before binding 127.0.0.1:18642", + ); + }); + + it("refuses to publish a forward when the internal service never binds", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness( + [ + "INTERNAL_PORT=18642", + "DASHBOARD_INTERNAL_PORT=19119", + "ss() { return 0; }", + 'sleep() { [ "${1:-}" = "0.1" ] && /bin/sleep 0.2 || :; }', + "hermes_capture_tracked_role() { return 0; }", + extractShellFunction(source, "start_socat_forwarder"), + 'SOCAT_PID=""', + "if start_socat_forwarder 8642 18642 API SOCAT_PID; then rc=0; else rc=$?; fi", + 'printf "RC=%s PID=%s\\n" "$rc" "$SOCAT_PID"', + ], + (tmpDir) => { + const binDir = path.join(tmpDir, "bin"); + fs.mkdirSync(binDir); + fs.writeFileSync(path.join(binDir, "socat"), "#!/usr/bin/env bash\nexit 0\n", { + mode: 0o700, + }); + return { PATH: `${binDir}:${process.env.PATH ?? ""}` }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("RC=1 PID=\n"); + expect(result.stderr).toContain( + "API service did not bind 127.0.0.1:18642; refusing to publish an empty forward", + ); + }); + + it("rejects a socat listener that exits immediately", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const supervisor = fs.readFileSync(SUPERVISOR_LIB, "utf-8"); + const result = runBashHarness( + [ + "INTERNAL_PORT=18642", + "DASHBOARD_INTERNAL_PORT=19119", + 'ss() { printf "LISTEN 0 128 127.0.0.1:18642 0.0.0.0:*\\n"; }', + "sleep() { :; }", + "kill() { return 0; }", + 'ps() { printf "Z\\n"; }', + "hermes_capture_tracked_role() { return 0; }", + extractShellFunction(supervisor, "gateway_control_pid_is_live"), + extractShellFunction(source, "start_socat_forwarder"), + 'SOCAT_PID=""', + "if start_socat_forwarder 8642 18642 API SOCAT_PID; then rc=0; else rc=$?; fi", + 'printf "RC=%s PID=%s\\n" "$rc" "$SOCAT_PID"', + ], + (tmpDir) => { + const binDir = path.join(tmpDir, "bin"); + fs.mkdirSync(binDir); + fs.writeFileSync(path.join(binDir, "socat"), "#!/usr/bin/env bash\nexit 23\n", { + mode: 0o700, + }); + return { PATH: `${binDir}:${process.env.PATH ?? ""}` }; + }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("RC=1 PID=\n"); + expect(result.stderr).toContain("API socat forwarder failed to stay running on 0.0.0.0:8642"); + }); +}); diff --git a/test/hermes-managed-exit-authorization.test.ts b/test/hermes-managed-exit-authorization.test.ts new file mode 100644 index 00000000000..a2b80fee89c --- /dev/null +++ b/test/hermes-managed-exit-authorization.test.ts @@ -0,0 +1,222 @@ +// 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, "..", "agents", "hermes", "start.sh"); +const SUPERVISOR_LIB = path.join( + import.meta.dirname, + "..", + "scripts", + "lib", + "gateway-supervisor.sh", +); + +type AuthorizationOptions = { + version?: string; + payloadPid?: string; + payloadStartIdentity?: string; + payloadControllerPid?: string; + payloadControllerStartIdentity?: string; + extraField?: string; + trailingData?: string; + directoryMetadata?: string; + markerMetadata?: string; + symlink?: boolean; + markerMissing?: boolean; + controllerPresent?: boolean; + controllerUid?: string; + controllerState?: string; + controllerCmdline?: string[]; +}; + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function extractShellFunction(source: string, name: string): string { + const match = source.match(new RegExp(`${escapeRegExp(name)}\\(\\) \\{([\\s\\S]*?)^\\}`, "m")); + const resolved = + match ?? + (() => { + throw new Error(`Expected ${name} in agents/hermes/start.sh`); + })(); + return `${name}() {${resolved[1]}\n}`; +} + +function runBashHarness(lines: string[], configure?: (tmpDir: string) => Record<string, string>) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-exit-auth-test-")); + const script = path.join(tmpDir, "run.sh"); + fs.writeFileSync(script, ["#!/usr/bin/env bash", "set -uo pipefail", ...lines].join("\n"), { + mode: 0o700, + }); + try { + return spawnSync("bash", [script], { + encoding: "utf-8", + timeout: 5000, + env: { ...process.env, ...configure?.(tmpDir) }, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} + +function runAuthorizationCheck(options: AuthorizationOptions = {}) { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const supervisor = fs.readFileSync(SUPERVISOR_LIB, "utf-8"); + const pid = "4242"; + const startIdentity = "333"; + const controllerPid = "7331"; + const controllerStartIdentity = "888"; + return runBashHarness( + [ + 'stat() { case "$3" in "$HERMES_MANAGED_EXPECTED_EXIT_DIR") printf "%s\\n" "$DIRECTORY_METADATA" ;; *) printf "%s\\n" "$MARKER_METADATA" ;; esac; }', + extractShellFunction(supervisor, "gateway_control_proc_root"), + extractShellFunction(supervisor, "gateway_control_proc_root_is_explicit"), + extractShellFunction(supervisor, "gateway_control_pid_start_identity"), + extractShellFunction(supervisor, "gateway_control_pid_state"), + extractShellFunction(source, "hermes_managed_controller_argv_is_expected"), + extractShellFunction(source, "hermes_managed_controller_is_live"), + extractShellFunction(source, "hermes_managed_gateway_exit_was_host_authorized"), + '_HERMES_PROC_ROOT="$PROC_ROOT"', + 'HERMES_MANAGED_EXPECTED_EXIT_DIR="$LEASE_DIR"', + 'HERMES_MANAGED_EXPECTED_EXIT_MARKER="managed-gateway-expected-exit"', + 'HERMES_MANAGED_CONTROLLER_PATH="/usr/local/lib/nemoclaw/managed-gateway-control.py"', + `if hermes_managed_gateway_exit_was_host_authorized ${pid} ${startIdentity}; then printf "authorized\\n"; else printf "counted\\n"; fi`, + ], + (tmpDir) => { + const leaseDir = path.join(tmpDir, "run", "nemoclaw"); + fs.mkdirSync(leaseDir, { recursive: true, mode: 0o711 }); + const marker = path.join(leaseDir, "managed-gateway-expected-exit"); + const payload = `${options.version ?? "v1"} ${options.payloadPid ?? pid} ${options.payloadStartIdentity ?? startIdentity} ${options.payloadControllerPid ?? controllerPid} ${options.payloadControllerStartIdentity ?? controllerStartIdentity}${options.extraField ? ` ${options.extraField}` : ""}\n${options.trailingData ?? ""}`; + const writeMarker = options.markerMissing + ? () => undefined + : options.symlink + ? () => { + const target = path.join(tmpDir, "attacker-marker"); + fs.writeFileSync(target, payload); + fs.symlinkSync(target, marker); + } + : () => fs.writeFileSync(marker, payload, { mode: 0o444 }); + writeMarker(); + + const procRoot = path.join(tmpDir, "proc"); + fs.mkdirSync(procRoot); + const writeController = + options.controllerPresent === false + ? () => undefined + : () => { + const controllerRoot = path.join(procRoot, controllerPid); + fs.mkdirSync(controllerRoot); + const fields = [ + options.controllerState ?? "S", + "1", + ...Array(17).fill("0"), + controllerStartIdentity, + ]; + fs.writeFileSync( + path.join(controllerRoot, "stat"), + `${controllerPid} (python3) ${fields.join(" ")}\n`, + ); + const uid = options.controllerUid ?? "0"; + fs.writeFileSync( + path.join(controllerRoot, "status"), + `Uid:\t${uid}\t${uid}\t${uid}\t${uid}\n`, + ); + fs.writeFileSync( + path.join(controllerRoot, "cmdline"), + Buffer.from( + `${( + options.controllerCmdline ?? [ + "python3", + "-I", + "/usr/local/lib/nemoclaw/managed-gateway-control.py", + "restart", + "a".repeat(64), + ] + ).join("\0")}\0`, + ), + ); + }; + writeController(); + return { + LEASE_DIR: leaseDir, + PROC_ROOT: procRoot, + DIRECTORY_METADATA: options.directoryMetadata ?? "0:0 711", + MARKER_METADATA: options.markerMetadata ?? "0:0 444 1", + }; + }, + ); +} + +describe("Hermes managed gateway exit authorization", () => { + it("accepts an exact authorization while its root controller identity is live", () => { + const result = runAuthorizationCheck(); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("authorized"); + }); + + it.each([ + ["wrong version", { version: "v2" }], + ["wrong PID", { payloadPid: "4243" }], + ["wrong start identity", { payloadStartIdentity: "334" }], + ["nonnumeric controller PID", { payloadControllerPid: "root" }], + ["wrong controller PID", { payloadControllerPid: "7332" }], + ["nonnumeric controller start identity", { payloadControllerStartIdentity: "future" }], + ["wrong controller start identity", { payloadControllerStartIdentity: "889" }], + ["missing controller", { controllerPresent: false }], + ["dead controller", { controllerState: "Z" }], + ["non-root controller", { controllerUid: "1000" }], + ["unexpected controller argv", { controllerCmdline: ["python3", "/tmp/attacker.py"] }], + ["extra payload field", { extraField: "unexpected" }], + ["trailing payload line", { trailingData: "unexpected\n" }], + ["missing marker", { markerMissing: true }], + ["writable runtime directory", { directoryMetadata: "0:0 733" }], + ["non-root marker", { markerMetadata: "1000:1000 444 1" }], + ["writable marker", { markerMetadata: "0:0 644 1" }], + ["hard-linked marker", { markerMetadata: "0:0 444 2" }], + ["symlink marker", { symlink: true }], + ])("counts an exit when authorization has %s", (_label, options) => { + const result = runAuthorizationCheck(options); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("counted"); + }); + + it("does not charge authenticated host-authorized exits against crash quarantine", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const result = runBashHarness([ + 'trace() { printf "%s\\n" "$*"; }', + 'hermes_tracked_role_is_current() { [ "$2" = "5006" ] && { trace "supervised:$2:crashes=$HERMES_MANAGED_GATEWAY_EXIT_COUNT"; exit 0; }; return 1; }', + 'wait() { trace "wait:$1"; return 143; }', + "mark_hermes_gateway_stopped() { GATEWAY_PID=0; GATEWAY_PID_START_IDENTITY=; }", + 'hermes_managed_gateway_exit_was_host_authorized() { trace "host-exit:$1:$2"; return 0; }', + 'date() { trace unexpected-crash-record; printf "100\\n"; }', + 'sleep() { [ "$1" = "60" ] && { trace unexpected-quarantine; exit 0; }; }', + 'recover_hermes_gateway_current_user() { recover_calls=$((recover_calls + 1)); GATEWAY_PID=$((5000 + recover_calls)); GATEWAY_PID_START_IDENTITY=$((7000 + recover_calls)); trace "recover:$GATEWAY_PID"; }', + "recover_calls=0", + extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), + extractShellFunction(source, "record_hermes_managed_gateway_exit"), + extractShellFunction(source, "supervise_hermes_gateway_current_user"), + "INTERNAL_PORT=18642", + "HERMES_MANAGED_GATEWAY_EXIT_TIMES=(90 95)", + "HERMES_MANAGED_GATEWAY_EXIT_COUNT=2", + "GATEWAY_PID=4242", + "GATEWAY_PID_START_IDENTITY=333", + "supervise_hermes_gateway_current_user", + ]); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.match(/^host-exit:/gm)).toHaveLength(6); + expect(result.stdout.match(/^recover:/gm)).toHaveLength(6); + expect(result.stdout).toContain("host-exit:4242:333"); + expect(result.stdout).toContain("host-exit:5005:7005"); + expect(result.stdout).toContain("supervised:5006:crashes=2"); + expect(result.stdout).not.toContain("unexpected-crash-record"); + expect(result.stdout).not.toContain("unexpected-quarantine"); + expect(result.stderr.match(/without charging crash quarantine/g)).toHaveLength(6); + }); +}); diff --git a/test/hermes-nonroot-strict-hash-reconciliation.test.ts b/test/hermes-nonroot-strict-hash-reconciliation.test.ts new file mode 100644 index 00000000000..8286a186723 --- /dev/null +++ b/test/hermes-nonroot-strict-hash-reconciliation.test.ts @@ -0,0 +1,467 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const RUNTIME_CONFIG_GUARD = path.join( + import.meta.dirname, + "..", + "agents", + "hermes", + "runtime-config-guard.py", +); + +interface ReconciliationFixture { + root: string; + sandboxDir: string; + hermesDir: string; + configPath: string; + envPath: string; + hashPath: string; + compatHashPath: string; + statePath: string; + trustedConfig: string; + trustedEnv: string; +} + +function hashInputs(fixture: ReconciliationFixture): string { + const result = spawnSync("sha256sum", [fixture.configPath, fixture.envPath], { + encoding: "utf-8", + timeout: 5000, + }); + expect(result.status, result.stderr).toBe(0); + return result.stdout; +} + +function createFixture(hermesMode = 0o3770): ReconciliationFixture { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-nonroot-hash-")); + const sandboxDir = path.join(root, "sandbox"); + const hermesDir = path.join(sandboxDir, ".hermes"); + const fixture: ReconciliationFixture = { + root, + sandboxDir, + hermesDir, + configPath: path.join(hermesDir, "config.yaml"), + envPath: path.join(hermesDir, ".env"), + hashPath: path.join(root, "hermes.config-hash"), + compatHashPath: path.join(hermesDir, ".config-hash"), + statePath: path.join(root, "hermes-restart-seal.json"), + trustedConfig: "model:\n default: trusted-model\n", + trustedEnv: "API_SERVER_PORT=18642\nSAFE_SETTING=trusted\n", + }; + fs.mkdirSync(hermesDir, { recursive: true }); + fs.chmodSync(sandboxDir, 0o770); + fs.chmodSync(hermesDir, hermesMode); + fs.writeFileSync(fixture.configPath, fixture.trustedConfig, { mode: 0o640 }); + fs.writeFileSync(fixture.envPath, fixture.trustedEnv, { mode: 0o600 }); + const trustedHash = hashInputs(fixture); + fs.writeFileSync(fixture.hashPath, trustedHash, { mode: 0o600 }); + fs.writeFileSync(fixture.compatHashPath, trustedHash, { mode: 0o600 }); + return fixture; +} + +function writeConfigArgs(fixture: ReconciliationFixture, expectedDigest: string): string[] { + return [ + "write-config", + "--hermes-dir", + fixture.hermesDir, + "--hash-file", + fixture.hashPath, + "--state-file", + fixture.statePath, + "--expected-config-sha256", + expectedDigest, + ]; +} + +function runSourceWrite(fixture: ReconciliationFixture, expectedDigest: string, content: string) { + return spawnSync("python3", [RUNTIME_CONFIG_GUARD, ...writeConfigArgs(fixture, expectedDigest)], { + encoding: "utf-8", + input: content, + timeout: 5000, + }); +} + +function runManagedNonrootWrite( + fixture: ReconciliationFixture, + expectedDigest: string, + content: string, +) { + const wrapper = String.raw` +import importlib.util +import os +import sys + +source = sys.argv[1] +spec = importlib.util.spec_from_file_location("nemoclaw_runtime_config_guard_fixture", source) +if spec is None or spec.loader is None: + raise SystemExit("could not load runtime guard fixture") +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +module._managed_nonroot_reconciliation_is_allowed = lambda: True +module._sandbox_identity = lambda: (os.geteuid(), os.getegid()) +sys.argv = [source, *sys.argv[2:]] +raise SystemExit(module.main()) +`; + return spawnSync( + "python3", + ["-c", wrapper, RUNTIME_CONFIG_GUARD, ...writeConfigArgs(fixture, expectedDigest)], + { encoding: "utf-8", input: content, timeout: 5000 }, + ); +} + +function refreshCompatOnly(fixture: ReconciliationFixture): void { + fs.writeFileSync(fixture.compatHashPath, hashInputs(fixture)); +} + +function strictHashIsValid(fixture: ReconciliationFixture): boolean { + return ( + spawnSync("sha256sum", ["-c", fixture.hashPath, "--status"], { + encoding: "utf-8", + timeout: 5000, + }).status === 0 + ); +} + +function expectedConfigDigest(fixture: ReconciliationFixture): string { + return createHash("sha256").update(fixture.trustedConfig).digest("hex"); +} + +function assertCleanRefusal(fixture: ReconciliationFixture, strictBefore: string): void { + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe(strictBefore); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); +} + +describe.skipIf(process.platform === "win32")( + "Hermes managed non-root strict hash reconciliation", + () => { + it("admits only the installed, markerless, uniquely supervised non-root topology", () => { + const probe = String.raw` +import importlib.util +import json +import os +import sys +import types + +source = sys.argv[1] +spec = importlib.util.spec_from_file_location("nemoclaw_runtime_config_guard_gate", source) +if spec is None or spec.loader is None: + raise SystemExit("could not load runtime guard fixture") +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +module.pwd.getpwnam = lambda _name: types.SimpleNamespace(pw_uid=1234) +module.INSTALLED_RUNTIME_CONFIG_GUARD = os.path.abspath(module.__file__) +module._startup_ready_marker_absent = lambda: True +module._openshell_supervised_nonroot_start_is_live = lambda root_uid, sandbox_uid: (root_uid, sandbox_uid) == (0, 1234) +allowed = module._managed_nonroot_reconciliation_is_allowed() +module._startup_ready_marker_absent = lambda: False +marker_present = module._managed_nonroot_reconciliation_is_allowed() +module._startup_ready_marker_absent = lambda: True +module._openshell_supervised_nonroot_start_is_live = lambda _root_uid, _sandbox_uid: False +not_supervised = module._managed_nonroot_reconciliation_is_allowed() +module.INSTALLED_RUNTIME_CONFIG_GUARD = "/different/installed/path" +source_helper = module._managed_nonroot_reconciliation_is_allowed() +print(json.dumps([allowed, marker_present, not_supervised, source_helper])) +`; + const result = spawnSync("python3", ["-c", probe, RUNTIME_CONFIG_GUARD], { + encoding: "utf-8", + timeout: 5000, + }); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([true, false, false, false]); + }); + + it("admits only sandbox-owned writable private-live or canonical-mutable metadata (#2426)", () => { + const probe = String.raw` +import importlib.util +import json +import sys + +source = sys.argv[1] +spec = importlib.util.spec_from_file_location("nemoclaw_runtime_config_guard_posture", source) +if spec is None or spec.loader is None: + raise SystemExit("could not load runtime guard fixture") +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +module._sandbox_identity = lambda: (1234, 1234) + +def files(mode=0o640, uid=1234, gid=1234): + return { + name: {"original": {"mode": mode, "uid": uid, "gid": gid}} + for name in ("config.yaml", ".env", ".config-hash") + } + +allowed = module._mutable_nonroot_reconciliation_posture_is_allowed +private_live = allowed({"mode": 0o700, "uid": 1234, "gid": 1234}, files()) +canonical_mutable = allowed({"mode": 0o3770, "uid": 1234, "gid": 1234}, files()) +foreign_private = allowed({"mode": 0o700, "uid": 0, "gid": 0}, files(uid=0, gid=0)) +unexpected_mode = allowed({"mode": 0o770, "uid": 1234, "gid": 1234}, files()) +locked = allowed({"mode": 0o755, "uid": 0, "gid": 0}, files(0o444, 0, 0)) +read_only_input = files() +read_only_input[".env"]["original"]["mode"] = 0o440 +partly_read_only = allowed({"mode": 0o700, "uid": 1234, "gid": 1234}, read_only_input) +group_writable = allowed({"mode": 0o700, "uid": 1234, "gid": 1234}, files(0o660)) +world_writable = allowed({"mode": 0o700, "uid": 1234, "gid": 1234}, files(0o666)) +print(json.dumps([private_live, canonical_mutable, foreign_private, unexpected_mode, locked, partly_read_only, group_writable, world_writable])) +`; + const result = spawnSync("python3", ["-c", probe, RUNTIME_CONFIG_GUARD], { + encoding: "utf-8", + timeout: 5000, + }); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + true, + true, + false, + false, + false, + false, + false, + false, + ]); + }); + + it.each([ + ["private live", 0o700], + ["canonical mutable", 0o3770], + ])("reconciles only the generated startup API key from the %s posture and completes the config transaction (#2426)", (_label, hermesMode) => { + const fixture = createFixture(hermesMode); + const generatedKey = "a".repeat(64); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${generatedKey}\n`); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + + try { + expect(strictHashIsValid(fixture)).toBe(false); + const updatedConfig = "model:\n default: trusted-model-v2\n"; + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + updatedConfig, + ); + expect(result.status, result.stderr).toBe(0); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(updatedConfig); + expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe( + `${fixture.trustedEnv}API_SERVER_KEY=${generatedKey}\n`, + ); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).not.toBe(strictBefore); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( + fs.readFileSync(fixture.compatHashPath, "utf-8"), + ); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses strict reconciliation from the shields-up root-locked posture (#2426)", () => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"8".repeat(64)}\n`); + refreshCompatOnly(fixture); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("outside mutable Hermes posture"); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("preserves the write-config shields-up refusal when the strict hash is current (#2426)", () => { + const fixture = createFixture(); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("config writes are unavailable while shields are up"); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses an unproven source-helper topology", () => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"b".repeat(64)}\n`); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const result = runSourceWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("outside managed non-root startup"); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it.each([ + ["weak", "API_SERVER_KEY=weak\n"], + ["export-prefixed", `export API_SERVER_KEY=${"c".repeat(64)}\n`], + ["single-quoted", `API_SERVER_KEY='${"d".repeat(64)}'\n`], + ["missing-final-newline", `API_SERVER_KEY=${"e".repeat(64)}`], + ["CRLF", `API_SERVER_KEY=${"f".repeat(64)}\r\n`], + ["duplicate", `API_SERVER_KEY=${"1".repeat(64)}\nAPI_SERVER_KEY=${"2".repeat(64)}\n`], + ])("refuses a %s API key delta", (_label, apiKeyText) => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, apiKeyText); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/API_SERVER_KEY change/u); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses a stale compatibility hash", () => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"3".repeat(64)}\n`); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("compat hash does not match frozen Hermes inputs"); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it.each([ + ["missing final LF", (text: string) => text.replace(/\n$/u, "")], + ["CRLF records", (text: string) => text.replace(/\n/gu, "\r\n")], + ])("refuses a strict hash with %s", (_label, mutate) => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"4".repeat(64)}\n`); + refreshCompatOnly(fixture); + const malformed = mutate(fs.readFileSync(fixture.hashPath, "utf-8")); + fs.writeFileSync(fixture.hashPath, malformed); + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("malformed Hermes config hash"); + assertCleanRefusal(fixture, malformed); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses any env drift beyond the generated API key", () => { + const fixture = createFixture(); + fs.appendFileSync( + fixture.envPath, + `API_SERVER_KEY=${"5".repeat(64)}\nUNEXPECTED_SETTING=attacker-controlled\n`, + ); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const result = runManagedNonrootWrite( + fixture, + expectedConfigDigest(fixture), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("non-API-key env drift"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses config drift even when compat and the host read match it", () => { + const fixture = createFixture(); + const driftedConfig = "model:\n default: attacker-model\n"; + fs.writeFileSync(fixture.configPath, driftedConfig); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"6".repeat(64)}\n`); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const result = runManagedNonrootWrite( + fixture, + createHash("sha256").update(driftedConfig).digest("hex"), + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("refusing config drift"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(driftedConfig); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps the host-read compare-and-swap requirement", () => { + const fixture = createFixture(); + fs.appendFileSync(fixture.envPath, `API_SERVER_KEY=${"7".repeat(64)}\n`); + refreshCompatOnly(fixture); + const strictBefore = fs.readFileSync(fixture.hashPath, "utf-8"); + try { + const staleHostDigest = createHash("sha256").update("stale host read\n").digest("hex"); + const result = runManagedNonrootWrite( + fixture, + staleHostDigest, + "model:\n default: must-not-apply\n", + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("config changed after the host read"); + assertCleanRefusal(fixture, strictBefore); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + }, +); diff --git a/test/hermes-restart-config-seal.test.ts b/test/hermes-restart-config-seal.test.ts new file mode 100644 index 00000000000..a36cd41a87a --- /dev/null +++ b/test/hermes-restart-config-seal.test.ts @@ -0,0 +1,1333 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const RUNTIME_CONFIG_GUARD = path.join( + import.meta.dirname, + "..", + "agents", + "hermes", + "runtime-config-guard.py", +); + +interface RestartFixture { + root: string; + sandboxDir: string; + hermesDir: string; + configPath: string; + envPath: string; + hashPath: string; + compatHashPath: string; + statePath: string; + trustedConfig: string; + trustedEnv: string; +} + +function mode(pathname: string): number { + return fs.statSync(pathname).mode & 0o7777; +} + +function createRestartFixture(): RestartFixture { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-restart-seal-")); + const sandboxDir = path.join(root, "sandbox"); + const hermesDir = path.join(sandboxDir, ".hermes"); + const configPath = path.join(hermesDir, "config.yaml"); + const envPath = path.join(hermesDir, ".env"); + const hashPath = path.join(root, "hermes.config-hash"); + const compatHashPath = path.join(hermesDir, ".config-hash"); + const statePath = path.join(root, "hermes-restart-seal.json"); + const trustedConfig = "model:\n default: trusted-model\n"; + const trustedEnv = "API_SERVER_PORT=18642\nSAFE_SETTING=trusted\n"; + + fs.mkdirSync(hermesDir, { recursive: true }); + fs.chmodSync(sandboxDir, 0o770); + fs.chmodSync(hermesDir, 0o3770); + fs.writeFileSync(configPath, trustedConfig, { mode: 0o640 }); + fs.chmodSync(configPath, 0o640); + fs.writeFileSync(envPath, trustedEnv, { mode: 0o600 }); + fs.chmodSync(envPath, 0o600); + + const hash = spawnSync("sha256sum", [configPath, envPath], { + encoding: "utf-8", + timeout: 5000, + }); + expect(hash.status, hash.stderr).toBe(0); + fs.writeFileSync(hashPath, hash.stdout, { mode: 0o600 }); + fs.writeFileSync(compatHashPath, hash.stdout, { mode: 0o600 }); + + return { + root, + sandboxDir, + hermesDir, + configPath, + envPath, + hashPath, + compatHashPath, + statePath, + trustedConfig, + trustedEnv, + }; +} + +function runWriteConfig(fixture: RestartFixture, expectedDigest: string, content: string) { + return spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "write-config", + "--hermes-dir", + fixture.hermesDir, + "--hash-file", + fixture.hashPath, + "--state-file", + fixture.statePath, + "--expected-config-sha256", + expectedDigest, + ], + { encoding: "utf-8", input: content, timeout: 5000 }, + ); +} + +function writeMutationLock(fixture: RestartFixture, token: string): string { + const lockPath = path.join(fixture.root, "hermes-config-mutation.lock"); + fs.writeFileSync( + lockPath, + `${JSON.stringify({ + version: 1, + token, + purpose: "seal-restart", + pid: 999_999_999, + pid_start_time: "1", + })}\n`, + { mode: 0o600 }, + ); + return lockPath; +} + +function runGuard(action: "seal-restart" | "unseal-restart", fixture: RestartFixture) { + const args = [ + RUNTIME_CONFIG_GUARD, + action, + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + ]; + args.push(...(action === "seal-restart" ? ["--hash-file", fixture.hashPath] : [])); + return spawnSync("python3", args, { + encoding: "utf-8", + timeout: 5000, + }); +} + +function runShieldsTransition(fixture: RestartFixture, shieldsMode: "locked" | "mutable") { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: shieldsMode, + }); + switch (begun.status) { + case 0: + break; + default: + return begun; + } + const token = shieldsTransactionToken(begun.stdout); + switch (token) { + case undefined: + throw new Error("Expected begin-shields-transition to emit a token"); + default: + break; + } + switch (shieldsMode) { + case "locked": + // The production host restores 0755 only after the recursive state guard's + // independent verification pass. This focused top-guard fixture has no + // recursive state, so model that successful handoff explicitly. + fs.chmodSync(fixture.hermesDir, 0o755); + break; + case "mutable": + break; + } + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + switch (applied.status) { + case 0: + break; + default: + return applied; + } + return runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); +} + +function runShieldsTransactionAction( + fixture: RestartFixture, + action: + | "begin-shields-transition" + | "apply-shields-transition" + | "finish-shields-transition" + | "prepare-shields-abort" + | "abort-shields-transition" + | "inspect-mutation-owner", + options: { + mode?: "locked" | "mutable"; + rollbackMode?: "locked" | "mutable"; + token?: string; + } = {}, +) { + const args = [ + RUNTIME_CONFIG_GUARD, + action, + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + ]; + args.push( + ...(action === "begin-shields-transition" || action === "finish-shields-transition" + ? ["--hash-file", fixture.hashPath] + : []), + ...(options.mode ? ["--shields-mode", options.mode] : []), + ...(options.rollbackMode ? ["--rollback-shields-mode", options.rollbackMode] : []), + ...(options.token ? ["--lock-token", options.token] : []), + ); + return spawnSync("python3", args, { encoding: "utf-8", timeout: 5000 }); +} + +function strictHashIsValid(fixture: RestartFixture): boolean { + return ( + spawnSync("sha256sum", ["-c", fixture.hashPath, "--status"], { + encoding: "utf-8", + timeout: 5000, + }).status === 0 + ); +} + +function shieldsTransactionToken(output: string): string | undefined { + return /^lock_token=([0-9a-f]{64}) original_locked=[01]\s*$/.exec(output)?.[1]; +} + +function overwriteThroughOldFd(fd: number, originalSize: number, byte: string): void { + const attackerBytes = Buffer.alloc(originalSize, byte); + fs.writeSync(fd, attackerBytes, 0, attackerBytes.length, 0); + fs.fsyncSync(fd); +} + +describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { + it("atomically binds a host config write to the bytes that were read and refreshes both hashes", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + const updatedConfig = "model:\n default: trusted-model-v2\n"; + + try { + const updated = runWriteConfig(fixture, expectedDigest, updatedConfig); + + expect(updated.status, updated.stderr).toBe(0); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(updatedConfig); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( + fs.readFileSync(fixture.compatHashPath, "utf-8"), + ); + expect(strictHashIsValid(fixture)).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps a maximum-size config write journal below its bounded state cap", { + timeout: 60_000, + }, () => { + const fixture = createRestartFixture(); + const boundarySize = 16 * 1024 * 1024; + const originalConfig = `${"a".repeat(boundarySize - 1)}\n`; + const updatedConfig = `${"b".repeat(boundarySize - 1)}\n`; + fs.writeFileSync(fixture.configPath, originalConfig); + const hash = spawnSync("sha256sum", [fixture.configPath, fixture.envPath], { + encoding: "utf-8", + timeout: 10_000, + }); + expect(hash.status, hash.stderr).toBe(0); + fs.writeFileSync(fixture.hashPath, hash.stdout); + fs.writeFileSync(fixture.compatHashPath, hash.stdout); + const expectedDigest = createHash("sha256").update(originalConfig).digest("hex"); + + try { + const updated = spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "write-config", + "--hermes-dir", + fixture.hermesDir, + "--hash-file", + fixture.hashPath, + "--state-file", + fixture.statePath, + "--expected-config-sha256", + expectedDigest, + ], + { encoding: "utf-8", input: updatedConfig, timeout: 45_000 }, + ); + expect(updated.status, updated.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).size).toBe(boundarySize); + expect(createHash("sha256").update(fs.readFileSync(fixture.configPath)).digest("hex")).toBe( + createHash("sha256").update(updatedConfig).digest("hex"), + ); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses to launder a stale host read and leaves the trusted config unchanged", () => { + const fixture = createRestartFixture(); + const staleDigest = createHash("sha256").update("attacker-controlled read\n").digest("hex"); + + try { + const updated = runWriteConfig( + fixture, + staleDigest, + "model:\n default: attacker-derived-model\n", + ); + + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config changed after the host read"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses host config writes while shields are up and restores the locked posture", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + fs.chmodSync(fixture.sandboxDir, 0o755); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + + try { + const updated = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: must-not-apply\n", + ); + + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config writes are unavailable while shields are up"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("serializes restart sealing against a host-held shields mutation lock", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + + try { + const lockPath = writeMutationLock(fixture, token); + + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("config mutation is already in progress"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o770); + + fs.unlinkSync(lockPath); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("recovers a dead mutation lock published before seal state creation", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + try { + const lockPath = writeMutationLock(fixture, token); + expect(fs.existsSync(lockPath)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + const recovered = spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "recover-prestate-lock", + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + "--startup-owner", + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(recovered.status, recovered.stderr).toBe(0); + expect(recovered.stdout.trim()).toBe("recovered=1"); + expect(fs.existsSync(lockPath)).toBe(false); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rejects a host config transaction while another Hermes mutation owns the lock", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + + try { + const lockPath = writeMutationLock(fixture, token); + + const updated = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: should-not-commit\n", + ); + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config mutation is already in progress"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + + fs.unlinkSync(lockPath); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rolls back a config-write phase killed after rename but before strict hash refresh", () => { + const fixture = createRestartFixture(); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const state = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + state.phase = "config-write-prepared"; + state.config_write = { + original_base64: Buffer.from(fixture.trustedConfig).toString("base64"), + original_sha256: createHash("sha256").update(fixture.trustedConfig).digest("hex"), + }; + fs.writeFileSync(fixture.statePath, `${JSON.stringify(state)}\n`, { mode: 0o600 }); + fs.chmodSync(fixture.statePath, 0o600); + + const replacement = path.join(fixture.hermesDir, ".config.crash-test"); + fs.writeFileSync(replacement, "model:\n default: interrupted-write\n", { mode: 0o444 }); + fs.chmodSync(replacement, 0o444); + fs.renameSync(replacement, fixture.configPath); + expect(strictHashIsValid(fixture)).toBe(false); + + const recovered = runGuard("unseal-restart", fixture); + expect(recovered.status, recovered.stderr).toBe(0); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("revokes pre-open writable fds while preserving trusted path bytes and strict hashes", () => { + const fixture = createRestartFixture(); + const configBefore = fs.statSync(fixture.configPath); + const envBefore = fs.statSync(fixture.envPath); + const configFd = fs.openSync(fixture.configPath, "r+"); + const envFd = fs.openSync(fixture.envPath, "r+"); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const configSealed = fs.statSync(fixture.configPath); + const envSealed = fs.statSync(fixture.envPath); + expect(configSealed.ino).not.toBe(configBefore.ino); + expect(envSealed.ino).not.toBe(envBefore.ino); + expect(configSealed.uid).toBe(process.getuid!()); + expect(envSealed.uid).toBe(process.getuid!()); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(configSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); + expect(envSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); + expect(mode(fixture.statePath)).toBe(0o600); + expect(strictHashIsValid(fixture)).toBe(true); + + overwriteThroughOldFd(configFd, configBefore.size, "X"); + overwriteThroughOldFd(envFd, envBefore.size, "Y"); + + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.statSync(fixture.configPath).ino).toBe(configSealed.ino); + expect(fs.statSync(fixture.envPath).ino).toBe(envSealed.ino); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.statSync(fixture.configPath).uid).toBe(configBefore.uid); + expect(fs.statSync(fixture.configPath).gid).toBe(configBefore.gid); + expect(fs.statSync(fixture.envPath).uid).toBe(envBefore.uid); + expect(fs.statSync(fixture.envPath).gid).toBe(envBefore.gid); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.closeSync(configFd); + fs.closeSync(envFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("revokes pre-open descriptors across shields lock and restores the mutable contract", () => { + const fixture = createRestartFixture(); + const configBefore = fs.statSync(fixture.configPath); + const envBefore = fs.statSync(fixture.envPath); + const compatBefore = fs.statSync(fixture.compatHashPath); + const configFd = fs.openSync(fixture.configPath, "r+"); + const envFd = fs.openSync(fixture.envPath, "r+"); + const compatFd = fs.openSync(fixture.compatHashPath, "r+"); + + try { + const locked = runShieldsTransition(fixture, "locked"); + expect(locked.status, locked.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); + expect(fs.statSync(fixture.compatHashPath).ino).not.toBe(compatBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(mode(fixture.compatHashPath)).toBe(0o444); + + overwriteThroughOldFd(configFd, configBefore.size, "X"); + overwriteThroughOldFd(envFd, envBefore.size, "Y"); + overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + + const mutable = runShieldsTransition(fixture, "mutable"); + expect(mutable.status, mutable.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o640); + expect(mode(fixture.compatHashPath)).toBe(0o640); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + false, + ); + } finally { + fs.closeSync(configFd); + fs.closeSync(envFd); + fs.closeSync(compatFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("holds the mutation lock through begin, apply, verification, and finish", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + + const owner = runShieldsTransactionAction(fixture, "inspect-mutation-owner"); + expect(owner.status, owner.stderr).toBe(0); + expect(owner.stdout).toContain("owner_active=1"); + expect(owner.stdout).toContain("recovery_safe=0"); + + const competingRestart = runGuard("seal-restart", fixture); + expect(competingRestart.status).not.toBe(0); + expect(competingRestart.stderr).toContain("restart seal is already active"); + const competingWrite = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: must-not-interleave\n", + ); + expect(competingWrite.status).not.toBe(0); + expect(competingWrite.stderr).toContain("restart seal is already active"); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + expect(applied.stdout).toContain("shields_mode=locked"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.sandboxDir)).toBe(0o755); + + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + false, + ); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps weakening fan-out inaccessible and keeps monotonic lock fan-out readable", () => { + for (const targetMode of ["mutable", "locked"] as const) { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: targetMode, + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(targetMode === "mutable" ? 0o700 : 0o500); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(abortState.shields_transition.mode).toBe("mutable"); + // State-dir rollback is another recursive transition. It remains + // root-only until abort commits the original posture. + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o3770); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + } + }); + + it("retains the 0500 recursive clamp and resumes the same lock transaction", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(0o500); + + const premature = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(premature.status).not.toBe(0); + expect(premature.stderr).toContain("retaining root-only 0500 clamp for retry"); + expect(mode(fixture.hermesDir)).toBe(0o500); + expect(fs.existsSync(fixture.statePath)).toBe(true); + + const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(resumed.status, resumed.stderr).toBe(0); + expect(shieldsTransactionToken(resumed.stdout)).toBe(token); + expect(mode(fixture.hermesDir)).toBe(0o500); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("cold-resumes an applied lock transaction before its final commit", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + + const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(resumed.status, resumed.stderr).toBe(0); + expect(shieldsTransactionToken(resumed.stdout)).toBe(token); + expect(mode(fixture.hermesDir)).toBe(0o500); + fs.chmodSync(fixture.hermesDir, 0o755); + const reapplied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(reapplied.status, reapplied.stderr).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(mode(fixture.hermesDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("takes over an expired applied mutable transition only after its worker lease ends", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o1775); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + let staleFd: number | undefined; + try { + const mutableBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(mutableBegin.status, mutableBegin.stderr).toBe(0); + const mutableToken = shieldsTransactionToken(mutableBegin.stdout); + expect(mutableToken).toMatch(/^[0-9a-f]{64}$/); + const mutableApply = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: mutableToken, + }); + expect(mutableApply.status, mutableApply.stderr).toBe(0); + staleFd = fs.openSync(fixture.configPath, "r+"); + + const premature = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(premature.status).not.toBe(0); + expect(premature.stderr).toContain("mutable transition lease has not expired"); + + const staleState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + staleState.shields_transition.lease_expires_ns = 1; + fs.writeFileSync(fixture.statePath, `${JSON.stringify(staleState)}\n`, { mode: 0o600 }); + const beforeTakeoverInode = fs.statSync(fixture.configPath).ino; + const lockedBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(lockedBegin.status, lockedBegin.stderr).toBe(0); + const lockedToken = shieldsTransactionToken(lockedBegin.stdout); + expect(lockedToken).toMatch(/^[0-9a-f]{64}$/); + expect(lockedToken).not.toBe(mutableToken); + expect(fs.statSync(fixture.configPath).ino).not.toBe(beforeTakeoverInode); + expect(mode(fixture.hermesDir)).toBe(0o500); + const sealedBytes = fs.readFileSync(fixture.configPath); + overwriteThroughOldFd(staleFd, sealedBytes.length, "X"); + expect(fs.readFileSync(fixture.configPath)).toEqual(sealedBytes); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: lockedToken, + }).status, + ).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token: lockedToken, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + for (const openFd of staleFd === undefined ? [] : [staleFd]) fs.closeSync(openFd); + fs.chmodSync(fixture.sandboxDir, 0o700); + for (const existingHermesDir of fs.existsSync(fixture.hermesDir) ? [fixture.hermesDir] : []) { + fs.chmodSync(existingHermesDir, 0o700); + } + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("hardens mutable modes and stale hashes from the frozen current bytes", () => { + const fixture = createRestartFixture(); + const configBefore = fs.statSync(fixture.configPath).ino; + fs.chmodSync(fixture.configPath, 0o666); + fs.chmodSync(fixture.envPath, 0o666); + fs.writeFileSync(fixture.hashPath, "stale strict hash\n"); + fs.writeFileSync(fixture.compatHashPath, "stale compatibility hash\n"); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(false); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( + fs.readFileSync(fixture.compatHashPath, "utf-8"), + ); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, + ).toBe(0); + expect( + runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, + ).toBe(0); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + for (const oversizedName of ["config.yaml", ".env"] as const) { + it(`contains an oversized sparse ${oversizedName} without reading its logical payload`, () => { + const fixture = createRestartFixture(); + const oversizedPath = oversizedName === "config.yaml" ? fixture.configPath : fixture.envPath; + fs.truncateSync( + oversizedPath, + oversizedName === "config.yaml" ? 16 * 1024 * 1024 + 1 : 4 * 1024 * 1024 + 1, + ); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + expect(transition.shields_transition.unavailable_reasons.join("\n")).toContain( + "oversized runtime config path", + ); + expect(fs.statSync(oversizedPath).size).toBeLessThan(1024); + expect(mode(oversizedPath)).toBe(0o400); + expect(mode(fixture.hermesDir)).toBe(0o500); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + it("fresh-seals a hardlinked input and revokes the external writable inode", () => { + const fixture = createRestartFixture(); + const external = path.join(fixture.root, "external-config"); + fs.unlinkSync(fixture.configPath); + fs.writeFileSync(external, fixture.trustedConfig, { mode: 0o666 }); + fs.linkSync(external, fixture.configPath); + const linkedInode = fs.statSync(external).ino; + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(fs.statSync(fixture.configPath).ino).not.toBe(linkedInode); + expect(fs.statSync(fixture.configPath).nlink).toBe(1); + expect( + JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")).shields_transition.unavailable, + ).toBe(false); + fs.writeFileSync(external, "attacker rewrite\n"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, + ).toBe(0); + expect( + runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, + ).toBe(0); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + for (const hostileKind of ["symlink", "fifo"] as const) { + it(`seals a hostile ${hostileKind} config entry into a root-only unavailable posture`, () => { + const fixture = createRestartFixture(); + fs.unlinkSync(fixture.configPath); + const arrangeHostileConfig = { + symlink: () => { + const victim = path.join(fixture.root, "victim"); + fs.writeFileSync(victim, "victim stays untouched\n"); + fs.symlinkSync(victim, fixture.configPath); + }, + fifo: () => expect(spawnSync("mkfifo", [fixture.configPath]).status).toBe(0), + } satisfies Record<typeof hostileKind, () => void>; + arrangeHostileConfig[hostileKind](); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + expect(fs.lstatSync(fixture.configPath).isFile()).toBe(true); + expect(mode(fixture.configPath)).toBe(0o400); + expect(mode(fixture.hermesDir)).toBe(0o500); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status).not.toBe(0); + expect(applied.stderr).toContain("sealed root-only and is unavailable"); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + for (const hostileKind of ["symlink", "fifo"] as const) { + it(`quarantines an outer .hermes ${hostileKind} only after freezing /sandbox`, () => { + const fixture = createRestartFixture(); + fs.rmSync(fixture.hermesDir, { recursive: true, force: true }); + const victim = path.join(fixture.root, "outer-victim"); + const arrangeHostileHome = { + symlink: () => { + fs.mkdirSync(victim); + fs.writeFileSync(path.join(victim, "proof"), "untouched\n"); + fs.symlinkSync(victim, fixture.hermesDir); + }, + fifo: () => expect(spawnSync("mkfifo", [fixture.hermesDir]).status).toBe(0), + } satisfies Record<typeof hostileKind, () => void>; + arrangeHostileHome[hostileKind](); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + expect(fs.lstatSync(fixture.hermesDir).isDirectory()).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + for (const proofPath of hostileKind === "symlink" ? [path.join(victim, "proof")] : []) { + expect(fs.readFileSync(proofPath, "utf-8")).toBe("untouched\n"); + } + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + it("re-seals an applied mutable transition before recursive rollback", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { token }); + expect(applied.status, applied.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o3770); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { token }); + expect(prepared.status, prepared.stderr).toBe(0); + const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(abortState.shields_transition.mode).toBe("locked"); + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { token }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it.runIf( + process.platform === "linux" && + process.getuid?.() === 0 && + spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, + )("keeps the locked Hermes entry sticky-protected while allowing ordinary home writes", () => { + const fixture = createRestartFixture(); + + try { + const locked = runShieldsTransition(fixture, "locked"); + expect(locked.status, locked.stderr).toBe(0); + const parent = fs.statSync(fixture.sandboxDir); + expect(parent.uid).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(fs.statSync(fixture.hermesDir).uid).toBe(0); + + const peer = spawnSync( + "setpriv", + [ + "--reuid=65534", + "--regid=65534", + `--groups=${String(parent.gid)}`, + "sh", + "-c", + 'touch "$1/peer-home-file" || exit 10; mv "$1/.hermes" "$1/.hermes-moved" 2>/dev/null && exit 20; test -d "$1/.hermes"', + "sh", + fixture.sandboxDir, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + + expect(peer.status, peer.stderr).toBe(0); + expect(fs.existsSync(path.join(fixture.sandboxDir, "peer-home-file"))).toBe(true); + expect(fs.existsSync(fixture.hermesDir)).toBe(true); + expect(fs.existsSync(path.join(fixture.sandboxDir, ".hermes-moved"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses to finish after the sealed Hermes directory is swapped", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + + const displaced = path.join(fixture.sandboxDir, ".hermes.displaced"); + fs.renameSync(fixture.hermesDir, displaced); + fs.mkdirSync(fixture.hermesDir, { mode: 0o755 }); + + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status).not.toBe(0); + expect(finished.stderr).toContain("refusing shields finish because .hermes changed"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps the transaction sealed when abort finds a corrupted compatibility hash", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + + fs.unlinkSync(fixture.compatHashPath); + fs.writeFileSync(fixture.compatHashPath, "attacker-controlled hash\n", { mode: 0o444 }); + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + + expect(aborted.status).not.toBe(0); + expect(aborted.stderr).toContain("compat hash verification failed"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.sandboxDir)).toBe(0o700); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("revokes descriptors opened after mutable apply before rolling back to locked", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o1775); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + let mutableFd: number | undefined; + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + expect(begun.stdout).toContain("original_locked=1"); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + const appliedInode = fs.statSync(fixture.configPath).ino; + mutableFd = fs.openSync(fixture.configPath, "r+"); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(appliedInode); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + fs.writeSync(mutableFd, Buffer.from("PWNED!"), 0, 6, 0); + fs.fsyncSync(mutableFd); + + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + for (const openFd of mutableFd === undefined ? [] : [mutableFd]) fs.closeSync(openFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rejects a foreign shields token and lets the owner abort to the exact prior posture", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + const foreign = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: randomBytes(32).toString("hex"), + }); + expect(foreign.status).not.toBe(0); + expect(foreign.stderr).toContain("lock token mismatch"); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o640); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("fails closed without replacing or locking paths when the strict hash is stale", () => { + const fixture = createRestartFixture(); + const configBefore = fs.statSync(fixture.configPath); + const envBefore = fs.statSync(fixture.envPath); + fs.writeFileSync(fixture.configPath, "model:\n default: attacker-model\n"); + + try { + const sealed = runGuard("seal-restart", fixture); + + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("strict hash verification failed"); + expect(fs.statSync(fixture.configPath).ino).toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).toBe(envBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("does not bless a compat hash changed through a pre-open descriptor", () => { + const fixture = createRestartFixture(); + const compatBefore = fs.statSync(fixture.compatHashPath); + const compatFd = fs.openSync(fixture.compatHashPath, "r+"); + + try { + overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); + const sealed = runGuard("seal-restart", fixture); + + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("compat hash verification failed"); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.readFileSync(fixture.compatHashPath, "utf-8")).not.toBe( + fs.readFileSync(fixture.hashPath, "utf-8"), + ); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.closeSync(compatFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("preserves an already trusted shields-up directory posture across seal and unseal", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o755); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + const configBefore = fs.statSync(fixture.configPath); + const envBefore = fs.statSync(fixture.envPath); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(fs.statSync(fixture.hermesDir).uid).toBe(process.getuid!()); + expect(strictHashIsValid(fixture)).toBe(true); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it.runIf( + process.platform === "linux" && + process.getuid?.() === 0 && + spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, + )("lets a sandbox-group peer create state but not unlink sealed config names", () => { + const fixture = createRestartFixture(); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const hermesGid = fs.statSync(fixture.hermesDir).gid; + const peer = spawnSync( + "setpriv", + [ + "--reuid=65534", + "--regid=65534", + `--groups=${hermesGid}`, + "sh", + "-c", + 'touch "$1/peer-runtime-state" || exit 10; rm "$1/config.yaml" 2>/dev/null && exit 20; test -f "$1/config.yaml"', + "sh", + fixture.hermesDir, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + + expect(peer.status, peer.stderr).toBe(0); + expect(fs.existsSync(path.join(fixture.hermesDir, "peer-runtime-state"))).toBe(true); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-runtime-api-key.test.ts b/test/hermes-runtime-api-key.test.ts index b244569c883..05440f2c1df 100644 --- a/test/hermes-runtime-api-key.test.ts +++ b/test/hermes-runtime-api-key.test.ts @@ -68,6 +68,7 @@ function runHermesRuntimeApiServerKeyMint( envFile?: string; mode?: "strict" | "compat"; fakeRoot?: boolean; + locked?: boolean; envPathKind?: "regular" | "symlink" | "hardlink"; configPathKind?: "regular" | "symlink"; } = {}, @@ -105,6 +106,12 @@ function runHermesRuntimeApiServerKeyMint( writeEnvPath[opts.envPathKind ?? "regular"](); writeHermesHash(hashPath, configPath, envPath); writeHermesHash(compatHashPath, configPath, envPath); + for (const _locked of opts.locked ? [true] : []) { + fs.chmodSync(hermesHome, 0o755); + fs.chmodSync(configPath, 0o444); + fs.chmodSync(envPath, 0o444); + fs.chmodSync(compatHashPath, 0o444); + } const src = fs.readFileSync(START_SCRIPT, "utf-8"); fs.writeFileSync( @@ -357,6 +364,58 @@ function runHermesRuntimeProviderPlaceholderRefresh(opts: { } describe("agents/hermes/start.sh runtime API server key", () => { + it("runs the startup guard in isolated mode as the calling shell's direct child", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-direct-child-")); + const hermesHome = path.join(tmpDir, ".hermes"); + const fakePython = path.join(tmpDir, "python"); + const ppidFile = path.join(tmpDir, "guard.ppid"); + const argsFile = path.join(tmpDir, "guard.args"); + const script = path.join(tmpDir, "run.sh"); + fs.mkdirSync(hermesHome); + fs.writeFileSync(path.join(hermesHome, ".env"), "API_SERVER_KEY=fixture\n"); + fs.writeFileSync( + fakePython, + '#!/usr/bin/env bash\nprintf "%s\\n" "$PPID" >"$PPID_FILE"\nprintf "%s\\n" "$@" >"$ARGS_FILE"\nprintf "minted=0\\n"\n', + { mode: 0o700 }, + ); + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + fs.writeFileSync( + script, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + extractShellFunctionFromSource(source, "ensure_hermes_runtime_api_server_key"), + `HERMES_DIR=${shellQuote(hermesHome)}`, + `HERMES_HASH_FILE=${shellQuote(path.join(tmpDir, "strict.hash"))}`, + `_HERMES_PYTHON=${shellQuote(fakePython)}`, + `_HERMES_RUNTIME_CONFIG_GUARD=${shellQuote(RUNTIME_CONFIG_GUARD)}`, + `PPID_FILE=${shellQuote(ppidFile)}`, + `ARGS_FILE=${shellQuote(argsFile)}`, + "export PPID_FILE ARGS_FILE", + "EXPECTED_PARENT=$BASHPID", + "ensure_hermes_runtime_api_server_key strict", + 'ACTUAL_PARENT="$(cat "$PPID_FILE")"', + 'printf "expected=%s actual=%s\\n" "$EXPECTED_PARENT" "$ACTUAL_PARENT"', + '[ "$EXPECTED_PARENT" = "$ACTUAL_PARENT" ]', + ].join("\n"), + { mode: 0o700 }, + ); + try { + const result = spawnSync("bash", [script], { + encoding: "utf-8", + timeout: 5000, + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toMatch(/^expected=([0-9]+) actual=\1\n$/); + expect(fs.readFileSync(argsFile, "utf-8").trim().split("\n").slice(0, 2)).toEqual([ + "-I", + RUNTIME_CONFIG_GUARD, + ]); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("mints API_SERVER_KEY at startup and refreshes Hermes config hashes", () => { const run = runHermesRuntimeApiServerKeyMint({ fakeRoot: true }); @@ -371,6 +430,17 @@ describe("agents/hermes/start.sh runtime API server key", () => { expect(run.result.stderr).not.toContain(run.apiServerKey ?? "missing-key"); }); + it("refuses to mint an API key into a shields-up env", () => { + const run = runHermesRuntimeApiServerKeyMint({ fakeRoot: true, locked: true }); + + expect(run.result.status).not.toBe(0); + expect(run.result.stderr).toContain("cannot update .env while shields are up"); + expect(run.apiServerKey).toBeNull(); + expect(run.envFileMode).toBe("444"); + expect(run.strictHashValid).toBe(true); + expect(run.compatHashValid).toBe(true); + }); + it("does not rotate an existing API_SERVER_KEY on restart", () => { const existingKey = "a".repeat(64); const run = runHermesRuntimeApiServerKeyMint({ @@ -704,12 +774,16 @@ describe("agents/hermes/start.sh runtime API server key", () => { "SLACK_APP_TOKEN=xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN\n", ); expect(run.envFileContent).not.toContain("openshell:resolve:env"); - expect(run.result.stderr).toContain("Normalized SLACK_BOT_TOKEN"); - expect(run.result.stderr).toContain("Normalized SLACK_APP_TOKEN"); + expect(run.result.stderr).toContain( + "[config] Refreshed Hermes provider placeholder for SLACK_BOT_TOKEN", + ); + expect(run.result.stderr).toContain( + "[config] Refreshed Hermes provider placeholder for SLACK_APP_TOKEN", + ); expect(run.strictHashValid).toBe(true); }); - it("refresh_hermes_provider_placeholders passes --runtime-plan only for regular artifacts", () => { + it("refreshes provider placeholders through isolated Python and passes only regular artifacts", () => { const present = runExtractedProviderPlaceholderRefresh({ runtimePlanPathKind: "regular" }); const absent = runExtractedProviderPlaceholderRefresh({ runtimePlanPathKind: "absent" }); const brokenSymlink = runExtractedProviderPlaceholderRefresh({ @@ -719,13 +793,16 @@ describe("agents/hermes/start.sh runtime API server key", () => { expect(present.result.status, present.result.stderr).toBe(0); expect(absent.result.status, absent.result.stderr).toBe(0); expect(brokenSymlink.result.status, brokenSymlink.result.stderr).toBe(0); + expect(present.args.slice(0, 2)).toEqual(["-I", RUNTIME_CONFIG_GUARD]); + expect(absent.args.slice(0, 2)).toEqual(["-I", RUNTIME_CONFIG_GUARD]); + expect(brokenSymlink.args.slice(0, 2)).toEqual(["-I", RUNTIME_CONFIG_GUARD]); expect(present.args).toContain("--runtime-plan"); expect(present.args).toContain(present.runtimePlanPath); expect(absent.args).not.toContain("--runtime-plan"); expect(absent.args).not.toContain(absent.runtimePlanPath); expect(brokenSymlink.args).not.toContain("--runtime-plan"); expect(brokenSymlink.args).not.toContain(brokenSymlink.runtimePlanPath); - }); + }, 15_000); it.each([ { diff --git a/test/hermes-runtime-config-guard.test.ts b/test/hermes-runtime-config-guard.test.ts new file mode 100644 index 00000000000..6d0000c2c79 --- /dev/null +++ b/test/hermes-runtime-config-guard.test.ts @@ -0,0 +1,1058 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const RUNTIME_CONFIG_GUARD = path.join( + import.meta.dirname, + "..", + "agents", + "hermes", + "runtime-config-guard.py", +); + +function runPythonHarness(source: string) { + return spawnSync("python3", ["-c", source, RUNTIME_CONFIG_GUARD], { + encoding: "utf-8", + timeout: 5000, + }); +} + +const loadGuardModule = String.raw` +import importlib.util +import sys + +spec = importlib.util.spec_from_file_location("runtime_config_guard", sys.argv[1]) +guard = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = guard +spec.loader.exec_module(guard) +`; + +describe("Hermes runtime config hash refresh race protection", () => { + it("creates an absent private runtime directory through its pinned parent", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import stat +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + parent = os.path.join(tmp, "run") + runtime = os.path.join(parent, "nemoclaw") + os.mkdir(parent, 0o700) + guard._ensure_private_runtime_directory(runtime, os.geteuid(), os.getegid(), 0o711) + guard._ensure_private_runtime_directory(runtime, os.geteuid(), os.getegid(), 0o711) + metadata = os.stat(runtime, follow_symlinks=False) + print(json.dumps({ + "directory": stat.S_ISDIR(metadata.st_mode), + "mode": stat.S_IMODE(metadata.st_mode), + "uid": metadata.st_uid, + "gid": metadata.st_gid, + })) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + directory: true, + mode: 0o711, + uid: process.getuid?.() ?? 0, + gid: process.getgid?.() ?? 0, + }); + }); + + it("provisions only the fixed production state and lock pair", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +calls = [] +guard.os.geteuid = lambda: 0 +guard.os.getegid = lambda: 0 +guard._ensure_private_runtime_directory = ( + lambda path, uid, gid, mode: calls.append([path, uid, gid, mode]) +) +guard._ensure_production_runtime_directory( + guard.HERMES_MUTATION_LOCK_FILE, + guard.HERMES_RESTART_STATE_FILE, +) +guard._ensure_production_runtime_directory( + "/tmp/attacker.lock", + "/tmp/attacker-state.json", +) +print(json.dumps(calls)) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([["/run/nemoclaw", 0, 0, 0o711]]); + }); + + it("refuses unsafe runtime parents, children, symlinks, and non-root production", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +errors = {} +with tempfile.TemporaryDirectory() as tmp: + parent = os.path.join(tmp, "run") + runtime = os.path.join(parent, "nemoclaw") + os.mkdir(parent, 0o700) + target = os.path.join(tmp, "target") + os.mkdir(target, 0o700) + os.symlink(target, runtime) + try: + guard._ensure_private_runtime_directory( + runtime, os.geteuid(), os.getegid(), 0o711 + ) + except guard.UnsafePathError as exc: + errors["symlink"] = str(exc) + + os.unlink(runtime) + os.mkdir(runtime, 0o700) + os.chmod(runtime, 0o733) + try: + guard._ensure_private_runtime_directory( + runtime, os.geteuid(), os.getegid(), 0o711 + ) + except guard.UnsafePathError as exc: + errors["writable_child"] = str(exc) + + os.rmdir(runtime) + os.chmod(parent, 0o733) + try: + guard._ensure_private_runtime_directory( + runtime, os.geteuid(), os.getegid(), 0o711 + ) + except guard.UnsafePathError as exc: + errors["writable_parent"] = str(exc) + +guard.os.geteuid = lambda: 1000 +guard.os.getegid = lambda: 1000 +try: + guard._ensure_production_runtime_directory( + guard.HERMES_MUTATION_LOCK_FILE, + guard.HERMES_RESTART_STATE_FILE, + ) +except guard.UnsafePathError as exc: + errors["nonroot"] = str(exc) + +print(json.dumps(errors)) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + nonroot: "Hermes production runtime state requires root", + symlink: "Hermes runtime state directory is unavailable", + writable_child: "refusing unsafe Hermes runtime state directory", + writable_parent: "refusing unsafe Hermes runtime state parent", + }); + }); + + it("warns once for unsupported directory fsync and propagates real I/O failures", () => { + const result = runPythonHarness(`${loadGuardModule} +import contextlib +import errno +import io +import json + +def unsupported_fsync(_fd): + raise OSError(errno.EOPNOTSUPP, "directory fsync unsupported") + +guard.os.fsync = unsupported_fsync +warnings = io.StringIO() +with contextlib.redirect_stderr(warnings): + guard._fsync_directory_after_replace(10) + guard._fsync_directory_after_replace(10) + +def failed_fsync(_fd): + raise OSError(errno.EIO, "storage I/O failed") + +guard.os.fsync = failed_fsync +try: + guard._fsync_directory_after_replace(10) +except OSError as exc: + failure_errno = exc.errno +else: + failure_errno = None + +print(json.dumps({ + "warning_lines": warnings.getvalue().strip().splitlines(), + "failure_errno": failure_errno, +})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + failure_errno: 5, + warning_lines: [ + "[security] directory fsync is unsupported; the atomic Hermes config rename completed without a directory durability barrier", + ], + }); + }); + + it("streams SHA-256 without materializing the entire file", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "config.yaml") + with open(path, "wb") as handle: + handle.write(b"streamed hash input\\n") + original = guard.OpenFile.read_bytes + guard.OpenFile.read_bytes = lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError("hash path materialized bytes") + ) + try: + entry, snapshot = guard._sha256_entry(path, guard.MAX_CONFIG_INPUT_BYTES) + finally: + guard.OpenFile.read_bytes = original + print(json.dumps({ + "digest": entry.split()[0], + "size": snapshot.size, + })) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof.size).toBe(20); + expect(proof.digest).toMatch(/^[0-9a-f]{64}$/); + }); + + it("rejects an oversized sparse input before issuing a read", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "config.yaml") + with open(path, "wb") as handle: + handle.truncate(guard.MAX_CONFIG_INPUT_BYTES + 1) + opened = guard._open_regular(path) + reads = 0 + original_read = guard.os.read + def counted_read(*args, **kwargs): + global reads + reads += 1 + return original_read(*args, **kwargs) + guard.os.read = counted_read + try: + try: + opened.read_bytes(guard.MAX_CONFIG_INPUT_BYTES) + except guard.UnsafePathError as exc: + error = str(exc) + else: + error = "" + finally: + guard.os.read = original_read + opened.close() + print(json.dumps({"error": error, "reads": reads})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + reads: 0, + }); + expect(JSON.parse(result.stdout).error).toContain("oversized runtime config path"); + }); + + it("bounds restart journals before publishing them", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + os.chmod(tmp, 0o700) + state = os.path.join(tmp, "state.json") + guard.MAX_RESTART_STATE_BYTES = 128 + try: + guard._write_restart_state( + state, + {"version": 1, "payload": "x" * 512}, + create=True, + ) + except guard.UnsafePathError as exc: + error = str(exc) + else: + error = "" + print(json.dumps({"error": error, "exists": os.path.exists(state)})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + error: "refusing oversized Hermes restart seal state", + exists: false, + }); + }); + + it("rejects a same-inode, same-size config rewrite between snapshots", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + hermes_dir = os.path.join(tmp, ".hermes") + os.mkdir(hermes_dir) + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + hash_path = os.path.join(tmp, "hermes.config-hash") + with open(config_path, "wb") as handle: + handle.write(b"model: one\\n") + with open(env_path, "wb") as handle: + handle.write(b"API_SERVER_PORT=18642\\n") + + before = os.stat(config_path) + original_write_hash = guard._write_hash + + def racing_write_hash(path, text): + original_write_hash(path, text) + if path == hash_path: + with open(config_path, "r+b", buffering=0) as handle: + handle.write(b"model: two\\n") + # Make the metadata transition deterministic even on filesystems + # whose natural timestamp granularity is too coarse for this race. + after_write = os.stat(config_path) + os.utime( + config_path, + ns=(after_write.st_atime_ns, before.st_mtime_ns + 1_000_000_000), + ) + + guard._write_hash = racing_write_hash + try: + guard.refresh_hashes(hermes_dir, hash_path, "strict") + except guard.UnsafePathError as exc: + rejected = True + error = str(exc) + else: + rejected = False + error = "" + + after = os.stat(config_path) + print(json.dumps({ + "rejected": rejected, + "error": error, + "same_inode": before.st_ino == after.st_ino, + "same_size": before.st_size == after.st_size, + "content": open(config_path, "rb").read().decode("utf-8"), + })) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof).toMatchObject({ + rejected: true, + same_inode: true, + same_size: true, + content: "model: two\n", + }); + expect(proof.error).toContain("refusing raced Hermes config/env path before hash refresh"); + }); + + it("writes strict and compatibility hashes from one stable input snapshot", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + hermes_dir = os.path.join(tmp, ".hermes") + os.mkdir(hermes_dir) + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + strict_hash_path = os.path.join(tmp, "hermes.config-hash") + compat_hash_path = os.path.join(hermes_dir, ".config-hash") + with open(config_path, "w", encoding="utf-8") as handle: + handle.write("model:\\n default: test-model\\n") + with open(env_path, "w", encoding="utf-8") as handle: + handle.write("API_SERVER_PORT=18642\\n") + + original_hash_text = guard._hash_text + original_write_hash = guard._write_hash + hash_text_calls = 0 + writes = [] + + def counted_hash_text(config, env): + global hash_text_calls + hash_text_calls += 1 + return original_hash_text(config, env) + + def captured_write_hash(path, text): + writes.append({"path": path, "text": text}) + original_write_hash(path, text) + + guard._hash_text = counted_hash_text + guard._write_hash = captured_write_hash + guard.refresh_hashes(hermes_dir, strict_hash_path, "both") + + with open(strict_hash_path, encoding="utf-8") as handle: + strict_text = handle.read() + with open(compat_hash_path, encoding="utf-8") as handle: + compat_text = handle.read() + print(json.dumps({ + "hash_text_calls": hash_text_calls, + "write_paths": [entry["path"] for entry in writes], + "write_texts_match": len(writes) == 2 and writes[0]["text"] == writes[1]["text"], + "files_match": strict_text == compat_text, + "config_entry_count": strict_text.count(config_path), + "env_entry_count": strict_text.count(env_path), + })) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof).toMatchObject({ + hash_text_calls: 1, + write_texts_match: true, + files_match: true, + config_entry_count: 1, + env_entry_count: 1, + }); + expect(proof.write_paths).toHaveLength(2); + expect(proof.write_paths[0]).toMatch(/\.hermes\/\.config-hash$/); + expect(proof.write_paths[1]).toMatch(/\/hermes\.config-hash$/); + }); + + it("leaves the strict trust anchor uncommitted if compatibility refresh is interrupted", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + hermes_dir = os.path.join(tmp, ".hermes") + os.mkdir(hermes_dir) + config_path = os.path.join(hermes_dir, "config.yaml") + env_path = os.path.join(hermes_dir, ".env") + strict_hash_path = os.path.join(tmp, "hermes.config-hash") + compat_hash_path = os.path.join(hermes_dir, ".config-hash") + with open(config_path, "w", encoding="utf-8") as handle: + handle.write("model:\\n default: old-model\\n") + with open(env_path, "w", encoding="utf-8") as handle: + handle.write("API_SERVER_PORT=18642\\n") + + guard.refresh_hashes(hermes_dir, strict_hash_path, "both") + with open(strict_hash_path, encoding="utf-8") as handle: + old_strict = handle.read() + with open(config_path, "w", encoding="utf-8") as handle: + handle.write("model:\\n default: new-model\\n") + + original_write_hash = guard._write_hash + writes = [] + + def interrupt_after_write(path, text): + writes.append(path) + original_write_hash(path, text) + if path == compat_hash_path: + raise RuntimeError("simulated crash before strict commit") + + guard._write_hash = interrupt_after_write + try: + guard.refresh_hashes(hermes_dir, strict_hash_path, "both") + except RuntimeError as exc: + interrupted = str(exc) + else: + interrupted = "" + + with open(strict_hash_path, encoding="utf-8") as handle: + strict_after = handle.read() + with open(compat_hash_path, encoding="utf-8") as handle: + compat_after = handle.read() + try: + guard._verify_strict_hash(hermes_dir, strict_hash_path) + except guard.UnsafePathError: + strict_rejects = True + else: + strict_rejects = False + + print(json.dumps({ + "interrupted": interrupted, + "writes": writes, + "strict_unchanged": strict_after == old_strict, + "anchors_differ": strict_after != compat_after, + "strict_rejects": strict_rejects, + })) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof.interrupted).toBe("simulated crash before strict commit"); + expect(proof.writes).toHaveLength(1); + expect(proof.writes[0]).toMatch(/\.hermes\/\.config-hash$/); + expect(proof).toMatchObject({ + strict_unchanged: true, + anchors_differ: true, + strict_rejects: true, + }); + }); +}); + +describe("Hermes provider placeholder diagnostics", () => { + it("logs only validated environment keys, never runtime-plan message content", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + env_path = os.path.join(tmp, ".env") + plan_path = os.path.join(tmp, "runtime-plan.json") + with open(env_path, "w", encoding="utf-8") as handle: + handle.write("SLACK_BOT_TOKEN=old-placeholder\\n") + with open(plan_path, "w", encoding="utf-8") as handle: + json.dump({ + "channels": [{"channelId": "slack", "active": True}], + "runtimeSetup": { + "envAliases": [{ + "channelId": "slack", + "envKey": "SLACK_BOT_TOKEN", + "match": "^openshell:resolve:env:SLACK_BOT_TOKEN$", + "value": "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + "message": "Authorization: Bearer should-never-be-logged", + }], + }, + }, handle) + + os.environ["SLACK_BOT_TOKEN"] = "openshell:resolve:env:SLACK_BOT_TOKEN" + guard._validate_env_text_with_boundary = lambda *_args: None + guard.refresh_hashes = lambda *_args: None + guard.provider_placeholders( + tmp, + os.path.join(tmp, ".config-hash"), + "compat", + plan_path, + "unused-boundary-validator", + ) + with open(env_path, "r", encoding="utf-8") as handle: + print(handle.read(), end="") +`); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("SLACK_BOT_TOKEN=xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN\n"); + expect(result.stderr).toContain( + "[config] Refreshed Hermes provider placeholder for SLACK_BOT_TOKEN", + ); + expect(result.stderr).not.toContain("Authorization"); + expect(result.stderr).not.toContain("should-never-be-logged"); + }); +}); + +describe("Hermes shields outer namespace containment", () => { + it("keeps the exact state worker PID alive as the in-container timeout owner", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +captured = {} +guard._claim_transition_worker = lambda state, token, purpose: { + "shields_transition": {"mode": "locked"} +} +guard.os.path.isfile = lambda _path: True +guard.signal.alarm = lambda seconds: captured.update({"alarm": seconds}) +def capture_exec(program, argv): + captured.update({"program": program, "argv": argv}) + raise RuntimeError("exec captured") +guard.os.execvp = capture_exec +try: + guard.run_state_dir_transition( + "/sandbox/.hermes", + "/run/nemoclaw/hermes-restart-seal.json", + "a" * 64, + "lock", + ) +except RuntimeError as exc: + captured["error"] = str(exc) +print(json.dumps(captured)) +`); + + expect(result.status, result.stderr).toBe(0); + const captured = JSON.parse(result.stdout); + expect(captured).toMatchObject({ + alarm: 0, + program: "timeout", + error: "exec captured", + }); + expect(captured.argv.slice(0, 5)).toEqual([ + "timeout", + "--signal=TERM", + "--kill-after=5s", + "12m", + expect.stringMatching(/python(?:3(?:\.\d+)?)?$/), + ]); + expect(captured.argv.slice(5)).toEqual([ + "/usr/local/lib/nemoclaw/state-dir-guard.py", + "lock", + "--config-dir", + "/sandbox/.hermes", + ]); + }); + + it("refuses mutable takeover while the exact claimed worker is live", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile +import time + +with tempfile.TemporaryDirectory() as tmp: + os.chmod(tmp, 0o700) + token = "b" * 64 + state_path = os.path.join(tmp, "state.json") + lock_path = os.path.join(tmp, "hermes-config-mutation.lock") + state = { + "version": 1, + "phase": "shields-transition-applied", + "mutation_lock_token": token, + "mutation_lock_path": lock_path, + "hermes_dir": "/sandbox/.hermes", + "hash_file": "/etc/nemoclaw/hermes.config-hash", + "parent": {"dev": 1, "ino": 1}, + "hermes": {"dev": 1, "ino": 2}, + "shields_transition": { + "mode": "mutable", + "lease_expires_ns": 1, + }, + } + with open(state_path, "w", encoding="utf-8") as handle: + json.dump(state, handle) + os.chmod(state_path, 0o600) + with open(lock_path, "w", encoding="utf-8") as handle: + json.dump({ + "version": 1, + "token": token, + "purpose": "state-dir-unlock", + "pid": 1234, + "pid_start_time": "99", + }, handle) + os.chmod(lock_path, 0o600) + guard._mutation_lock_owner_is_live = lambda _owner: True + try: + guard._takeover_expired_mutable_transition( + "/sandbox/.hermes", + "/etc/nemoclaw/hermes.config-hash", + state_path, + ) + except guard.UnsafePathError as exc: + error = str(exc) + else: + error = "" + print(json.dumps({"error": error, "state_exists": os.path.exists(state_path)})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + error: "Hermes mutable transition worker is still active; retry locked takeover", + state_exists: true, + }); + }); + + it("claims the expired mutable owner before freezing its namespace", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + os.chmod(tmp, 0o700) + token = "c" * 64 + state_path = os.path.join(tmp, "state.json") + lock_path = os.path.join(tmp, "hermes-config-mutation.lock") + state = { + "version": 1, + "phase": "shields-transition-applied", + "mutation_lock_token": token, + "mutation_lock_path": lock_path, + "hermes_dir": "/sandbox/.hermes", + "hash_file": "/etc/nemoclaw/hermes.config-hash", + "parent": {"dev": 1, "ino": 1}, + "hermes": {"dev": 1, "ino": 2}, + "shields_transition": {"mode": "mutable", "lease_expires_ns": 1}, + } + with open(state_path, "w", encoding="utf-8") as handle: + json.dump(state, handle) + os.chmod(state_path, 0o600) + with open(lock_path, "w", encoding="utf-8") as handle: + json.dump({ + "version": 1, + "token": token, + "purpose": "apply-shields-transition", + "pid": 1234, + "pid_start_time": "99", + }, handle) + os.chmod(lock_path, 0o600) + guard._mutation_lock_owner_is_live = lambda _owner: False + events = [] + def lose_claim(_state_path, _token, _purpose): + events.append("claim") + raise guard.UnsafePathError("simulated competing worker claim") + guard._claim_transition_worker = lose_claim + guard._open_directory = lambda _path: events.append("freeze") + try: + guard._takeover_expired_mutable_transition( + "/sandbox/.hermes", + "/etc/nemoclaw/hermes.config-hash", + state_path, + ) + except guard.UnsafePathError as exc: + error = str(exc) + else: + error = "" + print(json.dumps({"error": error, "events": events})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + error: "simulated competing worker claim", + events: ["claim"], + }); + }); + + it("freezes the parent before opening .hermes", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import tempfile + +with tempfile.TemporaryDirectory() as tmp: + os.chmod(tmp, 0o700) + sandbox = os.path.join(tmp, "sandbox") + hermes = os.path.join(sandbox, ".hermes") + os.makedirs(hermes) + os.chmod(sandbox, 0o770) + os.chmod(hermes, 0o3770) + with open(os.path.join(hermes, "config.yaml"), "wb") as handle: + handle.write(b"model: test\\n") + with open(os.path.join(hermes, ".env"), "wb") as handle: + handle.write(b"SAFE=1\\n") + with open(os.path.join(hermes, ".config-hash"), "wb") as handle: + handle.write(b"stale\\n") + strict = os.path.join(tmp, "strict.hash") + with open(strict, "wb") as handle: + handle.write(b"stale\\n") + state = os.path.join(tmp, "state.json") + + original_open_child = guard._open_child_directory + observed = [] + def checked_open_child(parent_fd, name, path): + if name == ".hermes": + parent = os.fstat(parent_fd) + observed.append({ + "mode": oct(parent.st_mode & 0o7777), + "uid": parent.st_uid, + }) + return original_open_child(parent_fd, name, path) + guard._open_child_directory = checked_open_child + try: + guard._seal_shields_locked(hermes, strict, state, "mutable") + finally: + guard._open_child_directory = original_open_child + print(json.dumps({ + "observed": observed, + "parent_mode": oct(os.stat(sandbox).st_mode & 0o7777), + "hermes_mode": oct(os.stat(hermes).st_mode & 0o7777), + })) + os.chmod(hermes, 0o700) + os.chmod(sandbox, 0o700) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof.observed[0]).toMatchObject({ mode: "0o700" }); + expect(proof).toMatchObject({ + parent_mode: "0o700", + hermes_mode: "0o500", + }); + }); + + it("rejects a cross-device .hermes without mutating the mounted child", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +import os +import stat +import tempfile +from types import SimpleNamespace + +with tempfile.TemporaryDirectory() as tmp: + os.chmod(tmp, 0o700) + sandbox = os.path.join(tmp, "sandbox") + hermes = os.path.join(sandbox, ".hermes") + os.makedirs(hermes) + os.chmod(sandbox, 0o770) + os.chmod(hermes, 0o3770) + strict = os.path.join(tmp, "strict.hash") + with open(strict, "wb") as handle: + handle.write(b"stale\\n") + state = os.path.join(tmp, "state.json") + original_stat = guard.os.stat + child_before = original_stat(hermes) + def cross_device_stat(path, *args, **kwargs): + result = original_stat(path, *args, **kwargs) + if path == ".hermes" and kwargs.get("dir_fd") is not None and kwargs.get("follow_symlinks") is False: + return SimpleNamespace( + st_mode=result.st_mode, + st_dev=result.st_dev + 1, + st_ino=result.st_ino, + st_uid=result.st_uid, + st_gid=result.st_gid, + st_nlink=result.st_nlink, + st_size=result.st_size, + st_mtime_ns=result.st_mtime_ns, + st_ctime_ns=result.st_ctime_ns, + ) + return result + guard.os.stat = cross_device_stat + try: + try: + guard._seal_shields_locked(hermes, strict, state, "mutable") + except guard.UnsafePathError as exc: + error = str(exc) + else: + error = "" + finally: + guard.os.stat = original_stat + child_after = original_stat(hermes) + print(json.dumps({ + "error": error, + "parent_mode": oct(original_stat(sandbox).st_mode & 0o7777), + "child_mode_unchanged": (child_before.st_mode & 0o7777) == (child_after.st_mode & 0o7777), + "child_inode_unchanged": child_before.st_ino == child_after.st_ino, + })) + os.chmod(sandbox, 0o700) +`); + + expect(result.status, result.stderr).toBe(0); + const proof = JSON.parse(result.stdout); + expect(proof.error).toContain("cross-device Hermes config root"); + expect(proof).toMatchObject({ + parent_mode: "0o700", + child_mode_unchanged: true, + child_inode_unchanged: true, + }); + }); +}); + +describe("Hermes startup readiness lease", () => { + it("fails closed under foreign PID 1 only for the installed guard entrypoint", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +guard._pid1_is_nemoclaw_start = lambda: False +source_entrypoint = guard.__file__ +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError: + source_allowed = False +else: + source_allowed = True + +guard.__file__ = guard.INSTALLED_RUNTIME_CONFIG_GUARD +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError as exc: + installed_error = str(exc) +else: + installed_error = "" +guard._startup_ready_for_current_pid1 = lambda: True +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError: + remapped_allowed = False +else: + remapped_allowed = True +finally: + guard.__file__ = source_entrypoint +print(json.dumps({ + "source_allowed": source_allowed, + "installed_error": installed_error, + "remapped_allowed": remapped_allowed, +})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + source_allowed: true, + installed_error: "Hermes runtime config guard refuses mutation under a foreign PID 1", + remapped_allowed: true, + }); + }); + + it("permits degraded host actions only when NemoClaw PID 1 is non-root", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +guard._pid1_is_nemoclaw_start = lambda: True +guard._startup_ready_for_current_pid1 = lambda: False +guard._process_effective_uid = lambda pid: 1000 if pid == 1 else None +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError: + nonroot_allowed = False +else: + nonroot_allowed = True + +guard._process_effective_uid = lambda pid: 0 if pid == 1 else None +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError as exc: + root_error = str(exc) +else: + root_error = "" +print(json.dumps({"nonroot_allowed": nonroot_allowed, "root_error": root_error})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + nonroot_allowed: true, + root_error: "Hermes startup is not ready for host config or gateway mutations", + }); + }); + + it("authenticates the markerless OpenShell supervisor topology narrowly", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +guard.__file__ = guard.INSTALLED_RUNTIME_CONFIG_GUARD +guard._pid1_is_nemoclaw_start = lambda: False +guard._startup_ready_for_current_pid1 = lambda: False +guard._startup_ready_marker_absent = lambda: True +guard.pwd.getpwnam = lambda _name: type("User", (), {"pw_uid": 1000})() +guard.os.getppid = lambda: 4242 +guard._openshell_supervised_nonroot_start_is_live = lambda root_uid, sandbox_uid, required_pid=None: ( + root_uid == 0 + and sandbox_uid == 1000 + and required_pid in {None, 4242} +) + +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError: + host_allowed = False +else: + host_allowed = True + +try: + guard._validate_action_readiness("ensure-api-key", True) +except guard.UnsafePathError: + startup_allowed = False +else: + startup_allowed = True + +try: + guard._validate_action_readiness("ensure-api-key", False) +except guard.UnsafePathError: + startup_without_owner_allowed = False +else: + startup_without_owner_allowed = True + +guard._startup_ready_marker_absent = lambda: False +try: + guard._validate_action_readiness("seal-restart", False) +except guard.UnsafePathError as exc: + stale_marker_error = str(exc) +else: + stale_marker_error = "" + +print(json.dumps({ + "host_allowed": host_allowed, + "startup_allowed": startup_allowed, + "startup_without_owner_allowed": startup_without_owner_allowed, + "stale_marker_error": stale_marker_error, +})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + host_allowed: true, + startup_allowed: true, + startup_without_owner_allowed: false, + stale_marker_error: "Hermes runtime config guard refuses mutation under a foreign PID 1", + }); + }); + + it("accepts direct legacy and namespace-remapped markers only for their live startup identity", () => { + const result = runPythonHarness(`${loadGuardModule} +import json +from types import SimpleNamespace + +class FakeOpen: + def __init__(self, payload): + self.payload = payload + self.snapshot = SimpleNamespace(uid=0, gid=0, mode=0o600, nlink=1) + def read_bytes(self, _max_bytes=None): + return self.payload + def close(self): + pass + +guard._process_start_time = lambda pid: "424242" if pid == 1 else None +guard._pid1_is_nemoclaw_start = lambda: True +payload = b"v1 111111\\n" +guard._open_regular = lambda _path: FakeOpen(payload) +stale = guard._startup_ready_for_current_pid1() +payload = b"v1 424242\\n" +legacy_current = guard._startup_ready_for_current_pid1() +payload = b"v1 424242\\nextra" +malformed = guard._startup_ready_for_current_pid1() +guard._pid1_is_nemoclaw_start = lambda: False +guard._startup_process_identity_is_live = lambda start_time, namespace_inode: ( + start_time == "424242" and namespace_inode == 515151 +) +payload = b"v2 424242 515151\\n" +remapped_current = guard._startup_ready_for_current_pid1() +payload = b"v2 424242 616161\\n" +remapped_stale = guard._startup_ready_for_current_pid1() +print(json.dumps({ + "stale": stale, + "legacy_current": legacy_current, + "malformed": malformed, + "remapped_current": remapped_current, + "remapped_stale": remapped_stale, +})) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + stale: false, + legacy_current: true, + malformed: false, + remapped_current: true, + remapped_stale: false, + }); + }); + + it("publishes a root-only marker containing the current PID 1 start time", () => { + const result = runPythonHarness(`${loadGuardModule} +import json + +captured = {} +guard._process_start_time = lambda pid: "987654" if pid == 1 else None +guard._process_namespace_inode = lambda pid: 424242 if pid == 1 else None +guard._open_regular = lambda _path: (_ for _ in ()).throw(FileNotFoundError()) + +def capture(path, data, **kwargs): + captured.update({ + "path": path, + "data": data.decode("ascii"), + "mode": kwargs["mode"], + "uid": kwargs["uid"], + "gid": kwargs["gid"], + "create": kwargs["expected"] is None, + }) + +guard._atomic_replace = capture +guard.publish_startup_ready() +print(json.dumps(captured)) +`); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + data: "v2 987654 424242\n", + mode: 0o600, + uid: 0, + gid: 0, + create: true, + }); + }); +}); diff --git a/test/hermes-start-config-integrity.test.ts b/test/hermes-start-config-integrity.test.ts index 4cd662f457c..6aa6d6d5c93 100644 --- a/test/hermes-start-config-integrity.test.ts +++ b/test/hermes-start-config-integrity.test.ts @@ -132,6 +132,45 @@ function runHermesDashboardHomePrepAsRoot() { } } +function runLockedParentStartupPreflight(parentMetadata: string) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-parent-preflight-")); + const scriptPath = path.join(tmpDir, "run.sh"); + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const mainStart = src.indexOf('if [ "$(id -u)" -eq 0 ]; then', src.indexOf("# ── Main")); + const rootBranchEnd = src.indexOf("\nelif ", mainStart); + expect(mainStart).toBeGreaterThanOrEqual(0); + expect(rootBranchEnd).toBeGreaterThan(mainStart); + const rootBranch = `${src.slice(mainStart, rootBranchEnd)}\nfi`; + const [parentOwner, parentMode] = parentMetadata.split(" "); + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + 'id() { [ "${1:-}" = "-u" ] && printf "0\\n" || command id "$@"; }', + "recover_startup_hermes_mutation() { return 0; }", + "hermes_restart_seal_orphaned() { return 1; }", + "hermes_config_root_is_locked() { return 0; }", + `stat() { case "\${2:-}" in '%U:%G') printf '%s\\n' ${shellQuote(parentOwner)} ;; '%a') printf '%s\\n' ${shellQuote(parentMode)} ;; *) return 1 ;; esac; }`, + extractShellFunctionFromSource(src, "hermes_locked_parent_is_protected"), + rootBranch, + 'printf "startup-continued\\n"', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + return spawnSync("bash", [scriptPath], { + encoding: "utf-8", + timeout: 5000, + env: process.env, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} + describe("agents/hermes/start.sh config integrity", () => { it("verifies the strict Hermes hash through the sandbox identity in root mode", () => { const result = runHermesConfigIntegrityVerifierAsRoot(); @@ -156,4 +195,16 @@ describe("agents/hermes/start.sh config integrity", () => { expect(result.stdout).toContain("/config.yaml"); expect(result.stdout).toContain("/.env"); }); + + it("continues locked startup only when /sandbox has the sticky root-owned posture", () => { + const protectedParent = runLockedParentStartupPreflight("root:sandbox 1775"); + expect(protectedParent.status, protectedParent.stderr).toBe(0); + expect(protectedParent.stdout).toContain("startup-continued"); + + const unprotectedParent = runLockedParentStartupPreflight("sandbox:sandbox 755"); + expect(unprotectedParent.status).toBe(1); + expect(unprotectedParent.stderr).toContain("HERMES_LOCKED_PARENT_UNPROTECTED"); + expect(unprotectedParent.stderr).toContain("trusted backup and recreate"); + expect(unprotectedParent.stderr).not.toContain("run shields up"); + }); }); diff --git a/test/hermes-start.test.ts b/test/hermes-start.test.ts index 564108e85a8..f9513fe079b 100644 --- a/test/hermes-start.test.ts +++ b/test/hermes-start.test.ts @@ -192,6 +192,7 @@ function runHermesEnvSecretBoundary(opts: { envFile?: string; symlinkEnvFile?: b [ "#!/usr/bin/env bash", "set -euo pipefail", + "_HERMES_BOUNDARY_TIMEOUT=()", extractShellFunctionFromSource(src, "validate_hermes_env_secret_boundary"), `HERMES_DIR=${shellQuote(hermesHome)}`, `_HERMES_BOUNDARY_VALIDATOR=${shellQuote(SECRET_BOUNDARY_VALIDATOR_SCRIPT)}`, @@ -220,6 +221,7 @@ function runHermesRuntimeEnvSecretBoundary(envOverrides: Record<string, string>) [ "#!/usr/bin/env bash", "set -euo pipefail", + "_HERMES_BOUNDARY_TIMEOUT=()", extractShellFunctionFromSource(src, "validate_hermes_runtime_env_secret_boundary"), `_HERMES_BOUNDARY_VALIDATOR=${shellQuote(SECRET_BOUNDARY_VALIDATOR_SCRIPT)}`, "validate_hermes_runtime_env_secret_boundary", @@ -328,6 +330,7 @@ function runTirithExplicitCommandDispatch(mode: "non-root" | "root") { "refresh_hermes_runtime_config_hashes() { :; }", "refresh_hermes_provider_placeholders() { :; }", "configure_messaging_channels() { :; }", + "prepare_hermes_nonroot_runtime() { retry_tirith_marker_if_needed; }", 'cleanup_stale_hermes_gateway_runtime() { echo "unexpected gateway cleanup" >&2; return 99; }', `HERMES_DIR=${shellQuote(hermesHome)}`, `HERMES_HASH_FILE=${shellQuote(path.join(tmpDir, "hermes.config-hash"))}`, @@ -416,6 +419,7 @@ function runHermesSandboxInitPreludeWithFakePath() { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-init-path-")); const fakeBin = path.join(tmpDir, "bin"); const fakeInit = path.join(tmpDir, "sandbox-init.sh"); + const fakeSupervisor = path.join(tmpDir, "gateway-supervisor.sh"); const marker = path.join(tmpDir, "dirname-called"); const sourcePathLog = path.join(tmpDir, "source-path.log"); const scriptPath = path.join(tmpDir, "run.sh"); @@ -433,6 +437,7 @@ function runHermesSandboxInitPreludeWithFakePath() { "harden_resource_limits() { :; }", ].join("\n"), ); + fs.writeFileSync(fakeSupervisor, "# supervisor fixture\n"); const src = fs.readFileSync(START_SCRIPT, "utf-8"); const start = src.indexOf( @@ -441,7 +446,8 @@ function runHermesSandboxInitPreludeWithFakePath() { const end = src.indexOf("\nif [ -d /opt/hermes/hermes_cli/web_dist ];", start); const prelude = src .slice(start, end) - .replaceAll("/usr/local/lib/nemoclaw/sandbox-init.sh", fakeInit); + .replaceAll("/usr/local/lib/nemoclaw/sandbox-init.sh", fakeInit) + .replaceAll("/usr/local/lib/nemoclaw/gateway-supervisor.sh", fakeSupervisor); fs.writeFileSync( scriptPath, @@ -493,6 +499,7 @@ function writeFakeProcCmdline(procRoot: string, pid: number, argv: string[]) { const pidDir = path.join(procRoot, String(pid)); fs.mkdirSync(pidDir, { recursive: true }); fs.writeFileSync(path.join(pidDir, "cmdline"), Buffer.from(`${argv.join("\0")}\0`)); + fs.writeFileSync(path.join(pidDir, "status"), "Name:\tfixture\nUid:\t1000\t1000\t1000\t1000\n"); } function lstatIfPresent(entry: string): fs.Stats | null { diff --git a/test/http-proxy-fix-sync.test.ts b/test/http-proxy-fix-sync.test.ts index 7efd58d7b07..8027926289a 100644 --- a/test/http-proxy-fix-sync.test.ts +++ b/test/http-proxy-fix-sync.test.ts @@ -1,16 +1,26 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { spawnSync } from "node:child_process"; -import { describe, it, expect } from "vitest"; +import { describe, expect, it } from "vitest"; const ROOT = path.join(import.meta.dirname, ".."); const CANONICAL_FIX = path.join(ROOT, "nemoclaw-blueprint", "scripts", "http-proxy-fix.js"); const START_SCRIPT = path.join(ROOT, "scripts", "nemoclaw-start.sh"); +function extractShellFunction(source: string, name: string): string { + const header = `${name}() {`; + const start = source.indexOf(header); + expect(start, `expected ${name} in nemoclaw-start.sh`).not.toBe(-1); + const body = source.slice(start + header.length); + const closing = body.match(/^}$/m); + expect(closing, `expected closing brace for ${name}`).not.toBeNull(); + return `${name}() {${body.slice(0, closing?.index ?? 0)}\n}`; +} + describe("http-proxy-fix preload sync (#2109)", () => { it("entrypoint emits the proxy fix preload and registers it in NODE_OPTIONS", () => { const startScript = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -41,7 +51,21 @@ describe("http-proxy-fix preload sync (#2109)", () => { 'emit_sandbox_sourced_file() { local target="$1"; cat > "$target"; chmod 444 "$target"; }', "NODE_USE_ENV_PROXY=1", "NODE_OPTIONS='--require /already-loaded.js'", + extractShellFunction(startScript, "node_options_has_require"), + extractShellFunction(startScript, "append_node_require_once"), block, + `_SANDBOX_SAFETY_NET=${JSON.stringify(path.join(tempDir, "safety-net.js"))}`, + `_SANDBOX_SAFETY_NET_SOURCE=${JSON.stringify(CANONICAL_FIX)}`, + `_NEMOTRON_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "nemotron-fix.js"))}`, + `_NEMOTRON_FIX_SOURCE=${JSON.stringify(CANONICAL_FIX)}`, + `_CIAO_GUARD_SCRIPT=${JSON.stringify(path.join(tempDir, "ciao-guard.js"))}`, + `_CIAO_GUARD_SOURCE=${JSON.stringify(CANONICAL_FIX)}`, + `_WS_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "ws-fix.js"))}`, + `_WS_FIX_SOURCE=${JSON.stringify(path.join(tempDir, "missing-ws-source.js"))}`, + `_SECCOMP_GUARD_SCRIPT=${JSON.stringify(path.join(tempDir, "seccomp-guard.js"))}`, + `_SECCOMP_GUARD_SOURCE=${JSON.stringify(CANONICAL_FIX)}`, + extractShellFunction(startScript, "install_core_runtime_preloads"), + "install_core_runtime_preloads", "printf 'NODE_OPTIONS=%s\\n' \"$NODE_OPTIONS\"", "printf 'SCRIPT=%s\\n' \"$_PROXY_FIX_SCRIPT\"", ].join("\n"); diff --git a/test/managed-gateway-control-trust-contract.test.ts b/test/managed-gateway-control-trust-contract.test.ts new file mode 100644 index 00000000000..cbdc1536fc2 --- /dev/null +++ b/test/managed-gateway-control-trust-contract.test.ts @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const REPO_ROOT = path.resolve(import.meta.dirname, ".."); +const HELPER = path.join(REPO_ROOT, "scripts", "managed-gateway-control.py"); +const RUNTIME_DOCS = path.join(REPO_ROOT, "docs", "manage-sandboxes", "runtime-controls.mdx"); + +describe("managed gateway control trust contract", () => { + it("keeps the shared-UID and mutable-config limits explicit in code and docs", () => { + const helper = fs.readFileSync(HELPER, "utf8"); + const docs = fs.readFileSync(RUNTIME_DOCS, "utf8"); + + expect(helper).toContain("malicious same-UID agent"); + expect(helper).toContain("mutable config retains the same trust/TOCTOU limitations"); + expect(helper).toContain("cannot manufacture gateway/agent UID isolation"); + expect(helper).toContain( + "minimum supported OpenShell launches a root-owned lifecycle supervisor", + ); + + expect(docs).toContain("malicious process running under the same sandbox UID"); + expect(docs).toContain("time-of-check/time-of-use limits of managed cold start"); + expect(docs).toContain("does not create gateway and agent UID isolation"); + expect(docs).toContain( + "minimum supported OpenShell provides a root-owned lifecycle supervisor", + ); + }); +}); diff --git a/test/managed-gateway-control.test.ts b/test/managed-gateway-control.test.ts new file mode 100644 index 00000000000..dc690c6e265 --- /dev/null +++ b/test/managed-gateway-control.test.ts @@ -0,0 +1,724 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const HELPER = path.join(import.meta.dirname, "..", "scripts", "managed-gateway-control.py"); +const BOUNDARY_VALIDATOR = path.join( + import.meta.dirname, + "..", + "agents", + "hermes", + "validate-env-secret-boundary.py", +); +const NONCE = "a".repeat(64); + +const PROCESS_HARNESS = String.raw` +import importlib.util +import json +import os +import shutil +import sys +import tempfile +from dataclasses import replace + +spec = importlib.util.spec_from_file_location("managed_control", sys.argv[1]) +control = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = control +spec.loader.exec_module(control) + +def write_process( + proc_root, + namespace_path, + pid, + start_time, + parent_pid, + uid, + cmdline, + environ=b"PATH=/usr/bin\0", + listener_inode=None, +): + process_root = os.path.join(proc_root, str(pid)) + os.makedirs(os.path.join(process_root, "ns")) + os.makedirs(os.path.join(process_root, "fd")) + os.symlink("../net", os.path.join(process_root, "net")) + fields = ["S", str(parent_pid)] + (["0"] * 17) + [str(start_time)] + with open(os.path.join(process_root, "stat"), "w", encoding="ascii") as stream: + stream.write(f"{pid} (managed) {' '.join(fields)}\n") + with open(os.path.join(process_root, "status"), "w", encoding="ascii") as stream: + stream.write( + f"Uid:\t{uid}\t{uid}\t{uid}\t{uid}\n" + f"NSpid:\t{pid}\n" + ) + with open(os.path.join(process_root, "cmdline"), "wb") as stream: + stream.write(cmdline) + with open(os.path.join(process_root, "environ"), "wb") as stream: + stream.write(environ) + os.link(namespace_path, os.path.join(process_root, "ns", "pid")) + if listener_inode is not None: + os.symlink(f"socket:[{listener_inode}]", os.path.join(process_root, "fd", "7")) + +def remove_process(proc_root, pid): + shutil.rmtree(os.path.join(proc_root, str(pid))) + +with tempfile.TemporaryDirectory() as root: + proc_root = os.path.join(root, "proc") + system_root = os.path.join(root, "system") + os.makedirs(os.path.join(proc_root, "net")) + os.makedirs(os.path.join(system_root, "run")) + os.makedirs(os.path.join(system_root, "usr/local/lib/nemoclaw")) + os.makedirs(os.path.join(system_root, "sandbox/.hermes")) + os.makedirs(os.path.join(system_root, "etc/nemoclaw")) + namespace_path = os.path.join(root, "pid-namespace") + with open(namespace_path, "wb") as stream: + stream.write(b"namespace") + for table in ("tcp", "tcp6"): + with open(os.path.join(proc_root, "net", table), "w", encoding="ascii") as stream: + stream.write("sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n") + with open(os.path.join(proc_root, "net", "tcp"), "a", encoding="ascii") as stream: + stream.write("0: 0100007F:48D2 00000000:0000 0A 0:0 00:0 0 1000 0 77777\n") + + write_process( + proc_root, + namespace_path, + 1, + 111, + 0, + 0, + b"/opt/openshell/bin/openshell-sandbox\0--managed\0", + ) + write_process( + proc_root, + namespace_path, + 40, + 222, + 1, + 1000, + b"bash\0/usr/local/bin/nemoclaw-start\0", + b"PATH=/usr/bin\0NEMOCLAW_DASHBOARD_PORT=18789\0", + ) + write_process( + proc_root, + namespace_path, + 41, + 333, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + controller_pid = os.getpid() + controller_start_time = "777" + write_process( + proc_root, + namespace_path, + controller_pid, + controller_start_time, + 1, + os.geteuid(), + b"python3\0-I\0/usr/local/lib/nemoclaw/managed-gateway-control.py\0restart\0" + + (b"a" * 64) + + b"\0", + ) + + control._sandbox_uid = lambda: 1000 + control._http_healthy_in_gateway_namespace = ( + lambda _reader, _identity, port, path: (port, path) in { + (18642, "/health"), + (8642, "/health"), + } + ) + os.environ["NEMOCLAW_MANAGED_CONTROL_ALLOW_NONROOT_TEST"] = "1" + os.environ["NEMOCLAW_MANAGED_CONTROL_SYSTEM_ROOT"] = system_root + boundary_path = os.path.join( + system_root, + "usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py", + ) + with open(boundary_path, "w", encoding="utf-8") as stream: + stream.write("# trusted validator fixture\n") + os.chmod(boundary_path, 0o755) + + with control.ProcReader(proc_root) as reader: + supervisor = control._discover_supervisor(reader) + hermes = control._agent_spec("hermes", reader, supervisor) + candidates = control._gateway_candidates(reader, supervisor, hermes) + initial_proof = { + "supervisor": [supervisor.pid, supervisor.start_time, supervisor.parent_pid], + "gateway": [candidates[0].pid, candidates[0].start_time, candidates[0].parent_pid], + "healthy": control._gateway_healthy(reader, candidates[0], hermes), + } + state_key_behavior = [ + replace(candidates[0], state="R").stable_key() + == candidates[0].stable_key(), + replace(candidates[0], state="Z").stable_key() + == candidates[0].stable_key(), + ] + mixed_namespace_rejected = not control._gateway_matches( + candidates[0], replace(supervisor, namespace_inode=None), hermes + ) + + real_namespace_inode = control._namespace_inode + control._namespace_inode = lambda _pid_fd: None + try: + namespace_denied_supervisor = control._discover_supervisor(reader) + namespace_denied = len( + control._gateway_candidates(reader, namespace_denied_supervisor, hermes) + ) == 1 + finally: + control._namespace_inode = real_namespace_inode + + preflight_steps = [] + real_validator = control._run_fixed_validator + real_runtime_validator = control._validate_runtime_environment + real_hash_check = control._verify_locked_hermes_hash + control._run_fixed_validator = lambda script, arguments: preflight_steps.append({ + "script": script, + "arguments": arguments, + }) + control._validate_runtime_environment = lambda script, environment: preflight_steps.append({ + "script": script, + "arguments": ["runtime-env"], + "runtime_port": environment.get("NEMOCLAW_DASHBOARD_PORT"), + }) + control._verify_locked_hermes_hash = lambda: preflight_steps.append({"hash": "checked"}) + try: + control._hermes_preflight(reader, supervisor) + finally: + control._run_fixed_validator = real_validator + control._validate_runtime_environment = real_runtime_validator + control._verify_locked_hermes_hash = real_hash_check + + real_subprocess_run = control.subprocess.run + control.subprocess.run = lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError("runtime boundary must not exec with untrusted env") + ) + try: + control._validate_runtime_environment( + sys.argv[2], + {"LD_PRELOAD": "/tmp/attacker.so", "SAFE": "1"}, + ) + runtime_validation = "in-process" + finally: + control.subprocess.run = real_subprocess_run + + write_process( + proc_root, + namespace_path, + 42, + 444, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + try: + control._gateway_candidates(reader, supervisor, hermes) + duplicate = "accepted" + except control.ControlError as error: + duplicate = error.code + remove_process(proc_root, 42) + + expected_gateway = candidates[0] + sent = [] + real_pidfd_open = control._pidfd_open + real_pidfd_exited = control._pidfd_exited + real_send = control._send_pidfd + read_fd, write_fd = os.pipe() + try: + control._pidfd_open = lambda _pid: os.dup(read_fd) + exit_checks = iter((False, True)) + control._pidfd_exited = lambda _pidfd, _timeout: next(exit_checks) + control._send_pidfd = lambda _pidfd, signum: sent.append(int(signum)) + control._terminate_gateway(reader, expected_gateway) + + with open(os.path.join(proc_root, "41", "stat"), "w", encoding="ascii") as stream: + fields = ["S", "40"] + (["0"] * 17) + ["999"] + stream.write(f"41 (managed) {' '.join(fields)}\n") + try: + control._terminate_gateway(reader, expected_gateway) + reused = "signalled" + except control.ControlError as error: + reused = error.code + finally: + control._pidfd_open = real_pidfd_open + control._pidfd_exited = real_pidfd_exited + control._send_pidfd = real_send + os.close(read_fd) + os.close(write_fd) + + # Restore the original gateway fixture, then make the fake TERM atomically + # expose the replacement that the real shell supervisor would launch. + remove_process(proc_root, 41) + write_process( + proc_root, + namespace_path, + 41, + 333, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + with open( + os.path.join(system_root, "usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"), + "w", + encoding="utf-8", + ) as stream: + stream.write("# trusted fixture\n") + os.chmod( + os.path.join(system_root, "usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"), + 0o755, + ) + real_proc_root = control._proc_root + control._proc_root = lambda: proc_root + control._preflight = lambda *_args: None + control._http_healthy_in_gateway_namespace = lambda *_args: True + real_terminate = control._terminate_gateway + with control.ProcReader(proc_root) as controller_reader: + controller_identity = control._controller_process_identity(controller_reader) + lease_path = os.path.join( + system_root, + "run/nemoclaw", + control.EXPECTED_EXIT_MARKER_NAME, + ) + lock_path = os.path.join( + system_root, + "run/nemoclaw", + control.EXPECTED_EXIT_LOCK_NAME, + ) + lease_observations = [] + def observe_expected_exit_lease(identity, label): + metadata = os.stat(lease_path, follow_symlinks=False) + lock_metadata = os.stat(lock_path, follow_symlinks=False) + with open(lease_path, "r", encoding="ascii") as stream: + version, pid, start_time, controller, controller_start = stream.read().split() + lease_observations.append({ + "label": label, + "identity": [ + version, + int(pid), + start_time, + int(controller), + controller_start, + ], + "secure": ( + metadata.st_uid == os.geteuid() + and metadata.st_gid == os.getegid() + and (metadata.st_mode & 0o777) == 0o444 + and metadata.st_nlink == 1 + and lock_metadata.st_uid == os.geteuid() + and lock_metadata.st_gid == os.getegid() + and (lock_metadata.st_mode & 0o777) == 0o600 + and lock_metadata.st_nlink == 1 + ), + }) + def replace_gateway(_reader, identity): + assert identity.pid == 41 + observe_expected_exit_lease(identity, "restart") + remove_process(proc_root, 41) + write_process( + proc_root, + namespace_path, + 43, + 555, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + + active_lease = control._publish_expected_exit_lease( + expected_gateway, + controller_identity, + ) + try: + control._publish_expected_exit_lease(expected_gateway, controller_identity) + active_controller_lock = "replaced" + except control.ControlError as error: + active_controller_lock = error.code + control._clear_expected_exit_lease(active_lease) + + orphaned_lease = control._publish_expected_exit_lease( + expected_gateway, + controller_identity, + ) + orphaned_inode = os.stat(lease_path, follow_symlinks=False).st_ino + os.close(orphaned_lease.marker_fd) + os.close(orphaned_lease.lock_fd) + os.close(orphaned_lease.directory_fd) + untrusted_marker_fd = os.open(lease_path, os.O_RDONLY) + control.fcntl.flock(untrusted_marker_fd, control.fcntl.LOCK_SH) + recovered_lease = control._publish_expected_exit_lease( + expected_gateway, + controller_identity, + ) + marker_flock_cannot_pin = ( + os.stat(lease_path, follow_symlinks=False).st_ino != orphaned_inode + ) + control.fcntl.flock(untrusted_marker_fd, control.fcntl.LOCK_UN) + os.close(untrusted_marker_fd) + control._clear_expected_exit_lease(recovered_lease) + + original_lease = control._publish_expected_exit_lease( + expected_gateway, + controller_identity, + ) + os.unlink(lease_path) + with open(lease_path, "w", encoding="ascii") as stream: + stream.write(f"v1 41 333 {controller_pid} {controller_start_time}\n") + os.chmod(lease_path, 0o444) + replacement_inode = os.stat(lease_path, follow_symlinks=False).st_ino + control._clear_expected_exit_lease(original_lease) + inode_safe_cleanup = ( + os.path.exists(lease_path) + and os.stat(lease_path, follow_symlinks=False).st_ino == replacement_inode + ) + os.unlink(lease_path) + + os.unlink(lock_path) + original_umask = os.umask(0o777) + try: + restrictive_umask_lease = control._publish_expected_exit_lease( + expected_gateway, + controller_identity, + ) + finally: + os.umask(original_umask) + restrictive_umask_modes = [ + os.stat(lease_path, follow_symlinks=False).st_mode & 0o777, + os.stat(lock_path, follow_symlinks=False).st_mode & 0o777, + ] + control._clear_expected_exit_lease(restrictive_umask_lease) + + control._terminate_gateway = replace_gateway + try: + restarted = control._control("restart", "a" * 64) + restart_lease_cleared = not os.path.exists(lease_path) + recovered = control._control("recover", "b" * 64) + probed = control._control("probe", "e" * 64) + + real_detect_agent = control._detect_agent + real_agent_spec = control._agent_spec + real_gateway_candidates = control._gateway_candidates + real_wait_for_healthy = control._wait_for_healthy_gateway + real_publish_lease = control._publish_expected_exit_lease + control._detect_agent = lambda: "openclaw" + control._agent_spec = lambda *_args: control.AgentSpec("openclaw", 18642) + control._gateway_candidates = lambda reader, *_args: [reader.capture(43)] + control._wait_for_healthy_gateway = lambda reader, *_args: reader.capture(43) + control._terminate_gateway = lambda *_args: None + control._publish_expected_exit_lease = lambda *_args: (_ for _ in ()).throw( + AssertionError("OpenClaw must not publish a Hermes crash-budget lease") + ) + try: + openclaw_restart = control._control("restart", "f" * 64) + finally: + control._detect_agent = real_detect_agent + control._agent_spec = real_agent_spec + control._gateway_candidates = real_gateway_candidates + control._wait_for_healthy_gateway = real_wait_for_healthy + control._publish_expected_exit_lease = real_publish_lease + control._terminate_gateway = replace_gateway + + real_wait_for_healthy = control._wait_for_healthy_gateway + timeout_refresh_waits = [] + timeout_refresh_signals = [] + def timeout_refresh_wait( + reader, + _supervisor, + _spec, + old_identity, + timeout_seconds=control.RECOVERY_TIMEOUT_SECONDS, + require_auxiliary_health=False, + ): + timeout_refresh_waits.append([ + old_identity.pid if old_identity else 0, + timeout_seconds, + require_auxiliary_health, + ]) + if len(timeout_refresh_waits) == 1: + remove_process(proc_root, 43) + write_process( + proc_root, + namespace_path, + 44, + 666, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + raise control.ControlError("GATEWAY_HEALTH_TIMEOUT") + if len(timeout_refresh_waits) == 2: + raise control.ControlError("GATEWAY_HEALTH_TIMEOUT") + return reader.capture(45) + def terminate_refreshed_gateway(_reader, identity): + timeout_refresh_signals.append(identity.pid) + assert identity.pid == 44 + observe_expected_exit_lease(identity, "unhealthy-recover") + remove_process(proc_root, 44) + write_process( + proc_root, + namespace_path, + 45, + 777, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + control._wait_for_healthy_gateway = timeout_refresh_wait + control._terminate_gateway = terminate_refreshed_gateway + try: + timeout_refresh = control._control("recover", "d" * 64) + timeout_lease_cleared = not os.path.exists(lease_path) + finally: + control._wait_for_healthy_gateway = real_wait_for_healthy + control._terminate_gateway = replace_gateway + remove_process(proc_root, 45) + write_process( + proc_root, + namespace_path, + 43, + 555, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + + real_gateway_healthy = control._gateway_healthy + inflight_health_attempts = [] + def inflight_health(*_args): + inflight_health_attempts.append("attempt") + return len(inflight_health_attempts) >= 2 + control._gateway_healthy = inflight_health + control._terminate_gateway = lambda *_args: (_ for _ in ()).throw( + AssertionError("recover must not terminate an in-flight healthy replacement") + ) + try: + inflight_recovery = control._control("recover", "c" * 64) + finally: + control._gateway_healthy = real_gateway_healthy + control._terminate_gateway = replace_gateway + real_gateway_healthy = control._gateway_healthy + health_attempts = [] + def transient_health(*_args): + health_attempts.append("attempt") + if len(health_attempts) == 1: + raise FileNotFoundError("replacement exited") + return True + control._gateway_healthy = transient_health + try: + with control.ProcReader(proc_root) as retry_reader: + retry_supervisor = control._discover_supervisor(retry_reader) + retried_pid = control._wait_for_healthy_gateway( + retry_reader, retry_supervisor, control.AgentSpec("hermes", 18642), None + ).pid + finally: + control._gateway_healthy = real_gateway_healthy + + real_http_health = control._http_healthy_in_gateway_namespace + public_health_attempts = [] + def delayed_public_health(_reader, _identity, port, path): + if (port, path) == (8642, "/health"): + public_health_attempts.append("attempt") + return len(public_health_attempts) >= 2 + return (port, path) == (18642, "/health") + control._http_healthy_in_gateway_namespace = delayed_public_health + try: + with control.ProcReader(proc_root) as readiness_reader: + readiness_supervisor = control._discover_supervisor(readiness_reader) + readiness_pid = control._wait_for_healthy_gateway( + readiness_reader, + readiness_supervisor, + control.AgentSpec( + "hermes", 18642, readiness_checks=((8642, "/health"),) + ), + None, + 1.0, + True, + ).pid + finally: + control._http_healthy_in_gateway_namespace = real_http_health + + auxiliary_attempts = [] + real_auxiliary_health = control._gateway_auxiliaries_healthy + def replace_during_auxiliary_check(_reader, identity, _spec): + auxiliary_attempts.append(identity.pid) + if identity.pid == 43: + remove_process(proc_root, 43) + write_process( + proc_root, + namespace_path, + 44, + 666, + 40, + 1000, + b"/usr/local/bin/hermes.real\0gateway\0run\0", + listener_inode="77777", + ) + return False + return True + control._gateway_auxiliaries_healthy = replace_during_auxiliary_check + try: + with control.ProcReader(proc_root) as auxiliary_reader: + auxiliary_supervisor = control._discover_supervisor(auxiliary_reader) + auxiliary_replacement = control._wait_for_healthy_gateway( + auxiliary_reader, + auxiliary_supervisor, + control.AgentSpec("hermes", 18642), + None, + 1.0, + True, + ).pid + finally: + control._gateway_auxiliaries_healthy = real_auxiliary_health + finally: + control._terminate_gateway = real_terminate + control._proc_root = real_proc_root + + os.environ["NEMOCLAW_MANAGED_CONTROL_PROC_ROOT"] = "/attacker/proc" + os.environ["NEMOCLAW_MANAGED_CONTROL_SYSTEM_ROOT"] = "/attacker/root" + source_proc = control._proc_root() + source_system = control._system_root() + del os.environ["NEMOCLAW_MANAGED_CONTROL_ALLOW_NONROOT_TEST"] + disabled_source_proc = control._proc_root() + disabled_source_system = control._system_root() + control.__file__ = control.INSTALLED_HELPER_PATH + installed_proc = control._proc_root() + installed_system = control._system_root() + + print(json.dumps({ + "initial": initial_proof, + "state_key_behavior": state_key_behavior, + "mixed_namespace_rejected": mixed_namespace_rejected, + "namespace_denied": namespace_denied, + "preflight": preflight_steps, + "runtime_validation": runtime_validation, + "duplicate": duplicate, + "signals": sent, + "reused": reused, + "restarted": restarted, + "recovered": recovered, + "probed": probed, + "openclaw_restart": openclaw_restart, + "lease_races": [ + active_controller_lock, + marker_flock_cannot_pin, + inode_safe_cleanup, + restrictive_umask_modes, + ], + "expected_exit_leases": [ + lease_observations, + restart_lease_cleared, + timeout_lease_cleared, + ], + "timeout_refresh": [ + timeout_refresh, + timeout_refresh_signals, + timeout_refresh_waits, + ], + "inflight_recovery": [inflight_recovery, len(inflight_health_attempts)], + "transient_retry": [retried_pid, len(health_attempts)], + "public_readiness_retry": [readiness_pid, len(public_health_attempts)], + "auxiliary_replacement": [auxiliary_replacement, auxiliary_attempts], + "source_seams": [source_proc, source_system], + "disabled_source_seams": [disabled_source_proc, disabled_source_system], + "installed_seams": [installed_proc, installed_system], + })) +`; + +describe("managed gateway root control", () => { + it("pins the OpenShell process tree, rejects ambiguity/reuse, and proves restart/recover", () => { + const result = spawnSync("python3", ["-c", PROCESS_HARNESS, HELPER, BOUNDARY_VALIDATOR], { + encoding: "utf-8", + timeout: 10_000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + initial: { + supervisor: [40, "222", 1], + gateway: [41, "333", 40], + healthy: true, + }, + state_key_behavior: [true, false], + mixed_namespace_rejected: true, + namespace_denied: true, + preflight: [ + { + script: expect.stringContaining( + "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py", + ), + arguments: ["env-file", expect.stringContaining("/sandbox/.hermes/.env")], + }, + { + script: expect.stringContaining( + "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py", + ), + arguments: ["runtime-env"], + runtime_port: "18789", + }, + { hash: "checked" }, + ], + runtime_validation: "in-process", + duplicate: "SUPERVISOR_UNAVAILABLE", + signals: [15, 9], + reused: "SUPERVISOR_UNAVAILABLE", + restarted: ["ok", 41, 43], + recovered: ["already-running", 43, 43], + probed: ["already-running", 43, 43], + openclaw_restart: ["ok", 43, 43], + lease_races: ["SUPERVISOR_BUSY", true, true, [0o444, 0o600]], + expected_exit_leases: [ + [ + { + label: "restart", + identity: ["v1", 41, "333", expect.any(Number), "777"], + secure: true, + }, + { + label: "unhealthy-recover", + identity: ["v1", 44, "666", expect.any(Number), "777"], + secure: true, + }, + ], + true, + true, + ], + timeout_refresh: [ + ["ok", 44, 45], + [44], + [ + [0, 10, false], + [0, 10, false], + [44, 150, true], + ], + ], + inflight_recovery: [["already-running", 43, 43], 4], + transient_retry: [43, 2], + public_readiness_retry: [43, 2], + auxiliary_replacement: [44, [43, 44]], + source_seams: ["/attacker/proc", "/attacker/root"], + disabled_source_seams: ["/proc", "/"], + installed_seams: ["/proc", "/"], + }); + }); + + it.each([ + ["replace", NONCE, "SUPERVISOR_INVALID_ACTION"], + ["restart", "abcd", "SUPERVISOR_INVALID_NONCE"], + ])("returns the existing marker for an invalid %s request", (action, nonce, marker) => { + const result = spawnSync("python3", [HELPER, action, nonce], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr.trim()).toBe(marker); + }); +}); diff --git a/test/nemoclaw-start-gateway-health.test.ts b/test/nemoclaw-start-gateway-health.test.ts index 6da39fc95a3..d73befcf04d 100644 --- a/test/nemoclaw-start-gateway-health.test.ts +++ b/test/nemoclaw-start-gateway-health.test.ts @@ -17,6 +17,13 @@ import * as path from "node:path"; import { describe, expect, it } from "vitest"; const START_SCRIPT = path.join(import.meta.dirname, "..", "scripts", "nemoclaw-start.sh"); +const GATEWAY_SUPERVISOR = path.join( + import.meta.dirname, + "..", + "scripts", + "lib", + "gateway-supervisor.sh", +); // Read a file that may legitimately be absent without a check-then-read // race (CodeQL js/file-system-race): attempt the read and treat a missing @@ -48,10 +55,34 @@ function safeTmpHelpers(src: string): string { return src.slice(start, end); } +function pidIdentityFunctions(src: string): string { + const supervisor = fs.readFileSync(GATEWAY_SUPERVISOR, "utf-8"); + return [ + extractShellFunction(src, "openclaw_load_pid_identity"), + extractShellFunction(src, "openclaw_pid_start_identity"), + extractShellFunction(src, "capture_openclaw_pid_start_identity"), + extractShellFunction(src, "openclaw_supervised_pid_is_live"), + extractShellFunction(supervisor, "gateway_control_proc_root"), + extractShellFunction(supervisor, "gateway_control_proc_root_is_explicit"), + extractShellFunction(supervisor, "gateway_control_pid_state"), + extractShellFunction(supervisor, "gateway_control_pid_is_live"), + ].join("\n"); +} + +const writeProcStatFunction = [ + "write_proc_stat() {", + ' local pid="$1" parent="$2" start="$3"', + ' printf \'%s (test-process) S %s\' "$pid" "$parent"', + " for _ in {1..17}; do printf ' 0'; done", + " printf ' %s\\n' \"$start\"", + "}", +].join("\n"); + function watchdogFunctions(): string { const src = fs.readFileSync(START_SCRIPT, "utf-8"); return [ safeTmpHelpers(src), + pidIdentityFunctions(src), extractShellFunction(src, "record_gateway_pid"), extractShellFunction(src, "gateway_pid_is_openclaw_gateway"), extractShellFunction(src, "gateway_watchdog_positive_int_ok"), @@ -59,6 +90,19 @@ function watchdogFunctions(): string { ].join("\n"); } +function rootGatewayLifecycleFunctions(src: string, gatewayLog: string): string { + return [ + pidIdentityFunctions(src), + extractShellFunction(src, "launch_openclaw_gateway").replaceAll("/tmp/gateway.log", gatewayLog), + extractShellFunction(src, "openclaw_supervised_aux_pid_is_live"), + extractShellFunction(src, "stop_openclaw_supervised_gateway"), + extractShellFunction(src, "refresh_openclaw_supervised_child_pids"), + extractShellFunction(src, "mark_openclaw_gateway_stopped"), + extractShellFunction(src, "stop_openclaw_gateway_fail_closed"), + extractShellFunction(src, "openclaw_reap_exited_gateway"), + ].join("\n"); +} + // Drive the watchdog end-to-end against a real background process standing in // for the gateway. `curlPlan` is the sequence of curl exit codes the stubbed // probe returns, one per watchdog cycle; the last entry repeats forever. @@ -92,6 +136,7 @@ function runWatchdog(opts: { "_DASHBOARD_PORT=18789", `_NEMOCLAW_PROC_ROOT=${JSON.stringify(procRoot)}`, `_NEMOCLAW_GATEWAY_LOG=${JSON.stringify(wedgeLogFile)}`, + writeProcStatFunction, // Throttle rather than no-op so the spinning loop stays cheap but the // test still completes in well under a second per cycle. "sleep() { command sleep 0.01; }", @@ -109,10 +154,15 @@ function runWatchdog(opts: { // exercised for real; its claimed cmdline comes from the proc fixture. "command sleep 60 &", "FAKE_GATEWAY_PID=$!", + "FAKE_GATEWAY_START=1001", `mkdir -p ${JSON.stringify(procRoot)}/$FAKE_GATEWAY_PID`, `printf '%s' ${JSON.stringify(opts.cmdline ?? "openclaw-gateway")} >${JSON.stringify(procRoot)}/$FAKE_GATEWAY_PID/cmdline`, + `write_proc_stat "$FAKE_GATEWAY_PID" "$$" "$FAKE_GATEWAY_START" >${JSON.stringify(procRoot)}/$FAKE_GATEWAY_PID/stat`, watchdogFunctions(), - 'record_gateway_pid "$FAKE_GATEWAY_PID"', + // The watchdog itself is outside the fake proc fixture. Its launch + // identity is irrelevant to these gateway-target tests. + 'capture_openclaw_pid_start_identity() { printf -v "$2" "%s" "watchdog-test"; }', + 'record_gateway_pid "$FAKE_GATEWAY_PID" "$FAKE_GATEWAY_START"', "start_gateway_serving_watchdog", 'printf "WATCHDOG_PID=%s\\n" "$GATEWAY_WATCHDOG_PID"', ...(opts.expectKill @@ -301,6 +351,7 @@ describe("gateway serving watchdog (#4710)", () => { "_DASHBOARD_PORT=18789", `_NEMOCLAW_PROC_ROOT=${JSON.stringify(procRoot)}`, `_NEMOCLAW_GATEWAY_LOG=${JSON.stringify(path.join(tmpDir, "gateway.log"))}`, + writeProcStatFunction, // A low threshold makes an inherited armed state lethal within a few // cycles, so survival proves the per-PID reset. "export NEMOCLAW_GATEWAY_WATCHDOG_REFUSED_THRESHOLD=2", @@ -314,7 +365,7 @@ describe("gateway serving watchdog (#4710)", () => { ' if [ -n "$rest" ]; then printf "%s\\n" "$rest" >"$_CURL_PLAN"; fi', ` printf 'probe\\n' >> ${JSON.stringify(probeLog)}`, ' case "$next" in', - ' 0) record_gateway_pid "$GATEWAY_B" ;;', + ' 0) record_gateway_pid "$GATEWAY_B" "$GATEWAY_B_START" ;;', " esac", ' return "$next"', "}", @@ -322,11 +373,16 @@ describe("gateway serving watchdog (#4710)", () => { "GATEWAY_A=$!", "command sleep 60 &", "GATEWAY_B=$!", + "GATEWAY_A_START=2001", + "GATEWAY_B_START=2002", `mkdir -p ${JSON.stringify(procRoot)}/$GATEWAY_A ${JSON.stringify(procRoot)}/$GATEWAY_B`, `printf 'openclaw-gateway' >${JSON.stringify(procRoot)}/$GATEWAY_A/cmdline`, `printf 'openclaw-gateway' >${JSON.stringify(procRoot)}/$GATEWAY_B/cmdline`, + `write_proc_stat "$GATEWAY_A" "$$" "$GATEWAY_A_START" >${JSON.stringify(procRoot)}/$GATEWAY_A/stat`, + `write_proc_stat "$GATEWAY_B" "$$" "$GATEWAY_B_START" >${JSON.stringify(procRoot)}/$GATEWAY_B/stat`, watchdogFunctions(), - 'record_gateway_pid "$GATEWAY_A"', + 'capture_openclaw_pid_start_identity() { printf -v "$2" "%s" "watchdog-test"; }', + 'record_gateway_pid "$GATEWAY_A" "$GATEWAY_A_START"', "start_gateway_serving_watchdog", // The curl stub swaps to gateway B during A's successful probe, // before the watchdog can start counting refused probes again. @@ -357,6 +413,281 @@ describe("gateway serving watchdog (#4710)", () => { fs.rmSync(tmpDir, { recursive: true, force: true }); } }); + + it("tracks the replacement before a termination signal interrupts restart health wait", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-restart-signal-race-")); + const eventLog = path.join(tmpDir, "events.log"); + const scriptPath = path.join(tmpDir, "run.sh"); + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `EVENT_LOG=${JSON.stringify(eventLog)}`, + "GATEWAY_PID=101", + "GATEWAY_PID_START_IDENTITY=old-start", + "SANDBOX_WAIT_PID=101", + "SANDBOX_CHILD_PIDS=(101)", + "GATEWAY_CONTROL_ACTION=restart", + "GATEWAY_CONTROL_SIGNAL_PENDING=0", + "gateway_control_take_request() { :; }", + 'openclaw_supervised_pid_is_live() { case "$1:$2" in "101:old-start"|"202:new-start") return 0 ;; *) return 1 ;; esac; }', + "gateway_control_stop_tracked_pid() {", + ' printf "stop:%s:%s\\n" "$1" "$2" >>"$EVENT_LOG"', + " return 0", + "}", + "prepare_openclaw_gateway_restart() { :; }", + "run_openclaw_config_guard() { :; }", + "restore_openclaw_restart_config() { :; }", + "cleanup_openclaw_gateway_locks() { :; }", + "launch_openclaw_gateway() {", + " GATEWAY_PID=202", + " GATEWAY_PID_START_IDENTITY=new-start", + " SANDBOX_WAIT_PID=202", + "}", + "wait_for_openclaw_gateway_internal() {", + ' kill -TERM "$$"', + " return 1", + "}", + "start_plugin_registry_refresh() { :; }", + "gateway_control_complete() { :; }", + "gateway_control_fail() { :; }", + "cleanup_on_signal() {", + ' printf "cleanup:wait=%s:children=%s\\n" "$SANDBOX_WAIT_PID" "${SANDBOX_CHILD_PIDS[*]}" >>"$EVENT_LOG"', + ' [ "$SANDBOX_WAIT_PID" -eq 202 ]', + ' [ "${SANDBOX_CHILD_PIDS[*]}" = "202" ]', + " exit 0", + "}", + "trap cleanup_on_signal SIGTERM SIGINT", + extractShellFunction(src, "openclaw_supervised_aux_pid_is_live"), + extractShellFunction(src, "stop_openclaw_supervised_gateway"), + extractShellFunction(src, "refresh_openclaw_supervised_child_pids"), + extractShellFunction(src, "mark_openclaw_gateway_stopped"), + extractShellFunction(src, "stop_openclaw_gateway_fail_closed"), + extractShellFunction(src, "retire_openclaw_supervised_gateway"), + extractShellFunction(src, "handle_openclaw_gateway_control_request"), + "handle_openclaw_gateway_control_request", + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, `script failed: ${result.stderr}`).toBe(0); + expect(fs.readFileSync(eventLog, "utf-8")).toBe( + "stop:101:old-start\ncleanup:wait=202:children=202\n", + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); + +describe("OpenClaw supervised child PID identity", () => { + it("does not re-admit a recycled plugin-refresh PID owned by another process", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-aux-pid-identity-")); + const procRoot = path.join(tmpDir, "proc"); + const scriptPath = path.join(tmpDir, "run.sh"); + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `_NEMOCLAW_PROC_ROOT=${JSON.stringify(procRoot)}`, + writeProcStatFunction, + 'mkdir -p "$_NEMOCLAW_PROC_ROOT/303" "$_NEMOCLAW_PROC_ROOT/404"', + 'write_proc_stat 303 "$$" 3003 >"$_NEMOCLAW_PROC_ROOT/303/stat"', + 'write_proc_stat 404 "$$" 4999 >"$_NEMOCLAW_PROC_ROOT/404/stat"', + pidIdentityFunctions(src), + 'gateway_control_pid_is_live() { case "$1" in 303|404) return 0 ;; *) return 1 ;; esac; }', + "GATEWAY_PID=", + "GATEWAY_PID_START_IDENTITY=", + "AUTO_PAIR_PID=303", + "AUTO_PAIR_PID_START_IDENTITY=3003", + "GATEWAY_LOG_TAIL_PID=", + "GATEWAY_LOG_TAIL_PID_START_IDENTITY=", + "GATEWAY_LOG_PERSIST_PID=", + "GATEWAY_LOG_PERSIST_PID_START_IDENTITY=", + "PLUGIN_REFRESH_PID=404", + "PLUGIN_REFRESH_PID_START_IDENTITY=4004", + "GATEWAY_WATCHDOG_PID=", + "GATEWAY_WATCHDOG_PID_START_IDENTITY=", + 'gateway_control_stop_tracked_pid() { printf "unsafe-stop\\n"; }', + extractShellFunction(src, "openclaw_supervised_aux_pid_is_live"), + extractShellFunction(src, "stop_openclaw_supervised_gateway"), + extractShellFunction(src, "refresh_openclaw_supervised_child_pids"), + "refresh_openclaw_supervised_child_pids", + 'printf "%s\\n" "${SANDBOX_CHILD_PIDS[*]}"', + 'if stop_openclaw_supervised_gateway 404 4004; then printf "STOPPED\\n"; else printf "STOP_REJECTED\\n"; fi', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, `script failed: ${result.stderr}`).toBe(0); + expect(result.stdout).toBe("303\nSTOP_REJECTED\n"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("does not accept a tracked-stop success while the numeric gateway PID remains live", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const script = [ + "set -uo pipefail", + "openclaw_supervised_pid_is_live() { return 0; }", + 'gateway_control_stop_tracked_pid() { printf "stop:%s:%s\\n" "$1" "$2"; return 0; }', + 'kill() { [ "$1" = "-0" ] && return 0; printf "unexpected-signal\\n"; }', + extractShellFunction(source, "stop_openclaw_supervised_gateway"), + "rc=0; stop_openclaw_supervised_gateway 4242 777 || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("stop:4242:777\nrc:1\n"); + expect(result.stderr).toContain("remains live after tracked stop"); + expect(result.stdout).not.toContain("unexpected-signal"); + }); + + it("exits PID 1 instead of marking an unproven OpenClaw gateway stopped", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const script = [ + "set -uo pipefail", + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + "stop_openclaw_supervised_gateway() { printf 'stop-refused\\n'; return 1; }", + "mark_openclaw_gateway_stopped() { printf 'unexpected-mark\\n'; }", + extractShellFunction(source, "stop_openclaw_gateway_fail_closed"), + "stop_openclaw_gateway_fail_closed", + "printf 'unexpected-return\\n'", + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status).toBe(1); + expect(result.stdout).toBe("stop-refused\n"); + expect(result.stderr).toContain("exiting PID 1 for whole-container cleanup"); + expect(result.stdout).not.toContain("unexpected-mark"); + expect(result.stdout).not.toContain("unexpected-return"); + }); + + it.each([ + ["a live PID with a different start identity", 'printf "888\\n"', "S"], + ["a live PID whose identity is temporarily unavailable", "return 1", "S"], + ])("refuses to reap %s", (_label, identityBody, state) => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const script = [ + "set -euo pipefail", + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + "GATEWAY_CONTROL_SIGNAL_PENDING=0", + `openclaw_pid_start_identity() { ${identityBody}; }`, + 'kill() { [ "$1" = "-0" ] && return 0; return 1; }', + `gateway_control_pid_state() { printf "${state}\\n"; }`, + 'wait() { printf "unexpected-wait:%s\\n" "$1"; }', + "openclaw_supervised_pid_is_live() { return 1; }", + "gateway_pid_is_openclaw_gateway() { return 1; }", + "mark_openclaw_gateway_stopped() { printf 'unexpected-mark\\n'; }", + extractShellFunction(source, "openclaw_reap_exited_gateway"), + "rc=0; openclaw_reap_exited_gateway || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("rc:2\n"); + expect(result.stderr).toContain("refusing to"); + expect(result.stdout).not.toContain("unexpected-wait"); + expect(result.stdout).not.toContain("unexpected-mark"); + }); +}); + +describe("managed gateway restart config boundary", () => { + it("routes unrecoverable seal failure through whole-container gateway revocation", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const script = [ + "set -uo pipefail", + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + "gateway_control_take_request() { GATEWAY_CONTROL_ACTION=restart; printf 'take-request\\n'; }", + "prepare_openclaw_gateway_restart() { printf 'prepare\\n'; return 0; }", + 'run_openclaw_config_guard() { printf "guard:%s\\n" "$1"; [ "$1" != "seal-restart" ]; }', + "restore_openclaw_restart_config() { printf 'restore-failed\\n'; return 1; }", + "stop_openclaw_gateway_fail_closed() { printf 'fail-closed-stop\\n'; }", + 'gateway_control_fail() { printf "fail:%s:%s\\n" "$1" "$2"; }', + extractShellFunction(source, "handle_openclaw_gateway_control_request"), + "rc=0; handle_openclaw_gateway_control_request || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual([ + "take-request", + "prepare", + "guard:seal-restart", + "restore-failed", + "fail-closed-stop", + "fail:unsafe-config:4242", + "rc:1", + ]); + }); + + it("removes only regular gateway locks and refuses a matching attacker directory", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-lock-cleanup-")); + const parent = path.join(tmpDir, "openclaw-test"); + const regularLock = path.join(parent, "gateway.good.lock"); + const plantedDirectory = path.join(parent, "gateway.evil.lock"); + const sentinel = path.join(plantedDirectory, "sentinel"); + fs.mkdirSync(plantedDirectory, { recursive: true }); + fs.writeFileSync(regularLock, "lock\n"); + fs.writeFileSync(sentinel, "keep\n"); + + const cleanup = extractShellFunction(source, "cleanup_openclaw_gateway_locks").replace( + 'os.open("/tmp", directory_flags)', + `os.open(${JSON.stringify(tmpDir)}, directory_flags)`, + ); + const script = path.join(tmpDir, "run.sh"); + fs.writeFileSync( + script, + ["#!/usr/bin/env bash", "set -euo pipefail", cleanup, "cleanup_openclaw_gateway_locks"].join( + "\n", + ), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [script], { encoding: "utf-8", timeout: 10_000 }); + expect(result.status, result.stderr).toBe(0); + expect(fs.existsSync(regularLock)).toBe(false); + expect(fs.readFileSync(sentinel, "utf-8")).toBe("keep\n"); + expect(result.stderr).toContain("refusing non-regular lock entry"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); }); describe("record_gateway_pid", () => { @@ -380,7 +711,7 @@ describe("record_gateway_pid", () => { `GATEWAY_PID_FILE=${JSON.stringify(pidFile)}`, safeTmpHelpers(fs.readFileSync(START_SCRIPT, "utf-8")), extractShellFunction(fs.readFileSync(START_SCRIPT, "utf-8"), "record_gateway_pid"), - "record_gateway_pid 4242", + "record_gateway_pid 4242 987654", ].join("\n"), { mode: 0o755 }, ); @@ -391,7 +722,7 @@ describe("record_gateway_pid", () => { // the content read — no check-then-use window. const fd = fs.openSync(pidFile, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); try { - expect(fs.readFileSync(fd, "utf-8")).toBe("4242\n"); + expect(fs.readFileSync(fd, "utf-8")).toBe("4242 987654\n"); } finally { fs.closeSync(fd); } @@ -419,19 +750,55 @@ describe("record_gateway_pid", () => { `GATEWAY_PID_FILE=${JSON.stringify(pidFile)}`, safeTmpHelpers(fs.readFileSync(START_SCRIPT, "utf-8")), extractShellFunction(fs.readFileSync(START_SCRIPT, "utf-8"), "record_gateway_pid"), - "record_gateway_pid 4242", + "record_gateway_pid 4242 987654", ].join("\n"), { mode: 0o755 }, ); const result = spawnSync("bash", [script], { encoding: "utf-8", timeout: 5000 }); expect(result.status, `script failed: ${result.stderr}`).toBe(0); - expect(fs.readFileSync(pidFile, "utf-8")).toBe("4242\n"); + expect(fs.readFileSync(pidFile, "utf-8")).toBe("4242 987654\n"); expect((fs.statSync(pidFile).mode & 0o777).toString(8)).toBe("600"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } }); + + it("clears the pid/starttime record when the tracked gateway is marked stopped", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-watchdog-pid-clear-")); + const pidFile = path.join(tmpDir, "gateway.pid"); + const script = path.join(tmpDir, "run.sh"); + fs.writeFileSync( + script, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `GATEWAY_PID_FILE=${JSON.stringify(pidFile)}`, + "GATEWAY_PID=4242", + "GATEWAY_PID_START_IDENTITY=987654", + "SANDBOX_WAIT_PID=4242", + safeTmpHelpers(src), + extractShellFunction(src, "record_gateway_pid"), + extractShellFunction(src, "clear_gateway_pid_record"), + "refresh_openclaw_supervised_child_pids() { SANDBOX_CHILD_PIDS=(); }", + extractShellFunction(src, "mark_openclaw_gateway_stopped"), + 'record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY"', + "mark_openclaw_gateway_stopped", + 'printf "PID=%s ID=%s WAIT=%s\\n" "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY" "$SANDBOX_WAIT_PID"', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [script], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("PID=0 ID= WAIT=\n"); + expect(fs.readFileSync(pidFile, "utf-8")).toBe(""); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); }); describe("gateway_pid_is_openclaw_gateway", () => { @@ -483,6 +850,106 @@ describe("gateway_pid_is_openclaw_gateway", () => { }); }); +describe("openclaw_gateway_healthy listener ownership", () => { + function checkHealth(listenerOwned: boolean): { + result: ReturnType<typeof spawnSync>; + events: string; + } { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-health-owner-")); + const eventLog = path.join(tmpDir, "events.log"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + "_DASHBOARD_PORT=19000", + `EVENT_LOG=${JSON.stringify(eventLog)}`, + `LISTENER_OWNED=${listenerOwned ? "1" : "0"}`, + "openclaw_gateway_pid_owns_listener() {", + ' printf "owner-check:%s:%s\\n" "$1" "$2" >>"$EVENT_LOG"', + ' [ "$LISTENER_OWNED" -eq 1 ]', + "}", + "curl() {", + ' printf "http-probe\\n" >>"$EVENT_LOG"', + ' printf "200"', + "}", + 'openclaw_supervised_pid_is_live() { [ "$1:$2" = "4242:valid-start" ]; }', + extractShellFunction(src, "openclaw_gateway_healthy"), + 'if openclaw_gateway_healthy 4242 valid-start; then printf "healthy\\n"; else printf "unhealthy\\n"; fi', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + return { result, events: readFileIfPresent(eventLog) ?? "" }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } + + it("rejects HTTP 200 from a listener not owned by the tracked gateway process", () => { + const { result, events } = checkHealth(false); + expect(result.status, `script failed: ${result.stderr}`).toBe(0); + expect(result.stdout).toBe("unhealthy\n"); + expect(events).toBe("http-probe\nowner-check:4242:19000\n"); + }); + + it("accepts HTTP 200 only after listener ownership is established", () => { + const { result, events } = checkHealth(true); + expect(result.status, `script failed: ${result.stderr}`).toBe(0); + expect(result.stdout).toBe("healthy\n"); + expect(events).toBe("http-probe\nowner-check:4242:19000\n"); + }); + + it("rejects a PID1-adopted recycled PID even when its cmdline and listener look valid", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-reused-identity-")); + const procRoot = path.join(tmpDir, "proc"); + const eventLog = path.join(tmpDir, "events.log"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(path.join(procRoot, "4242"), { recursive: true }); + fs.writeFileSync(path.join(procRoot, "4242", "cmdline"), "openclaw-gateway\0"); + + const supervisedAsPid1 = extractShellFunction(src, "openclaw_supervised_pid_is_live").replace( + '"$$"', + '"1"', + ); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `_NEMOCLAW_PROC_ROOT=${JSON.stringify(procRoot)}`, + `_DASHBOARD_PORT=19000`, + `EVENT_LOG=${JSON.stringify(eventLog)}`, + writeProcStatFunction, + 'write_proc_stat 4242 1 222222 >"$_NEMOCLAW_PROC_ROOT/4242/stat"', + pidIdentityFunctions(src), + supervisedAsPid1, + extractShellFunction(src, "gateway_pid_is_openclaw_gateway"), + 'openclaw_gateway_pid_owns_listener() { printf "listener-called\\n" >>"$EVENT_LOG"; return 0; }', + 'curl() { printf "200"; }', + extractShellFunction(src, "openclaw_gateway_healthy"), + 'gateway_pid_is_openclaw_gateway 4242 && printf "LOOKS_OPENCLAW=1\\n"', + 'if openclaw_gateway_healthy 4242 111111; then printf "HEALTHY=1\\n"; else printf "HEALTHY=0\\n"; fi', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("LOOKS_OPENCLAW=1\nHEALTHY=0\n"); + expect(readFileIfPresent(eventLog)).toBeNull(); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); + describe("healthcheck marker (#4503, #4710)", () => { // Behavioral test of the marker function: confirms the helper itself writes // an empty file at the target path and is a no-op when the path is already @@ -525,13 +992,50 @@ describe("healthcheck marker (#4503, #4710)", () => { // behaviorally: OPENSHELL_DRIVERS is exported during the run and must have // no influence on whether the marker is dropped. describe("gateway launch wiring (#4710)", () => { + it("exits PID 1 without signaling when gateway identity capture fails", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const launch = extractShellFunction(src, "launch_openclaw_gateway"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-capture-failure-")); + const eventLog = path.join(tmpDir, "events.log"); + const result = spawnSync( + "bash", + [ + "--noprofile", + "--norc", + "-c", + [ + "set -uo pipefail", + `EVENT_LOG=${JSON.stringify(eventLog)}`, + "STEP_DOWN_PREFIX_GATEWAY=()", + "OPENCLAW=/usr/bin/true", + "_DASHBOARD_PORT=19000", + "GATEWAY_PID=0", + "GATEWAY_PID_START_IDENTITY=", + "mark_in_container_gateway() { :; }", + "capture_openclaw_pid_start_identity() { return 1; }", + 'clear_gateway_pid_record() { printf "clear\\n" >>"$EVENT_LOG"; }', + 'kill() { printf "unexpected-kill:%s\\n" "$*" >>"$EVENT_LOG"; }', + 'wait() { printf "unexpected-wait:%s\\n" "$*" >>"$EVENT_LOG"; }', + launch, + "launch_openclaw_gateway", + ].join("\n"), + ], + { encoding: "utf-8", timeout: 5000 }, + ); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("could not capture gateway process identity"); + expect(fs.readFileSync(eventLog, "utf-8")).toBe("clear\n"); + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + function launchBlock(src: string, kind: "non-root" | "root"): string { const startMarker = kind === "non-root" ? "# Start gateway in background, auto-pair, then wait" : "# Start the gateway as the 'gateway' user."; const start = src.indexOf(startMarker); - const trap = src.indexOf("trap cleanup_on_signal SIGTERM SIGINT", start); + const trap = src.indexOf("trap cleanup_openclaw_on_signal SIGTERM SIGINT", start); expect(start, `Expected ${kind} gateway launch block in scripts/nemoclaw-start.sh`).not.toBe( -1, ); @@ -569,6 +1073,7 @@ describe("gateway launch wiring (#4710)", () => { extractShellFunction(src, "gateway_pid_is_openclaw_gateway"), extractShellFunction(src, "gateway_watchdog_positive_int_ok"), extractShellFunction(src, "start_gateway_serving_watchdog"), + rootGatewayLifecycleFunctions(src, gatewayLog), ].join("\n"); fs.writeFileSync( @@ -585,8 +1090,8 @@ describe("gateway launch wiring (#4710)", () => { `GATEWAY_PID_FILE=${JSON.stringify(pidFile)}`, // Keep the watchdog idle for the duration of the test run. "export NEMOCLAW_GATEWAY_WATCHDOG_INTERVAL_SECONDS=300", - "start_persistent_gateway_log_mirror() { command sleep 30 & GATEWAY_LOG_PERSIST_PID=$!; }", - "start_auto_pair() { command sleep 30 & AUTO_PAIR_PID=$!; }", + 'start_persistent_gateway_log_mirror() { command sleep 30 & GATEWAY_LOG_PERSIST_PID=$!; capture_openclaw_pid_start_identity "$GATEWAY_LOG_PERSIST_PID" GATEWAY_LOG_PERSIST_PID_START_IDENTITY; }', + 'start_auto_pair() { command sleep 30 & AUTO_PAIR_PID=$!; capture_openclaw_pid_start_identity "$AUTO_PAIR_PID" AUTO_PAIR_PID_START_IDENTITY; }', "start_plugin_registry_refresh() { :; }", "cleanup_on_signal() { :; }", "STEP_DOWN_PREFIX_SANDBOX=(gosu sandbox)", @@ -626,7 +1131,7 @@ describe("gateway launch wiring (#4710)", () => { expect(run.markerExists).toBe(true); // The watchdog reads the gateway PID from the pidfile each cycle. expect(run.gatewayPid).toBeDefined(); - expect(run.pidFileContent).toBe(run.gatewayPid); + expect(run.pidFileContent?.split(" ")[0]).toBe(run.gatewayPid); // The watchdog runs and is registered for SIGTERM cleanup. expect(run.watchdogPid).toBeDefined(); expect(run.stdout).toContain("WATCHDOG_ALIVE=1"); @@ -662,11 +1167,12 @@ describe("respawn loop pidfile refresh (#4710)", () => { const gatewayLog = path.join(tmpDir, "gateway.log"); const pidFile = path.join(tmpDir, "gateway.pid"); const initialPidFile = path.join(tmpDir, "initial.pid"); + const restoreSentinel = path.join(tmpDir, "runtime-guards-restored"); const scriptPath = path.join(tmpDir, "run.sh"); fs.mkdirSync(fakeBin); fs.writeFileSync( path.join(fakeBin, "openclaw"), - `#!/usr/bin/env bash\nprintf '%s\\n' "$*" >> ${JSON.stringify(openclawLog)}\nexec sleep 30\n`, + `#!/usr/bin/env bash\n[ -f ${JSON.stringify(restoreSentinel)} ] || exit 97\nprintf '%s\\n' "$*" >> ${JSON.stringify(openclawLog)}\nexec sleep 30\n`, { mode: 0o755 }, ); fs.writeFileSync(path.join(fakeBin, "gosu"), `#!/usr/bin/env bash\nshift\nexec "$@"\n`, { @@ -683,18 +1189,29 @@ describe("respawn loop pidfile refresh (#4710)", () => { '_DASHBOARD_PORT="19000"', `GATEWAY_PID_FILE=${JSON.stringify(pidFile)}`, "STEP_DOWN_PREFIX_GATEWAY=(gosu gateway)", + `prepare_openclaw_automatic_respawn() { printf restored >${JSON.stringify(restoreSentinel)}; }`, // The loop sleeps 2s between respawns; keep the test fast. "sleep() { command sleep 0.05; }", safeTmpHelpers(src), extractShellFunction(src, "record_gateway_pid"), + extractShellFunction(src, "clear_gateway_pid_record"), + rootGatewayLifecycleFunctions(src, gatewayLog), + kind === "root" ? "mark_in_container_gateway() { :; }" : "", + kind === "root" ? "GATEWAY_CONTROL_SIGNAL_PENDING=0" : "", + kind === "root" ? "handle_openclaw_gateway_control_request() { :; }" : "", + kind === "root" + ? 'openclaw_supervised_pid_is_live() { local current; gateway_control_pid_is_live "$1" || return 1; current="$(openclaw_pid_start_identity "$1")" || return 1; [ "$current" = "$2" ]; }' + : "", + kind === "root" ? "gateway_pid_is_openclaw_gateway() { return 0; }" : "", "SANDBOX_CHILD_PIDS=()", "SANDBOX_WAIT_PID=", "(", // A gateway that dies immediately with a non-zero status drives // exactly one respawn iteration. - ' bash -c "exit 7" &', + ' bash -c "sleep 0.1; exit 7" &', " GATEWAY_PID=$!", - ' record_gateway_pid "$GATEWAY_PID"', + ' GATEWAY_PID_START_IDENTITY="$(openclaw_pid_start_identity "$GATEWAY_PID")"', + ' record_gateway_pid "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY"', ` printf '%s' "$GATEWAY_PID" > ${JSON.stringify(initialPidFile)}`, respawnLoop(src, kind).replaceAll("/tmp/gateway.log", gatewayLog), ") &", @@ -702,7 +1219,7 @@ describe("respawn loop pidfile refresh (#4710)", () => { 'INITIAL=""; CURRENT=""', "for _ in $(command seq 1 200); do", ` INITIAL="$(cat ${JSON.stringify(initialPidFile)} 2>/dev/null || true)"`, - ` CURRENT="$(cat ${JSON.stringify(pidFile)} 2>/dev/null || true)"`, + ` CURRENT="$(awk '{ print $1 }' ${JSON.stringify(pidFile)} 2>/dev/null || true)"`, ' if [ -n "$INITIAL" ] && [ -n "$CURRENT" ] && [ "$CURRENT" != "$INITIAL" ]; then break; fi', " command sleep 0.05", "done", @@ -732,11 +1249,102 @@ describe("respawn loop pidfile refresh (#4710)", () => { expect(current, `no current pid in: ${stdout}`).toBeDefined(); expect(current).not.toBe(initial); expect(stdout).toContain("RESPAWNED_ALIVE=1"); + expect(fs.readFileSync(restoreSentinel, "utf-8")).toBe("restored"); expect(fs.readFileSync(openclawLog, "utf-8")).toContain("gateway run --port 19000"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } }); + + it("services a supervisor request that interrupts root respawn backoff before relaunch", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + const supervisor = fs.readFileSync(GATEWAY_SUPERVISOR, "utf-8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-respawn-control-race-")); + const eventLog = path.join(tmpDir, "events.log"); + const launchPidFile = path.join(tmpDir, "automatic-launch.pid"); + const gatewayLog = path.join(tmpDir, "gateway.log"); + const scriptPath = path.join(tmpDir, "run.sh"); + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `EVENT_LOG=${JSON.stringify(eventLog)}`, + `LAUNCH_PID_FILE=${JSON.stringify(launchPidFile)}`, + "GATEWAY_CONTROL_SIGNAL_PENDING=0", + "GATEWAY_PID_START_IDENTITY=reused-start", + "GATEWAY_REAPED=0", + "REUSED_GATEWAY_PID=0", + // Model USR1 interrupting the two-second crash backoff. Returning a + // signal-like status also proves the production sleep is guarded from + // errexit before it inspects the pending flag. + "sleep() {", + ' if [ "${1:-}" = "2" ]; then', + ' printf "backoff-interrupted\\n" >>"$EVENT_LOG"', + " GATEWAY_CONTROL_SIGNAL_PENDING=1", + " return 130", + " fi", + " command sleep 0.02", + "}", + extractShellFunction(supervisor, "gateway_control_pid_is_live").replace( + "gateway_control_pid_is_live() {", + "gateway_control_pid_is_live_real() {", + ), + "gateway_control_pid_is_live() {", + ' if [ "$GATEWAY_REAPED" -eq 1 ] && [ "$1" = "$REUSED_GATEWAY_PID" ]; then return 0; fi', + ' gateway_control_pid_is_live_real "$1"', + "}", + "gateway_control_pid_state() { printf 'Z\\n'; }", + 'openclaw_pid_start_identity() { printf "%s\\n" "$GATEWAY_PID_START_IDENTITY"; }', + "openclaw_supervised_pid_is_live() { return 1; }", + "gateway_pid_is_openclaw_gateway() { return 1; }", + "wait() {", + " local rc=0", + ' builtin wait "$@" || rc=$?', + " GATEWAY_REAPED=1", + ' return "$rc"', + "}", + "handle_openclaw_gateway_control_request() {", + ' printf "request-handled:tracked=%s\\n" "$GATEWAY_PID" >>"$EVENT_LOG"', + ' [ "$GATEWAY_PID" -eq 0 ] || exit 91', + // End the extracted infinite PID 1 loop once the assertion event has + // occurred. The surrounding subshell lets the harness continue. + " exit 0", + "}", + "launch_openclaw_gateway() {", + ' printf "automatic-relaunch\\n" >>"$EVENT_LOG"', + " command sleep 30 &", + " GATEWAY_PID=$!", + ' printf "%s\\n" "$GATEWAY_PID" >"$LAUNCH_PID_FILE"', + "}", + "refresh_openclaw_supervised_child_pids() { :; }", + extractShellFunction(src, "mark_openclaw_gateway_stopped"), + extractShellFunction(src, "openclaw_reap_exited_gateway"), + "(", + ' bash -c "exit 7" &', + " GATEWAY_PID=$!", + ' REUSED_GATEWAY_PID="$GATEWAY_PID"', + respawnLoop(src, "root").replaceAll("/tmp/gateway.log", gatewayLog), + ")", + // Defensive cleanup makes the harness safe against a regression that + // performs the automatic relaunch before servicing the request. + 'if [ -s "$LAUNCH_PID_FILE" ]; then kill -9 "$(cat "$LAUNCH_PID_FILE")" 2>/dev/null || true; fi', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, `script failed: ${result.stderr}`).toBe(0); + expect(fs.readFileSync(eventLog, "utf-8")).toBe( + "backoff-interrupted\nrequest-handled:tracked=0\n", + ); + expect(readFileIfPresent(launchPidFile)).toBeNull(); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); }); // Launch-path signal handling and child-PID tracking for both entrypoint @@ -751,7 +1359,7 @@ describe("nemoclaw-start gateway launch signal handling", () => { ? "# Start gateway in background, auto-pair, then wait" : "# Start the gateway as the 'gateway' user."; const start = src.indexOf(startMarker); - const trap = src.indexOf("trap cleanup_on_signal SIGTERM SIGINT", start); + const trap = src.indexOf("trap cleanup_openclaw_on_signal SIGTERM SIGINT", start); expect(start, `Expected ${kind} gateway launch block in scripts/nemoclaw-start.sh`).not.toBe( -1, ); @@ -795,8 +1403,8 @@ describe("nemoclaw-start gateway launch signal handling", () => { "export OPENCLAW_CONFIG_PATH=/sandbox/.openclaw/openclaw.json", "export OPENCLAW_OAUTH_DIR=/sandbox/.openclaw/credentials", '_DASHBOARD_PORT="19000"', - "start_persistent_gateway_log_mirror() { sleep 30 & GATEWAY_LOG_PERSIST_PID=$!; }", - "start_auto_pair() { sleep 30 & AUTO_PAIR_PID=$!; }", + 'start_persistent_gateway_log_mirror() { sleep 30 & GATEWAY_LOG_PERSIST_PID=$!; capture_openclaw_pid_start_identity "$GATEWAY_LOG_PERSIST_PID" GATEWAY_LOG_PERSIST_PID_START_IDENTITY; }', + 'start_auto_pair() { sleep 30 & AUTO_PAIR_PID=$!; capture_openclaw_pid_start_identity "$AUTO_PAIR_PID" AUTO_PAIR_PID_START_IDENTITY; }', "start_plugin_registry_refresh() { :; }", "cleanup_on_signal() { :; }", safeTmpHelpers(src), @@ -809,7 +1417,8 @@ describe("nemoclaw-start gateway launch signal handling", () => { // background services. Stub both — watchdog behavior has its own // suite in test/nemoclaw-start-gateway-health.test.ts. "record_gateway_pid() { :; }", - "start_gateway_serving_watchdog() { :; }", + 'start_gateway_serving_watchdog() { sleep 30 & GATEWAY_WATCHDOG_PID=$!; capture_openclaw_pid_start_identity "$GATEWAY_WATCHDOG_PID" GATEWAY_WATCHDOG_PID_START_IDENTITY; }', + rootGatewayLifecycleFunctions(src, gatewayLog), "STEP_DOWN_PREFIX_SANDBOX=(gosu sandbox)", "STEP_DOWN_PREFIX_GATEWAY=(gosu gateway)", launchBlock(kind, gatewayLog), @@ -857,7 +1466,7 @@ describe("nemoclaw-start gateway launch signal handling", () => { expect(stdout).toMatch(/AUTO_PAIR_PID=\d+/); expect(stdout).toMatch(/TAIL_PID=\d+/); expect(stdout).toMatch(/PERSIST_PID=\d+/); - expect(stdout).toContain("cleanup_on_signal"); + expect(stdout).toContain("cleanup_openclaw_on_signal"); }); it("launches the root gateway through gosu with the configured port and tracks child PIDs", () => { @@ -877,6 +1486,6 @@ describe("nemoclaw-start gateway launch signal handling", () => { expect(result.stdout).toMatch(/AUTO_PAIR_PID=\d+/); expect(result.stdout).toMatch(/TAIL_PID=\d+/); expect(result.stdout).toMatch(/PERSIST_PID=\d+/); - expect(result.stdout).toContain("cleanup_on_signal"); + expect(result.stdout).toContain("cleanup_openclaw_on_signal"); }); }); diff --git a/test/nemoclaw-start-gateway-recovery-race.test.ts b/test/nemoclaw-start-gateway-recovery-race.test.ts new file mode 100644 index 00000000000..73f303a7444 --- /dev/null +++ b/test/nemoclaw-start-gateway-recovery-race.test.ts @@ -0,0 +1,192 @@ +// 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 path from "node:path"; +import { describe, expect, it } from "vitest"; + +const START_SCRIPT = path.join(import.meta.dirname, "..", "scripts", "nemoclaw-start.sh"); + +function extractShellFunction(source: string, name: string): string { + const header = `${name}() {`; + const start = source.indexOf(header); + expect(start, `Expected ${name} in scripts/nemoclaw-start.sh`).not.toBe(-1); + const body = source.slice(start + header.length); + const closing = body.match(/^}$/m); + expect(closing, `Expected closing brace for ${name} in scripts/nemoclaw-start.sh`).not.toBeNull(); + return `${name}() {${body.slice(0, closing?.index ?? 0)}\n}`; +} + +describe("OpenClaw gateway recovery during respawn races", () => { + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + + it.each([ + ["already reaped", "0", "", ""], + ["dead but not yet reaped", "101", "old-start", "reap:101:old-start"], + ])("recovers when the previous gateway was %s", (_label, oldPid, oldIdentity, reapEvent) => { + const script = [ + "set -uo pipefail", + `GATEWAY_PID=${JSON.stringify(oldPid)}`, + `GATEWAY_PID_START_IDENTITY=${JSON.stringify(oldIdentity)}`, + "GATEWAY_CONTROL_ACTION=recover", + "gateway_control_take_request() { printf 'take-request\\n'; }", + "openclaw_gateway_healthy() { return 1; }", + "prepare_openclaw_gateway_restart() { printf 'prepare\\n'; }", + 'run_openclaw_config_guard() { printf "guard:%s\\n" "$1"; }', + "restore_openclaw_restart_config() { printf 'restore\\n'; }", + "openclaw_supervised_pid_is_live() { return 1; }", + "stop_openclaw_supervised_gateway() { printf 'unexpected-stop\\n'; return 1; }", + "openclaw_reap_exited_gateway() {", + ' printf "reap:%s:%s\\n" "$GATEWAY_PID" "$GATEWAY_PID_START_IDENTITY"', + " GATEWAY_PID=0", + " GATEWAY_PID_START_IDENTITY=", + "}", + "mark_openclaw_gateway_stopped() { printf 'mark-stopped\\n'; GATEWAY_PID=0; GATEWAY_PID_START_IDENTITY=; }", + "cleanup_openclaw_gateway_locks() { printf 'cleanup-locks\\n'; }", + "launch_openclaw_gateway() { printf 'launch\\n'; GATEWAY_PID=202; GATEWAY_PID_START_IDENTITY=new-start; }", + 'wait_for_openclaw_gateway_internal() { printf "wait:%s:%s\\n" "$1" "$2"; }', + "stop_openclaw_gateway_fail_closed() { printf 'unexpected-fail-closed\\n'; return 1; }", + "refresh_openclaw_supervised_child_pids() { printf 'refresh-children\\n'; }", + "start_plugin_registry_refresh() { printf 'plugin-refresh\\n'; }", + 'gateway_control_complete() { printf "complete:%s:%s:%s\\n" "$1" "$2" "$3"; }', + 'gateway_control_fail() { printf "unexpected-fail:%s:%s\\n" "$1" "$2"; }', + extractShellFunction(source, "retire_openclaw_supervised_gateway"), + extractShellFunction(source, "handle_openclaw_gateway_control_request"), + "rc=0; handle_openclaw_gateway_control_request || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual( + [ + "take-request", + "prepare", + "guard:seal-restart", + reapEvent, + "mark-stopped", + "cleanup-locks", + "launch", + "refresh-children", + "wait:202:new-start", + "restore", + "plugin-refresh", + "refresh-children", + `complete:ok:${oldPid}:202`, + "rc:0", + ].filter(Boolean), + ); + expect(result.stdout).not.toContain("unexpected-"); + }); + + it.each([ + ["a dead tracked gateway cannot be safely reaped", "101", "old-start", "101"], + ["the stopped tuple retains an inconsistent wait PID", "0", "", "101"], + ])("refuses recovery when %s", (_label, oldPid, oldIdentity, waitPid) => { + const script = [ + "set -uo pipefail", + `GATEWAY_PID=${JSON.stringify(oldPid)}`, + `GATEWAY_PID_START_IDENTITY=${JSON.stringify(oldIdentity)}`, + `SANDBOX_WAIT_PID=${JSON.stringify(waitPid)}`, + "GATEWAY_CONTROL_ACTION=recover", + "gateway_control_take_request() { printf 'take-request\\n'; }", + "openclaw_gateway_healthy() { return 1; }", + "prepare_openclaw_gateway_restart() { printf 'prepare\\n'; }", + 'run_openclaw_config_guard() { printf "guard:%s\\n" "$1"; }', + "restore_openclaw_restart_config() { printf 'restore\\n'; }", + "openclaw_supervised_pid_is_live() { return 1; }", + "stop_openclaw_supervised_gateway() { printf 'unexpected-stop\\n'; return 1; }", + "openclaw_reap_exited_gateway() { printf 'reap-refused\\n'; return 2; }", + "mark_openclaw_gateway_stopped() { printf 'unexpected-mark\\n'; }", + "cleanup_openclaw_gateway_locks() { printf 'unexpected-cleanup\\n'; }", + "launch_openclaw_gateway() { printf 'unexpected-launch\\n'; }", + 'gateway_control_fail() { printf "fail:%s:%s\\n" "$1" "$2"; }', + extractShellFunction(source, "retire_openclaw_supervised_gateway"), + extractShellFunction(source, "handle_openclaw_gateway_control_request"), + "rc=0; handle_openclaw_gateway_control_request || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe( + `take-request\nprepare\nguard:seal-restart\nreap-refused\nrestore\nfail:internal:${oldPid}\nrc:1\n`, + ); + expect(result.stdout).not.toContain("unexpected-"); + }); + + it.each([ + { + label: "reports the existing gateway healthy", + guardStatus: 0, + healthStatus: 0, + expected: [ + "take-request", + "guard:preflight-restart", + "healthy:4242:777", + "complete:already-running:4242:4242", + "rc:0", + ], + }, + { + label: "rejects an unsafe config before checking health", + guardStatus: 1, + healthStatus: 0, + expected: ["take-request", "guard:preflight-restart", "fail:unsafe-config:4242", "rc:1"], + }, + { + label: "reports an unhealthy gateway after config validation", + guardStatus: 0, + healthStatus: 1, + expected: [ + "take-request", + "guard:preflight-restart", + "healthy:4242:777", + "fail:health-timeout:4242", + "rc:1", + ], + }, + ])("keeps the authenticated probe read-only when it $label", ({ + guardStatus, + healthStatus, + expected, + }) => { + const script = [ + "set -uo pipefail", + "GATEWAY_PID=4242", + 'GATEWAY_PID_START_IDENTITY="777"', + "gateway_control_take_request() { GATEWAY_CONTROL_ACTION=probe; printf 'take-request\\n'; }", + `run_openclaw_config_guard() { printf "guard:%s\\n" "$1"; return ${guardStatus}; }`, + `openclaw_gateway_healthy() { printf "healthy:%s:%s\\n" "$1" "$2"; return ${healthStatus}; }`, + 'gateway_control_complete() { printf "complete:%s:%s:%s\\n" "$1" "$2" "$3"; }', + 'gateway_control_fail() { printf "fail:%s:%s\\n" "$1" "$2"; }', + "prepare_openclaw_gateway_restart() { printf 'unexpected-prepare\\n'; }", + "retire_openclaw_supervised_gateway() { printf 'unexpected-retire\\n'; }", + "mark_openclaw_gateway_stopped() { printf 'unexpected-mark-stopped\\n'; }", + "launch_openclaw_gateway() { printf 'unexpected-launch\\n'; }", + "stop_openclaw_gateway_fail_closed() { printf 'unexpected-stop\\n'; }", + "kill() { printf 'unexpected-signal\\n'; }", + extractShellFunction(source, "handle_openclaw_gateway_control_request"), + "rc=0; handle_openclaw_gateway_control_request || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim().split("\n")).toEqual(expected); + expect(result.stdout).not.toContain("unexpected-"); + }); +}); diff --git a/test/nemoclaw-start-guard-recovery.test.ts b/test/nemoclaw-start-guard-recovery.test.ts new file mode 100644 index 00000000000..cfdfbc43a17 --- /dev/null +++ b/test/nemoclaw-start-guard-recovery.test.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type SpawnSyncReturns, 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"); + +function extractShellFunction(source: string, name: string): string { + const header = `${name}() {`; + const start = source.indexOf(header); + expect(start, `expected ${name} in nemoclaw-start.sh`).not.toBe(-1); + const body = source.slice(start + header.length); + const closing = body.match(/^}$/m); + expect(closing, `expected closing brace for ${name}`).not.toBeNull(); + return `${name}() {${body.slice(0, closing?.index ?? 0)}\n}`; +} + +type Harness = { + eventLog: string; + result: SpawnSyncReturns<string>; + sources: Record<string, string>; + targets: Record<string, string>; + tmpDir: string; +}; + +function runRecoveryHarness({ missingCiaoSource = false } = {}): Harness { + const source = fs.readFileSync(START_SCRIPT, "utf8"); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-guard-recovery-")); + const eventLog = path.join(tmpDir, "events.log"); + const sources = { + safety: path.join(tmpDir, "source-safety.js"), + proxy: path.join(tmpDir, "source-proxy.js"), + nemotron: path.join(tmpDir, "source-nemotron.js"), + ciao: path.join(tmpDir, "source-ciao.js"), + websocket: path.join(tmpDir, "source-websocket.js"), + seccomp: path.join(tmpDir, "source-seccomp.js"), + }; + const targets = { + safety: path.join(tmpDir, "target-safety.js"), + proxy: path.join(tmpDir, "target-proxy.js"), + nemotron: path.join(tmpDir, "target-nemotron.js"), + ciao: path.join(tmpDir, "target-ciao.js"), + websocket: path.join(tmpDir, "target-websocket.js"), + seccomp: path.join(tmpDir, "target-seccomp.js"), + runtimeEnv: path.join(tmpDir, "nemoclaw-proxy-env.sh"), + }; + + const stagedSources = Object.entries(sources).filter( + ([name]) => !missingCiaoSource || name !== "ciao", + ); + for (const [name, sourcePath] of stagedSources) { + fs.writeFileSync(sourcePath, `module.exports = ${JSON.stringify(name)};\n`, { mode: 0o644 }); + } + + const script = [ + "set -uo pipefail", + `EVENT_LOG=${JSON.stringify(eventLog)}`, + 'NODE_OPTIONS=""', + "NODE_USE_ENV_PROXY=1", + `_SANDBOX_SAFETY_NET=${JSON.stringify(targets.safety)}`, + `_SANDBOX_SAFETY_NET_SOURCE=${JSON.stringify(sources.safety)}`, + `_PROXY_FIX_SCRIPT=${JSON.stringify(targets.proxy)}`, + `_PROXY_FIX_SOURCE=${JSON.stringify(sources.proxy)}`, + `_NEMOTRON_FIX_SCRIPT=${JSON.stringify(targets.nemotron)}`, + `_NEMOTRON_FIX_SOURCE=${JSON.stringify(sources.nemotron)}`, + `_CIAO_GUARD_SCRIPT=${JSON.stringify(targets.ciao)}`, + `_CIAO_GUARD_SOURCE=${JSON.stringify(sources.ciao)}`, + `_WS_FIX_SCRIPT=${JSON.stringify(targets.websocket)}`, + `_WS_FIX_SOURCE=${JSON.stringify(sources.websocket)}`, + `_SECCOMP_GUARD_SCRIPT=${JSON.stringify(targets.seccomp)}`, + `_SECCOMP_GUARD_SOURCE=${JSON.stringify(sources.seccomp)}`, + `_RUNTIME_SHELL_ENV_FILE=${JSON.stringify(targets.runtimeEnv)}`, + "OPENCLAW_RESTART_FAILURE_CODE=internal", + "emit_sandbox_sourced_file() {", + ' local target="$1" stage="${1}.stage"', + ' cat >"$stage" || return 1', + ' chmod 444 "$stage" || return 1', + ' mv -f "$stage" "$target" || return 1', + ' printf "emit:%s\\n" "$(basename "$target")" >>"$EVENT_LOG"', + "}", + 'run_openclaw_config_guard() { printf "guard:%s\\n" "$1" >>"$EVENT_LOG"; }', + 'write_messaging_runtime_setup_plan() { printf "write-messaging-plan\\n" >>"$EVENT_LOG"; }', + 'install_messaging_runtime_preloads() { printf "messaging\\n" >>"$EVENT_LOG"; }', + 'verify_messaging_runtime_secret_scans() { printf "secret-scan\\n" >>"$EVENT_LOG"; }', + "write_runtime_shell_env() {", + ' printf "write-runtime-env\\n" >>"$EVENT_LOG"', + ' printf "%s\\n" "# recovered runtime environment" | emit_sandbox_sourced_file "$_RUNTIME_SHELL_ENV_FILE"', + "}", + "validate_nemoclaw_tmp_permissions() {", + ' printf "validate\\n" >>"$EVENT_LOG"', + ' local target; for target in "$_SANDBOX_SAFETY_NET" "$_PROXY_FIX_SCRIPT" "$_NEMOTRON_FIX_SCRIPT" "$_CIAO_GUARD_SCRIPT" "$_WS_FIX_SCRIPT" "$_SECCOMP_GUARD_SCRIPT" "$_RUNTIME_SHELL_ENV_FILE"; do', + ' [ -f "$target" ] && [ ! -L "$target" ] || return 1', + " done", + "}", + extractShellFunction(source, "node_options_has_require"), + extractShellFunction(source, "append_node_require_once"), + extractShellFunction(source, "install_core_runtime_preloads"), + extractShellFunction(source, "openclaw_runtime_guard_chain_complete"), + extractShellFunction(source, "restore_openclaw_runtime_guard_chain"), + extractShellFunction(source, "prepare_openclaw_gateway_restart"), + "rc=0; prepare_openclaw_gateway_restart || rc=$?", + 'if [ "$rc" -eq 0 ] && [ "${RUN_TWICE:-0}" = "1" ]; then prepare_openclaw_gateway_restart || rc=$?; fi', + 'printf "rc:%s\\nfailure-code:%s\\nnode-options:%s\\n" "$rc" "$OPENCLAW_RESTART_FAILURE_CODE" "$NODE_OPTIONS"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf8", + env: { ...process.env, RUN_TWICE: missingCiaoSource ? "0" : "1" }, + timeout: 10_000, + }); + return { eventLog, result, sources, targets, tmpDir }; +} + +describe("OpenClaw PID 1 guard-chain recovery", () => { + it("re-stages packaged guards before rebuilding and validating the runtime environment", () => { + const harness = runRecoveryHarness(); + try { + expect(harness.result.status, harness.result.stderr).toBe(0); + expect(harness.result.stdout).toContain("rc:0\n"); + expect(harness.result.stderr.match(/restoring library guards/g)).toHaveLength(1); + + const onePass = [ + "guard:preflight-restart", + "emit:target-safety.js", + "emit:target-proxy.js", + "emit:target-nemotron.js", + "emit:target-ciao.js", + "emit:target-websocket.js", + "emit:target-seccomp.js", + "write-messaging-plan", + "messaging", + "secret-scan", + "write-runtime-env", + "emit:nemoclaw-proxy-env.sh", + "validate", + ]; + expect(fs.readFileSync(harness.eventLog, "utf8").trim().split("\n")).toEqual([ + ...onePass, + ...onePass, + ]); + + for (const name of ["safety", "proxy", "nemotron", "ciao", "websocket", "seccomp"]) { + const target = harness.targets[name]; + expect(fs.readFileSync(target, "utf8")).toBe( + fs.readFileSync(harness.sources[name], "utf8"), + ); + expect(fs.statSync(target).mode & 0o777).toBe(0o444); + expect(harness.result.stdout.split(target)).toHaveLength(2); + } + expect(fs.statSync(harness.targets.runtimeEnv).mode & 0o777).toBe(0o444); + } finally { + fs.rmSync(harness.tmpDir, { recursive: true, force: true }); + } + }); + + it("fails closed as preload-missing before validation when a packaged guard is absent", () => { + const harness = runRecoveryHarness({ missingCiaoSource: true }); + try { + expect(harness.result.status, harness.result.stderr).toBe(0); + expect(harness.result.stdout).toContain("rc:1\n"); + expect(harness.result.stdout).toContain("failure-code:preload-missing\n"); + expect(harness.result.stderr).toContain("source-ciao.js"); + const events = fs.readFileSync(harness.eventLog, "utf8"); + expect(events).toContain("guard:preflight-restart"); + expect(events).not.toContain("write-messaging-plan"); + expect(events).not.toContain("messaging"); + expect(events).not.toContain("write-runtime-env"); + expect(events).not.toContain("validate"); + } finally { + fs.rmSync(harness.tmpDir, { recursive: true, force: true }); + } + }); + + it("refuses an automatic respawn when guard restoration fails", () => { + const source = fs.readFileSync(START_SCRIPT, "utf8"); + const script = [ + "set -uo pipefail", + "restore_openclaw_runtime_guard_chain() { printf 'restore-attempted\\n'; return 1; }", + extractShellFunction(source, "prepare_openclaw_automatic_respawn"), + "rc=0; prepare_openclaw_automatic_respawn || rc=$?", + 'printf "rc:%s\\n" "$rc"', + ].join("\n"); + + const result = spawnSync("bash", ["--noprofile", "--norc", "-c", script], { + encoding: "utf8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe("restore-attempted\nrc:1\n"); + expect(result.stderr).toContain("refusing automatic respawn"); + }); +}); diff --git a/test/nemoclaw-start-locked-parent.test.ts b/test/nemoclaw-start-locked-parent.test.ts new file mode 100644 index 00000000000..2cd936aaa4f --- /dev/null +++ b/test/nemoclaw-start-locked-parent.test.ts @@ -0,0 +1,73 @@ +// 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"); + +function extractShellFunction(source: string, name: string): string { + const start = source.indexOf(`${name}() {`); + expect(start, `Expected ${name} in nemoclaw-start.sh`).toBeGreaterThanOrEqual(0); + const body = source.slice(start); + const end = body.indexOf("\n}"); + expect(end, `Expected ${name} closing brace`).toBeGreaterThan(0); + return `${body.slice(0, end)}\n}`; +} + +function runParentPreflight(configOwner: "root" | "sandbox", parentProtected: boolean) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-parent-")); + const scriptPath = path.join(tmpDir, "run.sh"); + const source = fs.readFileSync(START_SCRIPT, "utf-8"); + const blockStart = source.indexOf( + "# A root-owned config directory is the shields-up discriminator.", + ); + const blockEnd = source.indexOf("# Migrate legacy symlink layout", blockStart); + expect(blockStart).toBeGreaterThanOrEqual(0); + expect(blockEnd).toBeGreaterThan(blockStart); + const parentOwner = parentProtected ? "root:sandbox" : "sandbox:sandbox"; + const parentMode = parentProtected ? "1775" : "755"; + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `openclaw_config_dir_owner() { printf '%s\\n' ${JSON.stringify(configOwner)}; }`, + `stat() { case "\${2:-}" in '%U:%G') printf '%s\\n' ${JSON.stringify(parentOwner)} ;; '%a') printf '%s\\n' ${JSON.stringify(parentMode)} ;; *) return 1 ;; esac; }`, + extractShellFunction(source, "openclaw_locked_parent_is_protected"), + source.slice(blockStart, blockEnd), + 'printf "startup-continued\\n"', + ].join("\n"), + { mode: 0o700 }, + ); + + try { + return spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} + +describe("OpenClaw locked parent startup preflight", () => { + it("accepts mutable config and the sticky root-owned locked posture", () => { + const mutable = runParentPreflight("sandbox", false); + expect(mutable.status, mutable.stderr).toBe(0); + expect(mutable.stdout).toContain("startup-continued"); + + const locked = runParentPreflight("root", true); + expect(locked.status, locked.stderr).toBe(0); + expect(locked.stdout).toContain("startup-continued"); + }); + + it("refuses a root-owned config root under a renameable sandbox parent", () => { + const result = runParentPreflight("root", false); + expect(result.status).toBe(1); + expect(result.stdout).not.toContain("startup-continued"); + expect(result.stderr).toContain("OPENCLAW_LOCKED_PARENT_UNPROTECTED"); + expect(result.stderr).toContain("trusted backup and recreate"); + }); +}); diff --git a/test/nemoclaw-start-plugin-refresh.test.ts b/test/nemoclaw-start-plugin-refresh.test.ts index aa27cad13c6..ae15a2f5d77 100644 --- a/test/nemoclaw-start-plugin-refresh.test.ts +++ b/test/nemoclaw-start-plugin-refresh.test.ts @@ -40,9 +40,16 @@ function extractRefreshBlock(): string { "Expected plugin-refresh + PID-tracking block between start_auto_pair and SANDBOX_WAIT_PID in scripts/nemoclaw-start.sh", ); } - return [extractShellFunction(src, "start_plugin_registry_refresh"), src.slice(start, end)].join( - "\n", - ); + return [ + extractShellFunction(src, "openclaw_load_pid_identity"), + extractShellFunction(src, "openclaw_pid_start_identity"), + extractShellFunction(src, "capture_openclaw_pid_start_identity"), + extractShellFunction(src, "openclaw_supervised_pid_is_live"), + extractShellFunction(src, "start_plugin_registry_refresh"), + extractShellFunction(src, "openclaw_supervised_aux_pid_is_live"), + extractShellFunction(src, "refresh_openclaw_supervised_child_pids"), + src.slice(start, end), + ].join("\n"); } // Drive the refresh block end-to-end with stubs for `openclaw` and the @@ -102,6 +109,7 @@ function runRefreshBlock( ` if [ "$count" -ge ${opts.gatewayReadyAfter} ]; then exit 0; else exit 1; fi`, "fi", `if [ "$1" = "plugins" ] && [ "$2" = "registry" ] && [ "$3" = "--refresh" ]; then`, + " command sleep 0.2", ` printf 'CALL=plugins registry --refresh HOME=%s STEP_DOWN_USER=%s USER=%s\\n' "$HOME" "\${STEP_DOWN_USER:-}" "$(id -un)" >> ${JSON.stringify(envLog)}`, ` cp ${JSON.stringify(registryState)} ${JSON.stringify(preRefreshState)}`, ` cat > ${JSON.stringify(registryState)} <<'REGISTRY_STATE'`, @@ -144,9 +152,16 @@ function runRefreshBlock( // Stubs for variables the extracted block references that are set // earlier in the production script. "AUTO_PAIR_PID=", + "AUTO_PAIR_PID_START_IDENTITY=", "GATEWAY_LOG_TAIL_PID=", + "GATEWAY_LOG_TAIL_PID_START_IDENTITY=", "GATEWAY_LOG_PERSIST_PID=", + "GATEWAY_LOG_PERSIST_PID_START_IDENTITY=", "GATEWAY_PID=0", + "GATEWAY_PID_START_IDENTITY=", + "GATEWAY_WATCHDOG_PID=", + "GATEWAY_WATCHDOG_PID_START_IDENTITY=", + 'gateway_control_pid_is_live() { case "$1" in ""|0|1|*[!0-9]*) return 1 ;; *) return 0 ;; esac; }', block, "# Surface PLUGIN_REFRESH_PID + tracked SANDBOX_CHILD_PIDS for the test", 'printf "PLUGIN_REFRESH_PID=%s\\n" "$PLUGIN_REFRESH_PID"', diff --git a/test/nemoclaw-start-reconcile.test.ts b/test/nemoclaw-start-reconcile.test.ts index 64f0d813951..26137f43dd0 100644 --- a/test/nemoclaw-start-reconcile.test.ts +++ b/test/nemoclaw-start-reconcile.test.ts @@ -25,6 +25,7 @@ interface RunReconcileOptions { */ gatewayRawOutput?: string; env?: Record<string, string>; + locked?: boolean; } describe("agent identity reconciliation with provider (#3175)", () => { @@ -89,7 +90,7 @@ describe("agent identity reconciliation with provider (#3175)", () => { "set -euo pipefail", "id() { echo 0; }", "chown() { return 0; }", - `stat() { if [ "$1" = "-c" ] && [ "$2" = "%U" ] && [ "$3" = ${JSON.stringify(openclawDir)} ]; then echo sandbox; return 0; fi; command stat "$@"; }`, + `stat() { if [ "$1" = "-c" ] && [ "$2" = "%U" ] && [ "$3" = ${JSON.stringify(openclawDir)} ]; then echo ${options.locked ? "root" : "sandbox"}; return 0; fi; command stat "$@"; }`, 'relax_config_for_write() { chmod 644 "$@"; }', 'lock_config_after_write() { chmod 444 "$@"; }', helperFns, @@ -162,6 +163,26 @@ describe("agent identity reconciliation with provider (#3175)", () => { expect(hash).toBe("oldhash\n"); }); + it("never rewrites the host-sealed config while shields are up", () => { + const initial = { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: [{ id: "nvidia/new-model", name: "inference/nvidia/new-model" }], + }, + }, + }, + }; + const { result, config, hash } = runReconcile(initial, { locked: true }); + + expect(result.status).toBe(0); + expect(config).toEqual(initial); + expect(hash).toBe("oldhash\n"); + expect(result.stderr).toContain("Shields are up"); + }); + it("falls back to an inference-qualified model ref when provider metadata lacks name", () => { const { result, config, hash } = runReconcile({ agents: { defaults: { model: { primary: "inference/old-model" } } }, diff --git a/test/nemoclaw-start-telegram-runtime.test.ts b/test/nemoclaw-start-telegram-runtime.test.ts index 6e9806bdcd7..6d7862c71ad 100644 --- a/test/nemoclaw-start-telegram-runtime.test.ts +++ b/test/nemoclaw-start-telegram-runtime.test.ts @@ -229,4 +229,69 @@ describe("Telegram runtime preload installation", () => { fs.rmSync(tmpDir, { recursive: true, force: true }); } }); + + it("fails closed when a mandatory preload or connect-list write fails", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-telegram-write-failure-")); + const sourcePrefix = path.join(tmpDir, "preloads") + path.sep; + const sourcePath = path.join(sourcePrefix, "telegram-diagnostics.js"); + const preloadPath = path.join(tmpDir, "telegram-diagnostics.js"); + const planPath = path.join(tmpDir, "runtime-plan.json"); + const connectPreloadsPath = path.join(tmpDir, "connect-preloads.list"); + const scriptPath = path.join(tmpDir, "run.sh"); + const preload = { + source: sourcePath, + target: preloadPath, + injectInto: ["boot", "connect"], + optional: false, + }; + const cases = [ + { failTarget: preloadPath, nodePreloads: [preload], expectPreload: false }, + { failTarget: connectPreloadsPath, nodePreloads: [preload], expectPreload: true }, + { failTarget: connectPreloadsPath, nodePreloads: [], expectPreload: false }, + ]; + fs.mkdirSync(sourcePrefix, { recursive: true }); + fs.copyFileSync(TELEGRAM_RUNTIME_PRELOAD, sourcePath); + + try { + for (const testCase of cases) { + fs.rmSync(preloadPath, { force: true }); + fs.rmSync(connectPreloadsPath, { force: true }); + fs.writeFileSync(planPath, JSON.stringify({ nodePreloads: testCase.nodePreloads })); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -uo pipefail", + `FAIL_TARGET=${JSON.stringify(testCase.failTarget)}`, + "emit_sandbox_sourced_file() {", + ' local target="$1"', + ' [ "$target" != "$FAIL_TARGET" ] || { cat >/dev/null; return 1; }', + ' cat >"$target"', + ' chmod 444 "$target"', + "}", + "NODE_OPTIONS=''", + messagingRuntimeSetupSection(src, { + planPath, + connectPreloadsPath, + sourcePrefix, + targetPrefix: tmpDir + path.sep, + }), + "rc=0", + "install_messaging_runtime_preloads || rc=$?", + 'printf "rc=%s\\n" "$rc"', + 'exit "$rc"', + ].join("\n"), + { mode: 0o700 }, + ); + + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + expect(result.status, result.stderr).toBe(1); + expect(result.stdout).toContain("rc=1"); + expect(fs.existsSync(preloadPath)).toBe(testCase.expectPreload); + expect(fs.existsSync(connectPreloadsPath)).toBe(false); + } + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); }); diff --git a/test/nemoclaw-start.test.ts b/test/nemoclaw-start.test.ts index 6878aae19d9..ca84afeb773 100644 --- a/test/nemoclaw-start.test.ts +++ b/test/nemoclaw-start.test.ts @@ -1180,7 +1180,7 @@ describe("nemoclaw-start persistent gateway log hardening", () => { scriptPath, [ "#!/usr/bin/env bash", - "set -euo pipefail", + 'set -euo pipefail\n# Identity capture is covered by supervisor suites.\ncapture_openclaw_pid_start_identity() { printf -v "$2" "%s" "test:$1"; }', persistentLogFunction(tmpDir, gatewayLog), "start_persistent_gateway_log_mirror", "sleep 0.2", diff --git a/test/nemotron-inference-fix.test.ts b/test/nemotron-inference-fix.test.ts index aa606d8fc95..d30a49bb163 100644 --- a/test/nemotron-inference-fix.test.ts +++ b/test/nemotron-inference-fix.test.ts @@ -24,6 +24,16 @@ function extractStartScriptHeredoc(src, marker) { throw new Error(`Expected ${marker} heredoc in scripts/nemoclaw-start.sh`); } +function extractShellFunction(source, name) { + const header = `${name}() {`; + const start = source.indexOf(header); + expect(start, `expected ${name} in nemoclaw-start.sh`).not.toBe(-1); + const body = source.slice(start + header.length); + const closing = body.match(/^}$/m); + expect(closing, `expected closing brace for ${name}`).not.toBeNull(); + return `${name}() {${body.slice(0, closing?.index ?? 0)}\n}`; +} + describe("NVIDIA endpoint inference fix preload (#1193, #2051, #4063)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -49,7 +59,22 @@ describe("NVIDIA endpoint inference fix preload (#1193, #2051, #4063)", () => { "set -euo pipefail", 'emit_sandbox_sourced_file() { local target="$1"; cat > "$target"; chmod 444 "$target"; }', "NODE_OPTIONS='--require /already-loaded.js'", + "NODE_USE_ENV_PROXY=0", + extractShellFunction(src, "node_options_has_require"), + extractShellFunction(src, "append_node_require_once"), block, + `_SANDBOX_SAFETY_NET=${JSON.stringify(path.join(tempDir, "safety-net.js"))}`, + `_SANDBOX_SAFETY_NET_SOURCE=${JSON.stringify(NEMOTRON_FIX_SOURCE)}`, + `_PROXY_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "proxy-fix.js"))}`, + `_PROXY_FIX_SOURCE=${JSON.stringify(NEMOTRON_FIX_SOURCE)}`, + `_CIAO_GUARD_SCRIPT=${JSON.stringify(path.join(tempDir, "ciao-guard.js"))}`, + `_CIAO_GUARD_SOURCE=${JSON.stringify(NEMOTRON_FIX_SOURCE)}`, + `_WS_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "ws-fix.js"))}`, + `_WS_FIX_SOURCE=${JSON.stringify(path.join(tempDir, "missing-ws-source.js"))}`, + `_SECCOMP_GUARD_SCRIPT=${JSON.stringify(path.join(tempDir, "seccomp-guard.js"))}`, + `_SECCOMP_GUARD_SOURCE=${JSON.stringify(NEMOTRON_FIX_SOURCE)}`, + extractShellFunction(src, "install_core_runtime_preloads"), + "install_core_runtime_preloads", "printf 'NODE_OPTIONS=%s\\n' \"$NODE_OPTIONS\"", "printf 'SCRIPT=%s\\n' \"$_NEMOTRON_FIX_SCRIPT\"", ].join("\n"); diff --git a/test/openclaw-config-guard.test.ts b/test/openclaw-config-guard.test.ts new file mode 100644 index 00000000000..6188ac4b7fe --- /dev/null +++ b/test/openclaw-config-guard.test.ts @@ -0,0 +1,1491 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +const GUARD_PATH = path.resolve("scripts/openclaw-config-guard.py"); +const fixtures: string[] = []; + +const RUN_AS_CURRENT_USER = String.raw` +import importlib.util +import hashlib +import os +import sys +import time + +guard_path, action, config_dir, failure, expected_sha256 = sys.argv[1:6] +spec = importlib.util.spec_from_file_location("nemoclaw_openclaw_config_guard", guard_path) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +identity = module.Identity( + root_uid=os.getuid(), + root_gid=os.getgid(), + sandbox_uid=os.getuid(), + sandbox_gid=os.getgid(), +) +module.os.geteuid = lambda: 0 +module._production_identity = lambda: identity +module.PRODUCTION_CONFIG_DIR = config_dir +module.JOURNAL_PATH = os.path.join(os.path.dirname(config_dir), ".nemoclaw-test", "transaction.json") +module.MUTEX_PATH = os.path.join(os.path.dirname(config_dir), ".nemoclaw-test", "mutation.lock") +module.STARTUP_READY_PATH = os.path.join(os.path.dirname(config_dir), ".nemoclaw-test", "ready.json") +module.STARTUP_CAPABILITY_PATH = os.path.join(os.path.dirname(config_dir), ".nemoclaw-test", "ready-capability.json") +module.NODE_BINARY_PATH = os.environ.get("NEMOCLAW_TEST_NODE_PATH", module.NODE_BINARY_PATH) +module.JSON5_MODULE_PATH = os.environ.get("NEMOCLAW_TEST_JSON5_PATH", module.JSON5_MODULE_PATH) +if failure in {"installed-current", "installed-not-ready", "installed-nonroot-no-cap", "installed-nonroot-not-ready", "startup-owner", "old-image-no-cap"}: + module._pid1_is_nemoclaw_start = lambda: True + module._process_start_time = lambda pid: "424242" if pid == 1 else None + module._process_namespace_inode = lambda pid: 424242 if pid == 1 else None + module._startup_process_identity_is_live = lambda start_time, namespace_inode, effective_uid=0: ( + start_time == "424242" and namespace_inode == 424242 + ) +if failure in {"installed-current", "installed-not-ready", "installed-nonroot-no-cap", "installed-nonroot-not-ready", "installed-foreign-pid1", "installed-remapped", "installed-remapped-any-live", "installed-openshell-supervised", "installed-openshell-stale-marker", "startup-owner"}: + module.INSTALLED_HELPER_PATH = guard_path +if failure == "installed-foreign-pid1": + module._pid1_is_nemoclaw_start = lambda: False +if failure in {"installed-openshell-supervised", "installed-openshell-stale-marker"}: + module._pid1_is_nemoclaw_start = lambda: False + module._openshell_supervised_nonroot_start_is_live = lambda root_uid, sandbox_uid, required_pid=None: True + module._startup_markers_absent = lambda identity: failure == "installed-openshell-supervised" +if failure == "installed-remapped": + module._pid1_is_nemoclaw_start = lambda: False + module._startup_process_identity_is_live = lambda start_time, namespace_inode, effective_uid=0: ( + start_time == "424242" and namespace_inode == 424242 + ) +if failure == "installed-remapped-any-live": + module._pid1_is_nemoclaw_start = lambda: False + module._startup_process_identity_is_live = lambda start_time, namespace_inode, effective_uid=0: ( + (start_time, namespace_inode) in { + ("424242", 424242), + ("525252", 525252), + } + ) +if failure in {"installed-not-ready", "installed-current"}: + module._pid1_effective_uid = lambda: identity.root_uid +if failure in {"installed-nonroot-no-cap", "installed-nonroot-not-ready"}: + module._pid1_effective_uid = lambda: identity.root_uid + 1 +if failure == "startup-owner": + module.os.getppid = lambda: 1 +if failure == "pair-race": + original_snapshot = module._snapshot_file + raced = False + def race_pair(opened, name): + global raced + snapshot = original_snapshot(opened, name) + if name == "openclaw.json" and not raced: + raced = True + updated = b'{"gateway":{"port":19001}}\n' + with open(os.path.join(config_dir, "openclaw.json"), "wb") as stream: + stream.write(updated) + digest = hashlib.sha256(updated).hexdigest() + with open(os.path.join(config_dir, ".config-hash"), "w", encoding="ascii") as stream: + stream.write(digest + " openclaw.json\n") + return snapshot + module._snapshot_file = race_pair +if failure.startswith("immutable"): + inode_flags = {} + flag_log = os.environ["NEMOCLAW_TEST_FLAG_LOG"] + def fake_get_flags(fd): + return inode_flags.get(os.fstat(fd).st_ino, module.FS_IMMUTABLE_FL) + def fake_set_flags(fd, flags): + inode_flags[os.fstat(fd).st_ino] = flags + with open(flag_log, "a", encoding="utf-8") as stream: + stream.write(str(flags) + "\n") + module._get_inode_flags = fake_get_flags + module._set_inode_flags = fake_set_flags +if "second-replace" in failure: + original_replace = module._replace_from_snapshot + calls = 0 + def fail_second(*args, **kwargs): + global calls + calls += 1 + if calls == 2: + raise OSError("injected second replacement failure") + return original_replace(*args, **kwargs) + module._replace_from_snapshot = fail_second +if failure == "force-install-failure": + def fail_install(*_args, **_kwargs): + raise OSError("injected canonical install failure") + module._install_stored_pair = fail_install +if failure == "kill-after-freeze": + original_freeze = module._freeze + def kill_after_freeze(*args, **kwargs): + original_freeze(*args, **kwargs) + os._exit(88) + module._freeze = kill_after_freeze +if failure == "kill-after-prepared": + def kill_before_freeze(*_args, **_kwargs): + os._exit(87) + module._freeze = kill_before_freeze +if failure == "kill-after-first-replace": + original_replace_for_kill = module._replace_from_snapshot + replace_calls = 0 + def kill_after_first_replace(*args, **kwargs): + global replace_calls + result = original_replace_for_kill(*args, **kwargs) + replace_calls += 1 + if replace_calls == 1: + os._exit(89) + return result + module._replace_from_snapshot = kill_after_first_replace +if failure == "kill-after-commit": + original_write_journal = module._write_journal + def kill_after_commit(record, identity, opened=None): + original_write_journal(record, identity, opened) + if record.get("phase") == "committed": + os._exit(90) + module._write_journal = kill_after_commit +if failure == "kill-after-visible": + original_clear_secondary = module._clear_secondary_journal + def kill_before_secondary_clear(*args, **kwargs): + if os.stat(config_dir).st_mode & 0o7777 == 0o2770: + os._exit(91) + return original_clear_secondary(*args, **kwargs) + module._clear_secondary_journal = kill_before_secondary_clear +if failure == "clear-after-visible-fails": + original_clear_secondary_for_failure = module._clear_secondary_journal + def fail_visible_secondary_clear(*args, **kwargs): + if os.stat(config_dir).st_mode & 0o7777 == 0o2770: + raise OSError("injected visible cleanup failure") + return original_clear_secondary_for_failure(*args, **kwargs) + module._clear_secondary_journal = fail_visible_secondary_clear +if failure == "second-replace-kill-rollback-visible": + original_clear_secondary_after_rollback = module._clear_secondary_journal + def kill_after_rollback_handoff(*args, **kwargs): + if os.stat(config_dir).st_mode & 0o7777 == 0o2770: + os._exit(112) + return original_clear_secondary_after_rollback(*args, **kwargs) + module._clear_secondary_journal = kill_after_rollback_handoff +if failure == "plant-journal-before-freeze": + original_freeze_for_plant = module._freeze + def plant_before_freeze(*args, **kwargs): + planted = os.path.join(config_dir, module.PERSISTENT_JOURNAL_NAME) + try: + os.symlink(os.path.join(os.path.dirname(config_dir), "outside"), planted) + except FileExistsError: + pass + return original_freeze_for_plant(*args, **kwargs) + module._freeze = plant_before_freeze +if failure == "hold-mutex": + original_open_config = module._open_config + def hold_after_mutex(path): + with open(os.environ["NEMOCLAW_TEST_READY_FILE"], "w", encoding="utf-8") as stream: + stream.write("ready\n") + time.sleep(4) + return original_open_config(path) + module._open_config = hold_after_mutex +if failure in {"kill-seal-after-freeze-parent", "kill-seal-after-freeze-config"}: + target_name = "_freeze_parent" if failure.endswith("parent") else "_freeze_config" + original_freeze_step = getattr(module, target_name) + exit_code = 102 if failure.endswith("parent") else 103 + def kill_after_freeze_step(*args, **kwargs): + original_freeze_step(*args, **kwargs) + os._exit(exit_code) + setattr(module, target_name, kill_after_freeze_step) +if failure in { + "kill-seal-after-prepared", + "kill-seal-after-applying", + "kill-seal-after-sealed-journal", + "kill-unseal-after-journal", + "kill-unseal-after-committed", +}: + original_restart_write_journal = module._write_journal + phase_exit = { + "kill-seal-after-prepared": ("prepared", 101), + "kill-seal-after-applying": ("applying", 104), + "kill-seal-after-sealed-journal": ("sealed", 106), + "kill-unseal-after-journal": ("unsealing", 108), + "kill-unseal-after-committed": ("unseal-committed", 110), + } + wanted_phase, restart_exit = phase_exit[failure] + def kill_after_restart_journal(record, identity, opened=None): + original_restart_write_journal(record, identity, opened) + if record.get("action") == "restart-seal" and record.get("phase") == wanted_phase: + os._exit(restart_exit) + module._write_journal = kill_after_restart_journal +if failure in {"kill-seal-after-first-replace", "kill-unseal-after-first-replace"}: + original_restart_replace = module._replace_from_snapshot + restart_replace_calls = 0 + restart_replace_exit = 105 if failure.startswith("kill-seal") else 109 + def kill_after_restart_replace(*args, **kwargs): + global restart_replace_calls + result = original_restart_replace(*args, **kwargs) + restart_replace_calls += 1 + if restart_replace_calls == 1: + os._exit(restart_replace_exit) + return result + module._replace_from_snapshot = kill_after_restart_replace +if failure == "kill-seal-after-visible": + original_commit_locked = module._commit_locked_dirs + def kill_after_sealed_visible(*args, **kwargs): + original_commit_locked(*args, **kwargs) + os._exit(107) + module._commit_locked_dirs = kill_after_sealed_visible +if failure == "kill-unseal-after-visible": + original_commit_mutable = module._commit_mutable_dirs + def kill_after_unseal_visible(*args, **kwargs): + original_commit_mutable(*args, **kwargs) + os._exit(111) + module._commit_mutable_dirs = kill_after_unseal_visible +arguments = [action, "--config-dir", config_dir] +if expected_sha256: + arguments.extend(["--expected-config-sha256", expected_sha256]) +if failure == "startup-owner": + arguments.append("--startup-owner") +raise SystemExit(module.main(arguments)) +`; + +type GuardLine = { + type: "issue" | "result"; + action?: string; + status?: string; + code?: string; + path?: string; + detail?: string; + chattrApplied?: boolean; + configSha256?: string; + recovery?: string; + originalLocked?: boolean; +}; + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", `'\\''`)}'`; +} + +function trustedNodePath(configDir: string): string { + return path.join(path.dirname(configDir), ".nemoclaw-test-node"); +} + +function fixture() { + const created = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-config-guard-")); + const root = fs.realpathSync(created); + fixtures.push(root); + const configDir = path.join(root, ".openclaw"); + const configPath = path.join(configDir, "openclaw.json"); + const hashPath = path.join(configDir, ".config-hash"); + const nodePath = trustedNodePath(configDir); + const configBytes = Buffer.from('{"gateway":{"port":18789}}\n'); + fs.mkdirSync(configDir); + fs.writeFileSync(nodePath, `#!/bin/sh\nexec ${shellQuote(process.execPath)} "$@"\n`, { + mode: 0o500, + }); + fs.writeFileSync(configPath, configBytes, { mode: 0o660 }); + fs.writeFileSync( + hashPath, + `${createHash("sha256").update(configBytes).digest("hex")} openclaw.json\n`, + { mode: 0o660 }, + ); + fs.chmodSync(configPath, 0o660); + fs.chmodSync(hashPath, 0o660); + fs.chmodSync(configDir, 0o2770); + fs.chmodSync(root, 0o755); + return { root, configDir, configPath, hashPath }; +} + +type GuardAction = + | "preflight" + | "preflight-restart" + | "lock" + | "unlock" + | "seal-restart" + | "unseal-restart" + | "revoke-startup-ready" + | "publish-startup-ready" + | "write-config" + | "recover"; + +function runGuard( + action: GuardAction, + configDir: string, + failure = "none", + env: NodeJS.ProcessEnv = {}, + expectedSha256 = "", + input?: string | Buffer, +) { + const result = spawnSync( + "python3", + ["-c", RUN_AS_CURRENT_USER, GUARD_PATH, action, configDir, failure, expectedSha256], + { + encoding: "utf-8", + timeout: 15_000, + env: { + ...process.env, + NEMOCLAW_TEST_NODE_PATH: trustedNodePath(configDir), + NEMOCLAW_TEST_JSON5_PATH: path.resolve("nemoclaw/node_modules/json5"), + ...env, + }, + input, + maxBuffer: 32 * 1024 * 1024, + }, + ); + const lines = result.stdout + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as GuardLine); + return { ...result, lines }; +} + +function mode(filePath: string): number { + return fs.lstatSync(filePath).mode & 0o7777; +} + +function setUserXattr(filePath: string, value: string): boolean { + return ( + spawnSync( + "python3", + [ + "-c", + "import os,sys; os.setxattr(sys.argv[1], 'user.nemoclaw-test', sys.argv[2].encode())", + filePath, + value, + ], + { encoding: "utf-8" }, + ).status === 0 + ); +} + +function getUserXattr(filePath: string): string { + const result = spawnSync( + "python3", + [ + "-c", + "import os,sys; print(os.getxattr(sys.argv[1], 'user.nemoclaw-test').decode())", + filePath, + ], + { encoding: "utf-8" }, + ); + expect(result.status).toBe(0); + return result.stdout.trim(); +} + +afterEach(() => { + for (const root of fixtures.splice(0)) { + try { + fs.chmodSync(root, 0o700); + const configDir = path.join(root, ".openclaw"); + for (const existingConfigDir of fs.existsSync(configDir) && + !fs.lstatSync(configDir).isSymbolicLink() + ? [configDir] + : []) { + fs.chmodSync(existingConfigDir, 0o700); + for (const name of ["openclaw.json", ".config-hash"]) { + const filePath = path.join(existingConfigDir, name); + for (const existingFilePath of fs.existsSync(filePath) && fs.lstatSync(filePath).isFile() + ? [filePath] + : []) { + fs.chmodSync(existingFilePath, 0o600); + } + } + } + } catch { + // Best effort before recursive fixture cleanup. + } + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("openclaw-config-guard", () => { + it("keeps an exact locked parent and pair unchanged across idempotent relock", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const first = runGuard("lock", configDir); + expect(first.status, JSON.stringify(first.lines)).toBe(0); + const configInode = fs.statSync(configPath).ino; + const hashInode = fs.statSync(hashPath).ino; + const configBytes = fs.readFileSync(configPath); + const hashBytes = fs.readFileSync(hashPath); + expect(mode(root)).toBe(0o1775); + + const second = runGuard("lock", configDir); + expect(second.status, JSON.stringify(second.lines)).toBe(0); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + expect(fs.statSync(configPath).ino).toBe(configInode); + expect(fs.statSync(hashPath).ino).toBe(hashInode); + expect(fs.readFileSync(configPath)).toEqual(configBytes); + expect(fs.readFileSync(hashPath)).toEqual(hashBytes); + }); + + it("fresh-replaces both files on lock and unlock while preserving bytes, times, and xattrs", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const preservedTime = new Date("2025-01-02T03:04:05.000Z"); + fs.utimesSync(configPath, preservedTime, preservedTime); + fs.utimesSync(hashPath, preservedTime, preservedTime); + const hasXattrs = setUserXattr(configPath, "trusted-metadata"); + const initialConfig = fs.readFileSync(configPath); + const initialHash = fs.readFileSync(hashPath); + const initialConfigStat = fs.statSync(configPath); + const initialHashStat = fs.statSync(hashPath); + const staleConfigFd = fs.openSync(configPath, "r+"); + const staleHashFd = fs.openSync(hashPath, "r+"); + + try { + const locked = runGuard("lock", configDir); + expect(locked.status).toBe(0); + expect(locked.lines.at(-1)).toMatchObject({ + type: "result", + action: "lock", + status: "ok", + chattrApplied: false, + }); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + expect(fs.statSync(configPath).ino).not.toBe(initialConfigStat.ino); + expect(fs.statSync(hashPath).ino).not.toBe(initialHashStat.ino); + expect(fs.statSync(configPath).mtimeMs).toBe(initialConfigStat.mtimeMs); + expect(fs.statSync(hashPath).mtimeMs).toBe(initialHashStat.mtimeMs); + for (const expectedXattr of hasXattrs ? ["trusted-metadata"] : []) { + expect(getUserXattr(configPath)).toBe(expectedXattr); + } + + fs.writeSync(staleConfigFd, Buffer.from("MUTATED"), 0, 7, 0); + fs.writeSync(staleHashFd, Buffer.from("MUTATED"), 0, 7, 0); + fs.fsyncSync(staleConfigFd); + fs.fsyncSync(staleHashFd); + expect(fs.readFileSync(configPath)).toEqual(initialConfig); + expect(fs.readFileSync(hashPath)).toEqual(initialHash); + + const lockedConfigInode = fs.statSync(configPath).ino; + const lockedHashInode = fs.statSync(hashPath).ino; + const unlocked = runGuard("unlock", configDir); + expect(unlocked.status).toBe(0); + expect(mode(root)).toBe(0o755); + expect(mode(configDir)).toBe(0o2770); + expect(mode(configPath)).toBe(0o660); + expect(mode(hashPath)).toBe(0o660); + expect(fs.statSync(configPath).ino).not.toBe(lockedConfigInode); + expect(fs.statSync(hashPath).ino).not.toBe(lockedHashInode); + expect(fs.readFileSync(configPath)).toEqual(initialConfig); + expect(fs.readFileSync(hashPath)).toEqual(initialHash); + for (const expectedXattr of hasXattrs ? ["trusted-metadata"] : []) { + expect(getUserXattr(configPath)).toBe(expectedXattr); + } + } finally { + fs.closeSync(staleConfigFd); + fs.closeSync(staleHashFd); + } + }); + + it("rejects external symlink, hardlink, and special-file substitutions", () => { + for (const attack of ["symlink", "hardlink", "fifo"] as const) { + const { root, configDir, configPath, hashPath } = fixture(); + const external = path.join(root, "external.json"); + fs.writeFileSync(external, "outside\n"); + fs.rmSync(configPath); + const arrangeAttack = { + symlink: () => fs.symlinkSync(external, configPath), + hardlink: () => fs.linkSync(external, configPath), + fifo: () => expect(spawnSync("mkfifo", [configPath]).status).toBe(0), + } satisfies Record<typeof attack, () => void>; + arrangeAttack[attack](); + + const beforeHash = fs.readFileSync(hashPath); + const result = runGuard("preflight", configDir); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "issue", + code: attack === "hardlink" ? "hardlinked-config-file" : "unsafe-config-file", + path: configPath, + }), + ]), + ); + expect(fs.readFileSync(external, "utf-8")).toBe("outside\n"); + expect(fs.readFileSync(hashPath)).toEqual(beforeHash); + } + }); + + it("fail-closes a rename-swapped config namespace and leaves the external tree untouched", () => { + const { root, configDir } = fixture(); + const realConfig = path.join(root, "real-openclaw"); + fs.renameSync(configDir, realConfig); + fs.symlinkSync(realConfig, configDir); + const externalConfig = path.join(realConfig, "openclaw.json"); + const before = fs.readFileSync(externalConfig); + + const result = runGuard("lock", configDir); + + expect(result.status).toBe(0); + expect(fs.readFileSync(externalConfig)).toEqual(before); + expect(fs.lstatSync(configDir).isDirectory()).toBe(true); + expect(mode(configDir)).toBe(0o755); + expect(mode(path.join(configDir, "openclaw.json"))).toBe(0o444); + }); + + it("canonicalizes a stale mutable hash while strict preflight rejects a bad record path", () => { + const mismatch = fixture(); + const mismatchBytes = fs.readFileSync(mismatch.configPath); + fs.writeFileSync(mismatch.hashPath, `${"0".repeat(64)} openclaw.json\n`, { mode: 0o660 }); + + const mismatched = runGuard("lock", mismatch.configDir); + + expect(mismatched.status).toBe(0); + expect(fs.readFileSync(mismatch.hashPath, "utf-8")).toBe( + `${createHash("sha256").update(mismatchBytes).digest("hex")} openclaw.json\n`, + ); + expect(fs.readFileSync(mismatch.configPath)).toEqual(mismatchBytes); + expect(mode(mismatch.configDir)).toBe(0o755); + + const wrongPath = fixture(); + const digest = createHash("sha256").update(fs.readFileSync(wrongPath.configPath)).digest("hex"); + fs.writeFileSync(wrongPath.hashPath, `${digest} ../openclaw.json\n`); + const nonCanonical = runGuard("preflight", wrongPath.configDir); + expect(nonCanonical.status).toBe(1); + expect(nonCanonical.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "invalid-config-hash-path" }), + ]), + ); + + const absolute = fixture(); + const absoluteDigest = createHash("sha256") + .update(fs.readFileSync(absolute.configPath)) + .digest("hex"); + fs.writeFileSync(absolute.hashPath, `${absoluteDigest} ${absolute.configPath}\n`, { + mode: 0o660, + }); + expect(runGuard("preflight", absolute.configDir).status).toBe(0); + }); + + it("retries config and hash as one pair when a writer interleaves their capture", () => { + const { configDir, configPath, hashPath } = fixture(); + + const result = runGuard("lock", configDir, "pair-race"); + + expect(result.status).toBe(0); + const updated = Buffer.from('{"gateway":{"port":19001}}\n'); + expect(fs.readFileSync(configPath)).toEqual(updated); + expect(fs.readFileSync(hashPath, "utf-8")).toBe( + `${createHash("sha256").update(updated).digest("hex")} openclaw.json\n`, + ); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + }); + + it("restart preflight accepts a stable parseable config with a stale mutable hash", () => { + const { configDir, hashPath } = fixture(); + fs.writeFileSync(hashPath, `${"0".repeat(64)} openclaw.json\n`); + fs.chmodSync(hashPath, 0o660); + + expect(runGuard("preflight-restart", configDir).status).toBe(0); + const strict = runGuard("preflight", configDir); + expect(strict.status).toBe(1); + expect(strict.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "config-hash-mismatch" }), + ]), + ); + }); + + it("rolls a failed unlock back to the complete locked parent, config, and file posture", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const configBytes = fs.readFileSync(configPath); + const hashBytes = fs.readFileSync(hashPath); + expect(runGuard("lock", configDir).status).toBe(0); + + const result = runGuard("unlock", configDir, "second-replace"); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "transition-failed" }), + ]), + ); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + expect(fs.readFileSync(configPath)).toEqual(configBytes); + expect(fs.readFileSync(hashPath)).toEqual(hashBytes); + }); + + it("clears descriptor-bound immutable flags for replacement and restores them on rollback", () => { + const { root, configDir } = fixture(); + const flagLog = path.join(root, "inode-flags.log"); + fs.writeFileSync(flagLog, ""); + + const locked = runGuard("lock", configDir, "immutable", { + NEMOCLAW_TEST_FLAG_LOG: flagLog, + }); + expect(locked.status).toBe(0); + expect(fs.readFileSync(flagLog, "utf-8").trim().split("\n")).toContain("0"); + + fs.writeFileSync(flagLog, ""); + const failedUnlock = runGuard("unlock", configDir, "immutable-second-replace", { + NEMOCLAW_TEST_FLAG_LOG: flagLog, + }); + expect(failedUnlock.status).toBe(1); + const appliedFlags = fs.readFileSync(flagLog, "utf-8").trim().split("\n").map(Number); + expect(appliedFlags).toContain(0); + expect(appliedFlags).toContain(0x10); + expect(mode(configDir)).toBe(0o755); + }); + + it("enforces the exact production path and bounded config artifact sizes", () => { + const { configDir, hashPath } = fixture(); + const noPathOverride = RUN_AS_CURRENT_USER.replace( + "module.PRODUCTION_CONFIG_DIR = config_dir\n", + "", + ); + const wrongPath = spawnSync( + "python3", + ["-c", noPathOverride, GUARD_PATH, "preflight", configDir, "none", ""], + { encoding: "utf-8", timeout: 15_000 }, + ); + expect(wrongPath.status).toBe(1); + expect(wrongPath.stdout).toContain('"code": "invalid-config-path"'); + + fs.writeFileSync(hashPath, Buffer.alloc(64 * 1024 + 1, 0x61)); + const oversized = runGuard("preflight", configDir); + expect(oversized.status).toBe(1); + expect(oversized.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "issue", + code: "config-file-too-large", + path: hashPath, + }), + ]), + ); + }); + + it("CAS-writes a fresh mutable config/hash pair and revokes stale descriptors", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const oldConfig = fs.readFileSync(configPath); + const expected = createHash("sha256").update(oldConfig).digest("hex"); + const replacement = Buffer.from( + `${JSON.stringify({ gateway: { port: 19001 }, agents: { defaults: { model: "nvidia/test" } } }, null, 2)}\n`, + ); + const replacementDigest = createHash("sha256").update(replacement).digest("hex"); + const oldConfigInode = fs.statSync(configPath).ino; + const oldHashInode = fs.statSync(hashPath).ino; + const staleConfigFd = fs.openSync(configPath, "r+"); + const staleHashFd = fs.openSync(hashPath, "r+"); + + try { + const result = runGuard("write-config", configDir, "none", {}, expected, replacement); + + expect(result.status, JSON.stringify(result.lines)).toBe(0); + expect(result.lines.at(-1)).toMatchObject({ + type: "result", + action: "write-config", + status: "ok", + chattrApplied: false, + configSha256: replacementDigest, + }); + expect(mode(root)).toBe(0o755); + expect(mode(configDir)).toBe(0o2770); + expect(mode(configPath)).toBe(0o660); + expect(mode(hashPath)).toBe(0o660); + expect(fs.statSync(configPath).ino).not.toBe(oldConfigInode); + expect(fs.statSync(hashPath).ino).not.toBe(oldHashInode); + expect(fs.readFileSync(configPath)).toEqual(replacement); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${replacementDigest} openclaw.json\n`); + + fs.writeSync(staleConfigFd, Buffer.from("STALE!!"), 0, 7, 0); + fs.writeSync(staleHashFd, Buffer.from("STALE!!"), 0, 7, 0); + fs.fsyncSync(staleConfigFd); + fs.fsyncSync(staleHashFd); + expect(fs.readFileSync(configPath)).toEqual(replacement); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${replacementDigest} openclaw.json\n`); + } finally { + fs.closeSync(staleConfigFd); + fs.closeSync(staleHashFd); + } + }); + + it("safely replaces a sandbox-precreated persistent journal symlink", () => { + const { root, configDir, configPath } = fixture(); + const original = fs.readFileSync(configPath); + const expected = createHash("sha256").update(original).digest("hex"); + const outside = path.join(root, "outside-journal-target"); + const persistentJournal = path.join(configDir, ".nemoclaw-config-transaction.json"); + fs.writeFileSync(outside, "do-not-touch\n"); + fs.symlinkSync(outside, persistentJournal); + + const result = runGuard( + "write-config", + configDir, + "none", + {}, + expected, + Buffer.from('{"gateway":{"port":19001}}\n'), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(outside, "utf-8")).toBe("do-not-touch\n"); + expect(fs.existsSync(persistentJournal)).toBe(false); + }); + + it("refuses stale CAS and locked posture without changing either file", () => { + const staleCas = fixture(); + const beforeConfig = fs.readFileSync(staleCas.configPath); + const beforeHash = fs.readFileSync(staleCas.hashPath); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + + const stale = runGuard( + "write-config", + staleCas.configDir, + "none", + {}, + "0".repeat(64), + replacement, + ); + + expect(stale.status).toBe(1); + expect(stale.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "config-cas-mismatch" }), + ]), + ); + expect(fs.readFileSync(staleCas.configPath)).toEqual(beforeConfig); + expect(fs.readFileSync(staleCas.hashPath)).toEqual(beforeHash); + + const locked = fixture(); + expect(runGuard("lock", locked.configDir).status).toBe(0); + const lockedConfig = fs.readFileSync(locked.configPath); + const lockedHash = fs.readFileSync(locked.hashPath); + const lockedDigest = createHash("sha256").update(lockedConfig).digest("hex"); + const refused = runGuard( + "write-config", + locked.configDir, + "none", + {}, + lockedDigest, + replacement, + ); + expect(refused.status).toBe(1); + expect(refused.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "config-not-mutable" }), + ]), + ); + expect(fs.readFileSync(locked.configPath)).toEqual(lockedConfig); + expect(fs.readFileSync(locked.hashPath)).toEqual(lockedHash); + expect(mode(locked.configPath)).toBe(0o444); + }); + + it("rolls back both mutable files when the second write-config replacement fails", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const beforeConfig = fs.readFileSync(configPath); + const beforeHash = fs.readFileSync(hashPath); + const expected = createHash("sha256").update(beforeConfig).digest("hex"); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + + const result = runGuard("write-config", configDir, "second-replace", {}, expected, replacement); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "write-config-failed" }), + ]), + ); + expect(fs.readFileSync(configPath)).toEqual(beforeConfig); + expect(fs.readFileSync(hashPath)).toEqual(beforeHash); + expect(mode(root)).toBe(0o755); + expect(mode(configDir)).toBe(0o2770); + expect(mode(configPath)).toBe(0o660); + expect(mode(hashPath)).toBe(0o660); + }); + + it.each([ + ["kill-after-freeze", 88, "orphan-freeze-restored", false], + ["kill-after-first-replace", 89, "ambiguous-replay-locked", true], + ] as const)("recovers or fail-closes after %s", (failure, exitCode, recovery, locked) => { + const { root, configDir, configPath, hashPath } = fixture(); + const originalConfig = fs.readFileSync(configPath); + const originalHash = fs.readFileSync(hashPath); + const expected = createHash("sha256").update(originalConfig).digest("hex"); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + const journalPath = path.join(root, ".nemoclaw-test", "transaction.json"); + + const interrupted = runGuard("write-config", configDir, failure, {}, expected, replacement); + + expect(interrupted.status).toBe(exitCode); + expect(fs.existsSync(journalPath)).toBe(true); + expect(mode(configDir)).toBe(0o700); + // Simulate container recreation: /etc-style secondary state is gone while + // the persistent /sandbox tree and its root-frozen discriminator survive. + fs.rmSync(journalPath, { force: true }); + for (const _ambiguousReplacement of failure === "kill-after-first-replace" ? [true] : []) { + const refused = runGuard("preflight", configDir); + expect(refused.status).toBe(1); + expect(refused.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "recovery-required" }), + ]), + ); + } + + const recovered = runGuard("recover", configDir); + expect(recovered.status).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ + type: "result", + action: "recover", + status: "ok", + recovery, + }); + expect(fs.existsSync(journalPath)).toBe(false); + expect(fs.readFileSync(configPath)).toEqual(locked ? replacement : originalConfig); + const replacementDigest = createHash("sha256").update(replacement).digest("hex"); + const expectedHash = locked + ? Buffer.from(`${replacementDigest} openclaw.json\n`) + : originalHash; + expect(fs.readFileSync(hashPath)).toEqual(expectedHash); + expect(mode(root)).toBe(locked ? 0o1775 : 0o755); + expect(mode(configDir)).toBe(locked ? 0o755 : 0o2770); + expect(mode(configPath)).toBe(locked ? 0o444 : 0o660); + expect(mode(hashPath)).toBe(locked ? 0o444 : 0o660); + }); + + it("preserves later gateway bytes and a stale hash from the prepared phase", () => { + const { configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + const originalHash = fs.readFileSync(hashPath); + const expected = createHash("sha256").update(original).digest("hex"); + const intended = Buffer.from('{"gateway":{"port":19001}}\n'); + + const interrupted = runGuard( + "write-config", + configDir, + "kill-after-prepared", + {}, + expected, + intended, + ); + expect(interrupted.status).toBe(87); + expect(mode(configDir)).toBe(0o2770); + + const gatewayBytes = Buffer.from('{"gateway":{"port":19002},"runtime":true}\n'); + fs.writeFileSync(configPath, gatewayBytes); + fs.chmodSync(configPath, 0o660); + // Deliberately leave .config-hash stale; mutable gateway writes are allowed + // to refresh that non-anchor later in startup. + const recovered = runGuard("recover", configDir); + expect(recovered.status).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ + recovery: "prepared-preserved", + configSha256: createHash("sha256").update(gatewayBytes).digest("hex"), + }); + expect(fs.readFileSync(configPath)).toEqual(gatewayBytes); + expect(fs.readFileSync(hashPath)).toEqual(originalHash); + }); + + it("uses the frozen posture discriminator when both journals are lost and hash is stale", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + const expected = createHash("sha256").update(original).digest("hex"); + const staleHash = Buffer.from(`${"0".repeat(64)} openclaw.json\n`); + fs.writeFileSync(hashPath, staleHash); + fs.chmodSync(hashPath, 0o660); + + const interrupted = runGuard( + "write-config", + configDir, + "kill-after-freeze", + {}, + expected, + Buffer.from('{"gateway":{"port":19001}}\n'), + ); + expect(interrupted.status).toBe(88); + fs.rmSync(path.join(root, ".nemoclaw-test", "transaction.json"), { force: true }); + fs.rmSync(path.join(configDir, ".nemoclaw-config-transaction.json"), { force: true }); + + const recovered = runGuard("recover", configDir); + expect(recovered.status).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ recovery: "orphan-freeze-restored" }); + expect(fs.readFileSync(configPath)).toEqual(original); + expect(fs.readFileSync(hashPath)).toEqual(staleHash); + expect(mode(configDir)).toBe(0o2770); + }); + + it("finishes the committed replacement after interruption before mutable-directory commit", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const originalConfig = fs.readFileSync(configPath); + const expected = createHash("sha256").update(originalConfig).digest("hex"); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + const replacementDigest = createHash("sha256").update(replacement).digest("hex"); + const journalPath = path.join(root, ".nemoclaw-test", "transaction.json"); + + const interrupted = runGuard( + "write-config", + configDir, + "kill-after-commit", + {}, + expected, + replacement, + ); + expect(interrupted.status, JSON.stringify(interrupted.lines)).toBe(90); + expect(fs.existsSync(journalPath)).toBe(true); + expect(mode(configDir)).toBe(0o700); + fs.rmSync(journalPath, { force: true }); + + const recovered = runGuard("recover", configDir); + expect(recovered.status).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ + type: "result", + action: "recover", + status: "ok", + recovery: "ambiguous-replay-locked", + configSha256: replacementDigest, + }); + expect(fs.existsSync(journalPath)).toBe(false); + expect(fs.readFileSync(configPath)).toEqual(replacement); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${replacementDigest} openclaw.json\n`); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + }); + + it("preserves a later gateway write with stale hash when committed cleanup was interrupted", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + const expected = createHash("sha256").update(original).digest("hex"); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + const secondaryJournal = path.join(root, ".nemoclaw-test", "transaction.json"); + + const interrupted = runGuard( + "write-config", + configDir, + "kill-after-visible", + {}, + expected, + replacement, + ); + expect(interrupted.status).toBe(91); + expect(mode(configDir)).toBe(0o2770); + + const gatewayBytes = Buffer.from('{"gateway":{"port":19002},"runtime":true}\n'); + const gatewayDigest = createHash("sha256").update(gatewayBytes).digest("hex"); + const staleHash = fs.readFileSync(hashPath); + fs.writeFileSync(configPath, gatewayBytes, { mode: 0o660 }); + fs.chmodSync(configPath, 0o660); + fs.rmSync(secondaryJournal, { force: true }); + + const recovered = runGuard("recover", configDir); + expect(recovered.status).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ + type: "result", + action: "recover", + status: "ok", + recovery: "none", + originalLocked: false, + }); + expect(fs.readFileSync(configPath)).toEqual(gatewayBytes); + expect(fs.readFileSync(hashPath)).toEqual(staleHash); + }); + + it("bounds write-config stdin and deliberately rejects JSON5-only syntax", () => { + const oversized = fixture(); + const oversizedConfig = fs.readFileSync(oversized.configPath); + const expected = createHash("sha256").update(oversizedConfig).digest("hex"); + const tooLarge = runGuard( + "write-config", + oversized.configDir, + "none", + {}, + expected, + Buffer.alloc(16 * 1024 * 1024 + 1, 0x20), + ); + expect(tooLarge.status).toBe(1); + expect(tooLarge.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "config-file-too-large" }), + ]), + ); + expect(fs.readFileSync(oversized.configPath)).toEqual(oversizedConfig); + + const json5 = fixture(); + const json5Config = fs.readFileSync(json5.configPath); + const json5Expected = createHash("sha256").update(json5Config).digest("hex"); + const invalid = runGuard( + "write-config", + json5.configDir, + "none", + {}, + json5Expected, + "{ // JSON5 comment\n gateway: { port: 19001 },\n}\n", + ); + expect(invalid.status).toBe(1); + expect(invalid.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "issue", + code: "invalid-config-json", + detail: expect.stringContaining("strict JSON"), + }), + ]), + ); + expect(fs.readFileSync(json5.configPath)).toEqual(json5Config); + }); + + it("seals and unseals mutable restart config with stale hash and stale descriptors", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const config = fs.readFileSync(configPath); + const digest = createHash("sha256").update(config).digest("hex"); + fs.writeFileSync(hashPath, `${"0".repeat(64)} openclaw.json\n`, { mode: 0o660 }); + const oldConfigInode = fs.statSync(configPath).ino; + const oldHashInode = fs.statSync(hashPath).ino; + const staleConfig = fs.openSync(configPath, "r+"); + const staleHash = fs.openSync(hashPath, "r+"); + + try { + const sealed = runGuard("seal-restart", configDir); + expect(sealed.status, JSON.stringify(sealed.lines)).toBe(0); + expect(sealed.lines.at(-1)).toMatchObject({ + action: "seal-restart", + originalLocked: false, + configSha256: digest, + }); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + expect(fs.statSync(configPath).ino).not.toBe(oldConfigInode); + expect(fs.statSync(hashPath).ino).not.toBe(oldHashInode); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${digest} openclaw.json\n`); + + fs.writeSync(staleConfig, Buffer.from("STALE!!"), 0, 7, 0); + fs.writeSync(staleHash, Buffer.from("STALE!!"), 0, 7, 0); + expect(fs.readFileSync(configPath)).toEqual(config); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${digest} openclaw.json\n`); + + const sealedConfigInode = fs.statSync(configPath).ino; + const sealedHashInode = fs.statSync(hashPath).ino; + const unsealed = runGuard("unseal-restart", configDir); + expect(unsealed.status, JSON.stringify(unsealed.lines)).toBe(0); + expect(unsealed.lines.at(-1)).toMatchObject({ + action: "unseal-restart", + originalLocked: false, + }); + expect(mode(root)).toBe(0o755); + expect(mode(configDir)).toBe(0o2770); + expect(mode(configPath)).toBe(0o660); + expect(mode(hashPath)).toBe(0o660); + expect(fs.statSync(configPath).ino).not.toBe(sealedConfigInode); + expect(fs.statSync(hashPath).ino).not.toBe(sealedHashInode); + expect(fs.existsSync(path.join(configDir, ".nemoclaw-config-transaction.json"))).toBe(false); + } finally { + fs.closeSync(staleConfig); + fs.closeSync(staleHash); + } + }); + + it("records shields-locked restart state without replacing or weakening the host seal", () => { + const { root, configDir, configPath, hashPath } = fixture(); + expect(runGuard("lock", configDir).status).toBe(0); + const configInode = fs.statSync(configPath).ino; + const hashInode = fs.statSync(hashPath).ino; + + const sealed = runGuard("seal-restart", configDir); + expect(sealed.status).toBe(0); + expect(sealed.lines.at(-1)).toMatchObject({ originalLocked: true }); + expect(fs.statSync(configPath).ino).toBe(configInode); + expect(fs.statSync(hashPath).ino).toBe(hashInode); + expect(mode(root)).toBe(0o1775); + expect(mode(configDir)).toBe(0o755); + + const unsealed = runGuard("unseal-restart", configDir); + expect(unsealed.status).toBe(0); + expect(unsealed.lines.at(-1)).toMatchObject({ originalLocked: true }); + expect(fs.statSync(configPath).ino).toBe(configInode); + expect(fs.statSync(hashPath).ino).toBe(hashInode); + expect(mode(configPath)).toBe(0o444); + }); + + it("uses JSON5 validation for restart while locked posture still enforces hash coherence", () => { + const json5 = fixture(); + const bytes = Buffer.from("{\n // comment\n gateway: { port: 18789, },\n}\n"); + fs.writeFileSync(json5.configPath, bytes, { mode: 0o660 }); + fs.writeFileSync(json5.hashPath, `${"0".repeat(64)} openclaw.json\n`, { mode: 0o660 }); + expect(runGuard("preflight-restart", json5.configDir).status).toBe(0); + expect(runGuard("seal-restart", json5.configDir).status).toBe(0); + expect(runGuard("unseal-restart", json5.configDir).status).toBe(0); + + const locked = fixture(); + expect(runGuard("lock", locked.configDir).status).toBe(0); + fs.chmodSync(locked.hashPath, 0o644); + fs.writeFileSync(locked.hashPath, `${"0".repeat(64)} openclaw.json\n`); + fs.chmodSync(locked.hashPath, 0o444); + const rejected = runGuard("preflight-restart", locked.configDir); + expect(rejected.status).toBe(1); + expect(rejected.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "config-hash-mismatch" }), + ]), + ); + }); + + it.each([ + ["kill-seal-after-prepared", 101], + ["kill-seal-after-freeze-parent", 102], + ["kill-seal-after-freeze-config", 103], + ["kill-seal-after-applying", 104], + ["kill-seal-after-first-replace", 105], + ["kill-seal-after-sealed-journal", 106], + ["kill-seal-after-visible", 107], + ] as const)("recovers an interrupted restart seal at %s", (failure, exitCode) => { + const { root, configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + const interrupted = runGuard("seal-restart", configDir, failure); + expect(interrupted.status).toBe(exitCode); + + fs.rmSync(path.join(root, ".nemoclaw-test", "transaction.json"), { force: true }); + const recovered = runGuard("recover", configDir); + expect(recovered.status, `${failure}: ${JSON.stringify(recovered.lines)}`).toBe(0); + expect(fs.readFileSync(configPath)).toEqual(original); + const recoveredMode = mode(configDir); + expect([0o2770, 0o755]).toContain(recoveredMode); + const recoveredLocked = recoveredMode === 0o755; + expect(mode(configPath)).toBe(recoveredLocked ? 0o444 : 0o660); + expect(mode(hashPath)).toBe(recoveredLocked ? 0o444 : 0o660); + expect(recovered.lines.at(-1)).toMatchObject({ originalLocked: recoveredLocked }); + }); + + it.each([ + ["kill-unseal-after-journal", 108], + ["kill-unseal-after-first-replace", 109], + ["kill-unseal-after-committed", 110], + ["kill-unseal-after-visible", 111], + ] as const)("recovers an interrupted restart unseal at %s", (failure, exitCode) => { + const { root, configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + expect(runGuard("seal-restart", configDir).status).toBe(0); + const interrupted = runGuard("unseal-restart", configDir, failure); + expect(interrupted.status).toBe(exitCode); + + fs.rmSync(path.join(root, ".nemoclaw-test", "transaction.json"), { force: true }); + const recovered = runGuard("recover", configDir); + expect(recovered.status, `${failure}: ${JSON.stringify(recovered.lines)}`).toBe(0); + expect(fs.readFileSync(configPath)).toEqual(original); + const recoveredMode = mode(configDir); + expect([0o2770, 0o755]).toContain(recoveredMode); + const recoveredLocked = recoveredMode === 0o755; + expect(mode(configPath)).toBe(recoveredLocked ? 0o444 : 0o660); + expect(mode(hashPath)).toBe(recoveredLocked ? 0o444 : 0o660); + expect(recovered.lines.at(-1)).toMatchObject({ originalLocked: recoveredLocked }); + }); + + it("quarantines planted journal entry types and a last-moment swap without vetoing lock", () => { + for (const attack of ["symlink", "file", "directory"] as const) { + const current = fixture(); + const reserved = path.join(current.configDir, ".nemoclaw-config-transaction.json"); + const outside = path.join(current.root, `outside-${attack}`); + fs.writeFileSync(outside, "outside\n"); + const plantJournal = { + symlink: () => fs.symlinkSync(outside, reserved), + file: () => fs.writeFileSync(reserved, "planted\n", { mode: 0o644 }), + directory: () => fs.mkdirSync(reserved), + } satisfies Record<typeof attack, () => void>; + plantJournal[attack](); + expect(runGuard("lock", current.configDir).status).toBe(0); + expect(fs.readFileSync(outside, "utf-8")).toBe("outside\n"); + expect(mode(current.configPath)).toBe(0o444); + + for (const _directoryAttack of attack === "directory" ? [true] : []) { + expect(runGuard("unlock", current.configDir).status).toBe(0); + const retained = fs + .readdirSync(current.configDir) + .find((name) => name.startsWith(".nemoclaw-untrusted-journal-")); + expect(retained).toBeDefined(); + fs.renameSync(path.join(current.configDir, retained!), reserved); + expect(runGuard("lock", current.configDir).status).toBe(0); + } + } + + const swapped = fixture(); + fs.writeFileSync(path.join(swapped.root, "outside"), "outside\n"); + expect(runGuard("lock", swapped.configDir, "plant-journal-before-freeze").status).toBe(0); + expect(mode(swapped.configPath)).toBe(0o444); + }); + + it("fresh-severs stale descriptors even when canonical install raises", () => { + const { configDir, configPath, hashPath } = fixture(); + const config = fs.readFileSync(configPath); + const digest = createHash("sha256").update(config).digest("hex"); + const configFd = fs.openSync(configPath, "r+"); + const hashFd = fs.openSync(hashPath, "r+"); + try { + const result = runGuard("lock", configDir, "force-install-failure"); + expect(result.status).toBe(1); + expect(mode(configPath)).toBe(0o444); + expect(mode(hashPath)).toBe(0o444); + fs.writeSync(configFd, Buffer.from("STALE!!"), 0, 7, 0); + fs.writeSync(hashFd, Buffer.from("STALE!!"), 0, 7, 0); + expect(fs.readFileSync(configPath)).toEqual(config); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(`${digest} openclaw.json\n`); + } finally { + fs.closeSync(configFd); + fs.closeSync(hashFd); + } + }); + + it("does not roll back after mutable handoff when journal cleanup fails", () => { + const { root, configDir, configPath } = fixture(); + const original = fs.readFileSync(configPath); + const expected = createHash("sha256").update(original).digest("hex"); + const replacement = Buffer.from('{"gateway":{"port":19001}}\n'); + const result = runGuard( + "write-config", + configDir, + "clear-after-visible-fails", + {}, + expected, + replacement, + ); + expect(result.status).toBe(0); + expect(fs.readFileSync(configPath)).toEqual(replacement); + expect(mode(configDir)).toBe(0o2770); + expect(fs.existsSync(path.join(configDir, ".nemoclaw-config-transaction.json"))).toBe(false); + expect(fs.existsSync(path.join(root, ".nemoclaw-test", "transaction.json"))).toBe(true); + expect(runGuard("recover", configDir).status).toBe(0); + expect(fs.readFileSync(configPath)).toEqual(replacement); + }); + + it("preserves gateway writes after a crash in failed-write rollback handoff", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const original = fs.readFileSync(configPath); + const originalHash = fs.readFileSync(hashPath); + const expected = createHash("sha256").update(original).digest("hex"); + const intended = Buffer.from('{"gateway":{"port":19001}}\n'); + + const interrupted = runGuard( + "write-config", + configDir, + "second-replace-kill-rollback-visible", + {}, + expected, + intended, + ); + expect(interrupted.status).toBe(112); + expect(fs.readFileSync(configPath)).toEqual(original); + expect(fs.readFileSync(hashPath)).toEqual(originalHash); + expect(mode(configDir)).toBe(0o2770); + expect(fs.existsSync(path.join(configDir, ".nemoclaw-config-transaction.json"))).toBe(false); + expect(fs.existsSync(path.join(root, ".nemoclaw-test", "transaction.json"))).toBe(true); + + const gatewayBytes = Buffer.from('{"gateway":{"port":19002},"runtime":true}\n'); + fs.writeFileSync(configPath, gatewayBytes, { mode: 0o660 }); + fs.chmodSync(configPath, 0o660); + // The gateway is allowed to leave the mutable non-anchor hash stale. + const recovered = runGuard("recover", configDir); + expect(recovered.status, JSON.stringify(recovered.lines)).toBe(0); + expect(recovered.lines.at(-1)).toMatchObject({ + recovery: "prepared-preserved", + configSha256: createHash("sha256").update(gatewayBytes).digest("hex"), + originalLocked: false, + }); + expect(fs.readFileSync(configPath)).toEqual(gatewayBytes); + expect(fs.readFileSync(hashPath)).toEqual(originalHash); + expect(mode(configDir)).toBe(0o2770); + expect(fs.existsSync(path.join(root, ".nemoclaw-test", "transaction.json"))).toBe(false); + }); + + it("serializes mutations, rejects a live owner, and reclaims a stale owner record", () => { + const { root, configDir, configPath } = fixture(); + const ready = path.join(root, "mutex-ready"); + const child = spawn( + "python3", + ["-c", RUN_AS_CURRENT_USER, GUARD_PATH, "recover", configDir, "hold-mutex", ""], + { + env: { + ...process.env, + NEMOCLAW_TEST_NODE_PATH: trustedNodePath(configDir), + NEMOCLAW_TEST_JSON5_PATH: path.resolve("nemoclaw/node_modules/json5"), + NEMOCLAW_TEST_READY_FILE: ready, + }, + stdio: "ignore", + }, + ); + try { + for (let attempt = 0; attempt < 80 && !fs.existsSync(ready); attempt += 1) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25); + } + expect(fs.existsSync(ready)).toBe(true); + const blocked = runGuard("lock", configDir); + expect(blocked.status).toBe(1); + expect(blocked.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "mutation-in-progress" }), + ]), + ); + } finally { + child.kill("SIGKILL"); + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100); + } + const recoveredOwner = runGuard("lock", configDir); + expect(recoveredOwner.status, JSON.stringify(recoveredOwner.lines)).toBe(0); + expect(mode(configPath)).toBe(0o444); + }); + + it("enforces the installed-helper startup lease while retaining explicit old-image fallback", () => { + const foreignPid1 = fixture(); + const foreignBlocked = runGuard("lock", foreignPid1.configDir, "installed-foreign-pid1"); + expect(foreignBlocked.status).toBe(1); + expect(foreignBlocked.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "startup-not-ready" }), + ]), + ); + + const beforeRevoke = fixture(); + const blocked = runGuard("lock", beforeRevoke.configDir, "installed-not-ready"); + expect(blocked.status).toBe(1); + expect(blocked.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "startup-not-ready" }), + ]), + ); + + const oldImage = fixture(); + expect(runGuard("lock", oldImage.configDir, "old-image-no-cap").status).toBe(0); + + const current = fixture(); + const revoked = runGuard("revoke-startup-ready", current.configDir, "startup-owner"); + expect(revoked.status, JSON.stringify(revoked.lines)).toBe(0); + expect(runGuard("lock", current.configDir, "installed-current").status).toBe(1); + expect(runGuard("publish-startup-ready", current.configDir, "startup-owner").status).toBe(0); + expect(runGuard("lock", current.configDir, "installed-current").status).toBe(0); + expect(runGuard("lock", current.configDir, "installed-remapped").status).toBe(0); + + const readyPath = path.join(current.root, ".nemoclaw-test", "ready.json"); + fs.writeFileSync( + readyPath, + `${JSON.stringify({ + pid: 1, + pidNamespaceInode: 525252, + pidStartTime: "525252", + version: 2, + })}\n`, + ); + fs.chmodSync(readyPath, 0o600); + const splitLease = runGuard("lock", current.configDir, "installed-remapped-any-live"); + expect(splitLease.status).toBe(1); + expect(splitLease.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "startup-not-ready" }), + ]), + ); + }); + + it("allows only authenticated no-capability non-root startup postures", () => { + const degraded = fixture(); + expect(runGuard("lock", degraded.configDir, "installed-nonroot-no-cap").status).toBe(0); + + const optedIn = fixture(); + const revoked = runGuard("revoke-startup-ready", optedIn.configDir, "startup-owner"); + expect(revoked.status, JSON.stringify(revoked.lines)).toBe(0); + const blocked = runGuard("lock", optedIn.configDir, "installed-nonroot-not-ready"); + expect(blocked.status).toBe(1); + expect(blocked.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "startup-not-ready" }), + ]), + ); + + const supervised = fixture(); + expect(runGuard("lock", supervised.configDir, "installed-openshell-supervised").status).toBe(0); + + const staleMarker = fixture(); + const staleBlocked = runGuard( + "lock", + staleMarker.configDir, + "installed-openshell-stale-marker", + ); + expect(staleBlocked.status).toBe(1); + expect(staleBlocked.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "startup-not-ready" }), + ]), + ); + }); + + it("keeps restart journal bounded near the maximum config size", () => { + const { root, configDir, configPath, hashPath } = fixture(); + const max = 16 * 1024 * 1024; + const prefix = Buffer.from('{"padding":"'); + const suffix = Buffer.from('"}\n'); + const large = Buffer.concat([ + prefix, + Buffer.alloc(max - prefix.length - suffix.length, 0x61), + suffix, + ]); + const digest = createHash("sha256").update(large).digest("hex"); + fs.writeFileSync(configPath, large, { mode: 0o660 }); + fs.writeFileSync(hashPath, `${digest} openclaw.json\n`, { mode: 0o660 }); + + const sealed = runGuard("seal-restart", configDir); + expect(sealed.status, JSON.stringify(sealed.lines)).toBe(0); + const persistent = path.join(configDir, ".nemoclaw-config-transaction.json"); + expect(fs.statSync(persistent).size).toBeLessThan(48 * 1024 * 1024); + expect(fs.statSync(path.join(root, ".nemoclaw-test", "transaction.json")).size).toBeLessThan( + 48 * 1024 * 1024, + ); + expect(runGuard("unseal-restart", configDir).status).toBe(0); + }, 20_000); + + it("runs from source injected through python stdin", () => { + const { root, configDir } = fixture(); + const maliciousCwd = path.join(root, "attacker-cwd"); + const importMarker = path.join(root, "attacker-secrets-imported"); + fs.mkdirSync(maliciousCwd); + fs.writeFileSync( + path.join(maliciousCwd, "secrets.py"), + `from pathlib import Path\nPath(${JSON.stringify(importMarker)}).write_text("imported")\nraise RuntimeError("attacker module imported")\n`, + ); + const source = fs + .readFileSync(GUARD_PATH, "utf-8") + .replace(/\nif __name__ == "__main__":\n raise SystemExit\(main\(\)\)\s*$/, ""); + const injected = + `${source}\n` + + String.raw` +os.geteuid = lambda: 0 +PRODUCTION_CONFIG_DIR = ${JSON.stringify("__CONFIG_DIR__")} +JOURNAL_PATH = ${JSON.stringify("__JOURNAL_PATH__")} +MUTEX_PATH = ${JSON.stringify("__MUTEX_PATH__")} +NODE_BINARY_PATH = ${JSON.stringify(trustedNodePath(configDir))} +JSON5_MODULE_PATH = ${JSON.stringify(path.resolve("nemoclaw/node_modules/json5"))} +_production_identity = lambda: Identity( + root_uid=os.getuid(), root_gid=os.getgid(), + sandbox_uid=os.getuid(), sandbox_gid=os.getgid(), +) +raise SystemExit(main()) +` + .replace("__CONFIG_DIR__", configDir) + .replace( + "__JOURNAL_PATH__", + path.join(path.dirname(configDir), ".injected-journal", "transaction.json"), + ) + .replace( + "__MUTEX_PATH__", + path.join(path.dirname(configDir), ".injected-journal", "mutation.lock"), + ); + + const result = spawnSync("python3", ["-I", "-", "preflight", "--config-dir", configDir], { + input: injected, + encoding: "utf-8", + timeout: 15_000, + cwd: maliciousCwd, + env: { ...process.env, PYTHONPATH: maliciousCwd }, + }); + + expect(result.status).toBe(0); + expect(fs.existsSync(importMarker)).toBe(false); + expect(JSON.parse(result.stdout.trim())).toMatchObject({ + type: "result", + action: "preflight", + status: "ok", + }); + }); +}); diff --git a/test/package-contract/cli/command-registry.test.ts b/test/package-contract/cli/command-registry.test.ts index 904303583f5..9ecb1ec7a66 100644 --- a/test/package-contract/cli/command-registry.test.ts +++ b/test/package-contract/cli/command-registry.test.ts @@ -56,13 +56,13 @@ describe("command-registry", () => { }); describe("sandboxCommands()", () => { - it("should return exactly 49 entries", () => { - // 43 visible + 6 hidden (shields×3 + config get/set/rotate-token). - // 43 visible includes the sessions group (root + list + reset + delete + + it("should return exactly 50 entries", () => { + // 44 visible + 6 hidden (shields×3 + config get/set/rotate-token). + // 44 visible includes the sessions group (root + list + reset + delete + // export), the agents quartet (add + apply + delete + list), the // singular `agent` passthrough that forwards to `openclaw agent`, and // the download + upload host-side openshell wrappers. - expect(sandboxCommands()).toHaveLength(49); + expect(sandboxCommands()).toHaveLength(50); }); it("every entry has scope sandbox", () => { @@ -218,9 +218,9 @@ describe("command-registry", () => { }); describe("sandboxActionTokens()", () => { - it("returns exactly 29 unique action tokens including empty string", () => { + it("returns exactly 30 unique action tokens including empty string", () => { const tokens = sandboxActionTokens(); - expect(tokens).toHaveLength(29); + expect(tokens).toHaveLength(30); // Must contain every first-level sandbox action plus the empty default action. const expected = new Set([ "agent", @@ -249,6 +249,7 @@ describe("command-registry", () => { "shields", "config", "channels", + "gateway", "gateway-token", "upload", "", diff --git a/test/package-contract/cli/public-argv-translation.test.ts b/test/package-contract/cli/public-argv-translation.test.ts index 2cd2c6a6e08..e6b075ebc64 100644 --- a/test/package-contract/cli/public-argv-translation.test.ts +++ b/test/package-contract/cli/public-argv-translation.test.ts @@ -225,6 +225,11 @@ describe("translatePublicSandboxArgv", () => { "sandbox:snapshot:restore", ["alpha", "latest"], ); + expectNative( + translatePublicSandboxArgv("alpha", "gateway", ["restart", "--quiet"]), + "sandbox:gateway:restart", + ["alpha", "--quiet"], + ); expectNative( translatePublicSandboxArgv("alpha", "skill", ["remove", "my-skill"]), "sandbox:skill:remove", diff --git a/test/process-recovery-custom-agent.test.ts b/test/process-recovery-custom-agent.test.ts new file mode 100644 index 00000000000..1d3c972d3fa --- /dev/null +++ b/test/process-recovery-custom-agent.test.ts @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const { checkAndRecoverSandboxProcesses } = requireSource( + "../src/lib/actions/sandbox/process-recovery.ts", +) as typeof import("../src/lib/actions/sandbox/process-recovery.js"); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function getSandboxExecShellCommand(rawArgs: unknown): string { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + return String(args.at(-1) ?? ""); +} + +function restoreEnvValue(name: string, previous: string | undefined): void { + previous === undefined ? delete process.env[name] : (process.env[name] = previous); +} + +type SpawnMockResult = { + status: number; + stdout: string; + stderr: string; +}; + +function openshellExecResult(rawArgs: unknown, recovered: boolean): SpawnMockResult { + const shellCommand = getSandboxExecShellCommand(rawArgs); + const status = shellCommand.includes("HTTP_CODE=$(curl") + ? recovered + ? "RUNNING" + : "STOPPED" + : ""; + return { + status: 0, + stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${status}\n`, + stderr: "", + }; +} + +function sshExecResult( + rawArgs: unknown, + sshCommands: string[], + currentRecovered: boolean, + setRecovered: (value: boolean) => void, +): SpawnMockResult { + const sshCommand = getSandboxExecShellCommand(rawArgs); + const isHealthProbe = sshCommand.includes("HTTP_CODE=$(curl"); + const launchRecovered = sshCommand.includes('"$AGENT_BIN" gateway run --port 19000'); + const nextRecovered = isHealthProbe ? currentRecovered : launchRecovered; + sshCommands.push(sshCommand); + setRecovered(nextRecovered); + return { + status: 0, + stdout: isHealthProbe + ? currentRecovered + ? "RUNNING" + : "STOPPED" + : launchRecovered + ? "GATEWAY_PID=5150" + : "", + stderr: "", + }; +} + +function spawnResultForCommand( + command: unknown, + rawArgs: unknown, + sshCommands: string[], + recovered: boolean, + setRecovered: (value: boolean) => void, +): SpawnMockResult { + return String(command).endsWith("openshell") + ? openshellExecResult(rawArgs, recovered) + : command === "ssh" + ? sshExecResult(rawArgs, sshCommands, recovered, setRecovered) + : { status: 1, stdout: "", stderr: "" }; +} + +function withFakeOpenshellBinary<T>(fn: () => T): T { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); + const bin = path.join(dir, "openshell"); + const previous = process.env.NEMOCLAW_OPENSHELL_BIN; + fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.NEMOCLAW_OPENSHELL_BIN = bin; + try { + return fn(); + } finally { + restoreEnvValue("NEMOCLAW_OPENSHELL_BIN", previous); + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { + it("retains SSH health-probe compatibility for an explicitly loaded custom gateway agent", () => { + const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.ts"); + const agentRuntime = requireSource("../src/lib/agent/runtime.ts"); + const registry = requireSource("../src/lib/state/registry.ts"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.ts"); + const childProcess = requireSource("node:child_process"); + const sshCommands: string[] = []; + + vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ + status: 0, + output: "Host openshell-custom-box\n HostName 127.0.0.1\n", + } as never); + vi.spyOn(childProcess, "spawnSync").mockImplementation((command: unknown, rawArgs: unknown) => { + const sshCommand = getSandboxExecShellCommand(rawArgs); + sshCommands.push(...(command === "ssh" ? [sshCommand] : [])); + return ( + String(command).endsWith("openshell") + ? { status: 1, stdout: "", stderr: "sandbox exec unavailable" } + : command === "ssh" + ? { status: 0, stdout: "RUNNING\n", stderr: "" } + : { status: 1, stdout: "", stderr: "" } + ) as never; + }); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "custom-agent", + displayName: "Custom Agent", + binary_path: "/usr/local/bin/custom-agent", + gateway_command: "custom-agent gateway run", + forwardPort: 19000, + healthProbe: { url: "http://127.0.0.1:19000/health", port: 19000 }, + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "custom-box", + agent: "custom-agent", + dashboardPort: 19000, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: `SANDBOX BIND PORT PID STATUS +custom-box 127.0.0.1 19000 12345 running`, + }); + + expect( + withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("custom-box", { quiet: true })), + ).toEqual({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + }); + expect(sshCommands).toHaveLength(1); + expect(sshCommands[0]).toContain("HTTP_CODE=$(curl"); + expect(sshCommands[0]).not.toContain("gateway run"); + }); + + it("recovers a stopped custom gateway agent over SSH fallback", () => { + const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.ts"); + const agentRuntime = requireSource("../src/lib/agent/runtime.ts"); + const registry = requireSource("../src/lib/state/registry.ts"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.ts"); + const childProcess = requireSource("node:child_process"); + const runningForward = `SANDBOX BIND PORT PID STATUS +custom-box 127.0.0.1 19000 12345 running`; + const sshCommands: string[] = []; + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; + let recovered = false; + let healthProbeCalls = 0; + + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "2"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "0"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + + try { + vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ + status: 0, + output: "Host openshell-custom-box\n HostName 127.0.0.1\n", + } as never); + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (command: unknown, rawArgs: unknown) => { + healthProbeCalls += Number( + String(command).endsWith("openshell") && + getSandboxExecShellCommand(rawArgs).includes("HTTP_CODE=$(curl"), + ); + const setRecovered = (value: boolean): void => { + recovered = value; + }; + return spawnResultForCommand( + command, + rawArgs, + sshCommands, + recovered, + setRecovered, + ) as never; + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "custom-agent", + displayName: "Custom Agent", + binary_path: "/usr/local/bin/custom-agent", + gateway_command: "custom-agent gateway run", + forwardPort: 19000, + healthProbe: { url: "http://127.0.0.1:19000/health", port: 19000 }, + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "custom-box", + agent: "custom-agent", + dashboardPort: 19000, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: runningForward, + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + + expect( + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("custom-box", { quiet: true }), + ), + ).toEqual({ + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: true, + }); + expect(sshCommands.some((command) => command.includes('"$AGENT_BIN" gateway run'))).toBe( + true, + ); + expect(healthProbeCalls).toBe(2); + expect(recovered).toBe(true); + } finally { + restoreEnvValue("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", previousWaitSeconds); + restoreEnvValue("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", previousPollInterval); + restoreEnvValue("NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS", previousSettleSeconds); + } + }); + + it("fails closed when a persisted non-OpenClaw manifest cannot be loaded", () => { + const agentRuntime = requireSource("../src/lib/agent/runtime.ts"); + const registry = requireSource("../src/lib/state/registry.ts"); + const childProcess = requireSource("node:child_process"); + const commands: string[] = []; + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); + + vi.spyOn(childProcess, "spawnSync").mockImplementation((command: unknown, rawArgs: unknown) => { + commands.push(`${String(command)} ${getSandboxExecShellCommand(rawArgs)}`); + return { + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSTOPPED\n", + stderr: "", + } as never; + }); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "custom-box", + agent: "missing-custom-agent", + dashboardPort: 19000, + }); + + expect( + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("custom-box", { quiet: false }), + ), + ).toEqual({ + checked: true, + wasRunning: false, + recovered: false, + forwardRecovered: false, + }); + + expect(commands.join("\n")).not.toContain("openclaw gateway run"); + expect(commands.some((command) => command.startsWith("ssh "))).toBe(false); + const errorOutput = errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(errorOutput).toContain("unsupported agent"); + expect(errorOutput).toContain("missing-custom-agent agent definition could not be loaded"); + expect(errorOutput).toContain("nemoclaw 'custom-box' recover"); + expect(errorOutput).not.toContain("nemoclaw 'custom-box' gateway restart"); + expect(errorOutput).toContain("nemoclaw 'custom-box' rebuild --yes"); + expect(errorOutput).not.toContain("nohup"); + const logOutput = logSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(logOutput).toContain("missing-custom-agent gateway is not running"); + expect(logOutput).not.toContain("OpenClaw gateway"); + }); +}); diff --git a/test/process-recovery-forward-failure.test.ts b/test/process-recovery-forward-failure.test.ts new file mode 100644 index 00000000000..a9d16571469 --- /dev/null +++ b/test/process-recovery-forward-failure.test.ts @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const { checkAndRecoverSandboxProcesses } = requireSource( + "../src/lib/actions/sandbox/process-recovery.ts", +) as typeof import("../src/lib/actions/sandbox/process-recovery.js"); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function withFakeOpenshellBinary<T>(fn: () => T): T { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); + const bin = path.join(dir, "openshell"); + const previous = process.env.NEMOCLAW_OPENSHELL_BIN; + const restoreEnv = + previous === undefined + ? () => { + delete process.env.NEMOCLAW_OPENSHELL_BIN; + } + : () => { + process.env.NEMOCLAW_OPENSHELL_BIN = previous; + }; + fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.NEMOCLAW_OPENSHELL_BIN = bin; + try { + return fn(); + } finally { + restoreEnv(); + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +function compactTeamsMessagingPlan(port = "3978") { + return { + schemaVersion: 1, + sandboxName: "beta", + agent: "openclaw", + workflow: "onboard", + disabledChannels: [], + networkPolicy: { + presets: ["teams"], + entries: [ + { + channelId: "teams", + presetName: "teams", + policyKeys: ["teams"], + source: "manifest", + }, + ], + }, + channels: [ + { + channelId: "teams", + active: true, + configured: true, + disabled: false, + inputs: [ + { inputId: "allowedUsers", value: "00000000-0000-0000-0000-000000000001" }, + { inputId: "appId", value: "test-teams-app-id" }, + { inputId: "clientSecret", credentialAvailable: true }, + { inputId: "requireMention", value: "1" }, + { inputId: "tenantId", value: "test-teams-tenant-id" }, + { inputId: "webhookPort", value: port }, + ], + }, + ], + credentialBindings: [], + }; +} + +describe("checkAndRecoverSandboxProcesses primary forward failure", () => { + it("reports failure when a messaging forward cannot recover even if the primary is healthy", () => { + const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.ts"); + const agentRuntime = requireSource("../src/lib/agent/runtime.ts"); + const registry = requireSource("../src/lib/state/registry.ts"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.ts"); + const childProcess = requireSource("node:child_process"); + + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "beta", + agent: "openclaw", + dashboardPort: 18789, + messaging: { schemaVersion: 1, plan: compactTeamsMessagingPlan() }, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockImplementation( + (port: unknown) => Number(port) === 18789, + ); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: `SANDBOX BIND PORT PID STATUS +beta 127.0.0.1 18789 12345 running`, + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockImplementation((rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + return { status: args[0] === "forward" && args[1] === "start" ? 1 : 0 } as never; + }); + + expect( + withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true })), + ).toEqual({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the messaging webhook host forward could not be re-established", + }); + }); + + it("reports failure when the primary forward cannot recover even if secondary forwards recover", () => { + const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.ts"); + const agentRuntime = requireSource("../src/lib/agent/runtime.ts"); + const registry = requireSource("../src/lib/state/registry.ts"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.ts"); + const childProcess = requireSource("node:child_process"); + let teamsForwardStarted = false; + + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "beta", + agent: "openclaw", + dashboardPort: 18789, + messaging: { schemaVersion: 1, plan: compactTeamsMessagingPlan() }, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(false); + vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation(() => ({ + status: 0, + output: teamsForwardStarted + ? `SANDBOX BIND PORT PID STATUS +beta 127.0.0.1 3978 12346 running` + : `SANDBOX BIND PORT PID STATUS +beta 127.0.0.1 18789 12345 dead`, + })); + const runOpenshell = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockImplementation((rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + const isForwardStart = args[0] === "forward" && args[1] === "start"; + const startsTeamsForward = isForwardStart && args.includes("3978"); + teamsForwardStarted = teamsForwardStarted || startsTeamsForward; + return { status: isForwardStart && args.includes("18789") ? 1 : 0 } as never; + }); + + expect( + withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true })), + ).toEqual({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the primary dashboard/API host forward could not be re-established", + }); + expect(teamsForwardStarted).toBe(true); + expect(runOpenshell).toHaveBeenCalledWith( + ["forward", "start", "--background", "3978", "beta"], + { ignoreError: true }, + ); + }); +}); diff --git a/test/process-recovery-managed-controller.test.ts b/test/process-recovery-managed-controller.test.ts new file mode 100644 index 00000000000..133f342c42c --- /dev/null +++ b/test/process-recovery-managed-controller.test.ts @@ -0,0 +1,241 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const { checkAndRecoverSandboxProcesses } = requireSource( + "../src/lib/actions/sandbox/process-recovery.ts", +) as typeof import("../src/lib/actions/sandbox/process-recovery.js"); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function getSandboxExecShellCommand(rawArgs: unknown): string { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + const payload = String(args.at(-1) ?? ""); + const match = payload.match(/printf '%s' '([A-Za-z0-9+\/=]+)' \| base64 -d \| sh/); + return match ? Buffer.from(match[1], "base64").toString("utf8") : payload; +} + +function withFakeOpenshellBinary<T>(fn: () => T): T { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); + const bin = path.join(dir, "openshell"); + const previous = process.env.NEMOCLAW_OPENSHELL_BIN; + fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.NEMOCLAW_OPENSHELL_BIN = bin; + try { + return fn(); + } finally { + previous === undefined + ? delete process.env.NEMOCLAW_OPENSHELL_BIN + : (process.env.NEMOCLAW_OPENSHELL_BIN = previous); + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +describe("managed gateway recovery controller", () => { + const recoveredGateway = { + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: true, + }; + const unrecoveredGateway = { + checked: true, + wasRunning: false, + recovered: false, + forwardRecovered: false, + }; + const successfulControl = { status: 0, stdout: "GATEWAY_PID=123\n", stderr: "" }; + const successfulProbe = { status: 0, stdout: "ALREADY_RUNNING\n", stderr: "" }; + + it.each([ + { + label: "PID 1 supervisor", + recoverResults: [successfulControl], + expectedResult: recoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "OpenShell managed controller", + recoverResults: [successfulControl], + managedProbeResult: successfulProbe, + expectedResult: recoveredGateway, + expectedActions: ["recover", "probe"], + settleSeconds: "1", + }, + { + label: "two transient controller races followed by authenticated recovery", + recoverResults: [ + { status: 1, stdout: "", stderr: "SUPERVISOR_UNAVAILABLE" }, + { status: 1, stdout: "", stderr: "SUPERVISOR_BUSY" }, + successfulControl, + ], + expectedResult: recoveredGateway, + expectedActions: ["recover", "recover", "recover"], + settleSeconds: "0", + }, + { + label: "persistent exact unavailable controller result", + recoverResults: [{ status: 1, stdout: "", stderr: "SUPERVISOR_UNAVAILABLE" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover", "recover", "recover"], + settleSeconds: "0", + }, + { + label: "busy controller marker on stdout", + recoverResults: [{ status: 1, stdout: "SUPERVISOR_BUSY", stderr: "" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "OpenShell managed controller wedge", + recoverResults: [successfulControl], + managedProbeResult: { status: 1, stdout: "", stderr: "GATEWAY_HEALTH_TIMEOUT" }, + expectedResult: unrecoveredGateway, + expectedActions: ["recover", "probe"], + settleSeconds: "1", + }, + { + label: "non-exact unavailable marker", + recoverResults: [{ status: 1, stdout: "", stderr: "prefix SUPERVISOR_UNAVAILABLE suffix" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "unavailable marker with another error line", + recoverResults: [{ status: 1, stdout: "", stderr: "SUPERVISOR_UNAVAILABLE\nGATEWAY_FAILED" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "unavailable marker with a nonstandard status", + recoverResults: [{ status: 2, stdout: "", stderr: "SUPERVISOR_UNAVAILABLE" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "unsafe controller directory refusal", + recoverResults: [{ status: 1, stdout: "", stderr: "SUPERVISOR_UNSAFE_CONTROL_DIR" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "invalid controller status refusal", + recoverResults: [{ status: 1, stdout: "", stderr: "SUPERVISOR_INVALID_STATUS" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "controller rebuild requirement", + recoverResults: [{ status: 127, stdout: "", stderr: "SUPERVISOR_REBUILD_REQUIRED" }], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + { + label: "missing controller result", + recoverResults: [null], + expectedResult: unrecoveredGateway, + expectedActions: ["recover"], + settleSeconds: "0", + }, + ])("waits for $label recovery before declaring success", ({ + recoverResults, + expectedResult, + expectedActions, + managedProbeResult, + settleSeconds, + }) => { + const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); + const agentRuntime = requireSource("../src/lib/agent/runtime.js"); + const registry = requireSource("../src/lib/state/registry.js"); + const childProcess = requireSource("node:child_process"); + const runningForward = `SANDBOX BIND PORT PID STATUS +beta 127.0.0.1 18789 12345 running`; + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; + let recoveryActionCalls = 0; + const requestGatewaySupervisorAction = vi.fn( + (_sandboxName: string, action: "restart" | "recover" | "probe") => { + const isProbe = action === "probe"; + const result = isProbe + ? (managedProbeResult ?? successfulProbe) + : recoverResults[Math.min(recoveryActionCalls, recoverResults.length - 1)]; + recoveryActionCalls += Number(!isProbe); + return result; + }, + ); + let healthProbeCalls = 0; + + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "2"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "0"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = settleSeconds; + + try { + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (_command: unknown, rawArgs: unknown) => { + const isHealthProbe = getSandboxExecShellCommand(rawArgs).includes("HTTP_CODE=$(curl"); + healthProbeCalls += Number(isHealthProbe); + return ( + isHealthProbe + ? { + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSTOPPED\n", + stderr: "", + } + : { status: 0, stdout: "", stderr: "" } + ) as never; + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "beta", + agent: "openclaw", + dashboardPort: 18789, + }); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: runningForward, + }); + + const result = withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("beta", { + quiet: true, + requestGatewaySupervisorAction, + }), + ); + expect(result).toEqual(expectedResult); + expect(requestGatewaySupervisorAction.mock.calls).toEqual( + expectedActions.map((action) => ["beta", action]), + ); + expect(healthProbeCalls).toBe(1); + } finally { + previousWaitSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = previousWaitSeconds); + previousPollInterval === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = previousPollInterval); + previousSettleSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = previousSettleSeconds); + } + }); +}); diff --git a/test/process-recovery-primitives.test.ts b/test/process-recovery-primitives.test.ts new file mode 100644 index 00000000000..f0fbad62100 --- /dev/null +++ b/test/process-recovery-primitives.test.ts @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +const requireSource = createRequire(import.meta.url); +const { + classifyForwardHealthWithReachability, + classifySandboxForwardHealth, + executeSandboxExecCommand, + resolveSandboxDashboardPort, +} = requireSource( + "../src/lib/actions/sandbox/process-recovery.ts", +) as typeof import("../src/lib/actions/sandbox/process-recovery.js"); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function withFakeOpenshellBinary<T>(fn: () => T): T { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); + const bin = path.join(dir, "openshell"); + const previous = process.env.NEMOCLAW_OPENSHELL_BIN; + fs.writeFileSync(bin, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + process.env.NEMOCLAW_OPENSHELL_BIN = bin; + try { + return fn(); + } finally { + previous === undefined + ? delete process.env.NEMOCLAW_OPENSHELL_BIN + : (process.env.NEMOCLAW_OPENSHELL_BIN = previous); + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +describe("resolveSandboxDashboardPort", () => { + it("uses the recorded OpenClaw dashboard port for multi-sandbox recovery", () => { + expect( + resolveSandboxDashboardPort("beta", { + getSessionAgent: () => null, + getSandbox: () => ({ name: "beta", dashboardPort: 18790 }), + }), + ).toBe(18790); + }); + + it("falls back to the default OpenClaw dashboard port when registry metadata is absent", () => { + expect( + resolveSandboxDashboardPort("legacy", { + getSessionAgent: () => null, + getSandbox: () => null, + }), + ).toBe(18789); + }); + + it("keeps non-OpenClaw agents on their declared forward port", () => { + expect( + resolveSandboxDashboardPort("hermes-box", { + getSessionAgent: () => ({ forwardPort: 8642 }), + getSandbox: () => ({ name: "hermes-box", dashboardPort: 18790 }), + }), + ).toBe(8642); + }); + + it("does not invent a dashboard port for terminal agents without declared forwards", () => { + expect( + resolveSandboxDashboardPort("terminal-box", { + getSessionAgent: () => ({ runtime: { kind: "terminal" } }), + getSandbox: () => ({ name: "terminal-box", dashboardPort: 18790 }), + }), + ).toBe(18790); + }); + + it("ignores invalid agent forward ports and falls back to registry metadata", () => { + expect( + resolveSandboxDashboardPort("beta", { + getSessionAgent: () => ({ forwardPort: 0 }), + getSandbox: () => ({ name: "beta", dashboardPort: 18790 }), + }), + ).toBe(18790); + }); +}); + +describe("classifySandboxForwardHealth", () => { + it("returns true for a running forward owned by the target sandbox", () => { + expect( + classifySandboxForwardHealth( + [{ sandboxName: "beta", port: "18790", status: "running" }], + "beta", + "18790", + ), + ).toBe(true); + }); + + it("returns occupied when another sandbox owns the expected port", () => { + expect( + classifySandboxForwardHealth( + [{ sandboxName: "alpha", port: "18790", status: "running" }], + "beta", + "18790", + ), + ).toBe("occupied"); + }); + + it("returns false for a missing forward", () => { + expect(classifySandboxForwardHealth([], "beta", "18790")).toBe(false); + }); + + it("returns false for a non-running forward owned by the target sandbox", () => { + expect( + classifySandboxForwardHealth( + [{ sandboxName: "beta", port: "18790", status: "dead" }], + "beta", + "18790", + ), + ).toBe(false); + }); + + it("finds a live target entry after a stale duplicate for the same port", () => { + expect( + classifySandboxForwardHealth( + [ + { sandboxName: "beta", port: "18790", status: "dead" }, + { sandboxName: "beta", port: "18790", status: "running" }, + ], + "beta", + "18790", + ), + ).toBe(true); + }); + + it("returns occupied when a foreign live entry conflicts with the live target", () => { + expect( + classifySandboxForwardHealth( + [ + { sandboxName: "beta", port: "18790", status: "running" }, + { sandboxName: "alpha", port: "18790", status: "running" }, + ], + "beta", + "18790", + ), + ).toBe("occupied"); + }); + + it("ignores a stale foreign entry when the target owns the live forward", () => { + expect( + classifySandboxForwardHealth( + [ + { sandboxName: "alpha", port: "18790", status: "dead" }, + { sandboxName: "beta", port: "18790", status: "running" }, + ], + "beta", + "18790", + ), + ).toBe(true); + }); +}); + +describe("classifyForwardHealthWithReachability", () => { + it("does not trust an arbitrary local listener for a non-running owned entry", () => { + let probed = false; + const result = classifyForwardHealthWithReachability( + [{ sandboxName: "beta", port: "18790", status: "dead" }], + "beta", + "18790", + () => { + probed = true; + return true; + }, + ); + + expect(result).toBe(false); + expect(probed).toBe(false); + }); + + it("does not accept reachability when the forward list entry is missing", () => { + expect(classifyForwardHealthWithReachability([], "beta", "18790", () => true)).toBe(false); + }); + + it("returns false when forward list says dead and the port does not answer", () => { + expect( + classifyForwardHealthWithReachability( + [{ sandboxName: "beta", port: "18790", status: "dead" }], + "beta", + "18790", + () => false, + ), + ).toBe(false); + }); + + it("returns false when an owned running row no longer answers", () => { + let probed = false; + const result = classifyForwardHealthWithReachability( + [{ sandboxName: "beta", port: "18790", status: "running" }], + "beta", + "18790", + () => { + probed = true; + return false; + }, + ); + expect(result).toBe(false); + expect(probed).toBe(true); + }); + + it("returns occupied even when the port answers if another sandbox owns it", () => { + // Reachability says yes, but the entry belongs to a different sandbox — + // we must not silently take over someone else's forward. + expect( + classifyForwardHealthWithReachability( + [{ sandboxName: "alpha", port: "18790", status: "running" }], + "beta", + "18790", + () => true, + ), + ).toBe("occupied"); + }); + + it("requires a live duplicate after a stale target entry to answer", () => { + let probed = false; + const result = classifyForwardHealthWithReachability( + [ + { sandboxName: "beta", port: "18790", status: "dead" }, + { sandboxName: "beta", port: "18790", status: "running" }, + ], + "beta", + "18790", + () => { + probed = true; + return true; + }, + ); + + expect(result).toBe(true); + expect(probed).toBe(true); + }); + + it("returns occupied for a foreign live duplicate even when the target also has a live row", () => { + expect( + classifyForwardHealthWithReachability( + [ + { sandboxName: "beta", port: "18790", status: "running" }, + { sandboxName: "alpha", port: "18790", status: "running" }, + ], + "beta", + "18790", + () => true, + ), + ).toBe("occupied"); + }); +}); + +describe("executeSandboxExecCommand", () => { + it("parses stdout-framed root exec output after the startup marker", () => { + const childProcess = requireSource("node:child_process"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "OpenShell sandbox exec output:", + "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__", + "stdout: SECRET_BOUNDARY_OK", + ].join("\n"), + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + }); + + it("rejects a non-frame preamble and surfaces a missing trusted fallback identity", () => { + const childProcess = requireSource("node:child_process"); + const dockerExec = requireSource("../src/lib/adapters/docker/exec.ts"); + const privilegedExec = requireSource("../src/lib/sandbox/privileged-exec.ts"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout", + "stdout: RUNNING", + ].join("\n"), + stderr: "", + } as never); + const privilegedArgv = vi.spyOn(privilegedExec, "privilegedSandboxExecArgv"); + const dockerSpawnSync = vi.spyOn(dockerExec, "dockerSpawnSync"); + + expect(() => + withFakeOpenshellBinary(() => executeSandboxExecCommand("hermes-box", "echo RUNNING")), + ).toThrow(/No NemoClaw registry entry found.*refusing privileged exec/); + expect(privilegedArgv).toHaveBeenCalledTimes(1); + expect(dockerSpawnSync).not.toHaveBeenCalled(); + }); + + it("passes a newline-free Hermes validator payload to OpenShell", () => { + const childProcess = requireSource("node:child_process"); + const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand( + "hermes-box", + "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", + ), + ); + + const args = spawn.mock.calls[0]?.[1] as string[]; + const shellPayload = args.at(-1) ?? ""; + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(shellPayload.includes("\n")).toBe(false); + expect(shellPayload.includes("\r")).toBe(false); + expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + expect(shellPayload).toContain("base64 -d | sh"); + }); + + it("falls back to local Docker root exec when OpenShell exec output has no marker", () => { + const childProcess = requireSource("node:child_process"); + const dockerExec = requireSource("../src/lib/adapters/docker/exec.ts"); + const privilegedExec = requireSource("../src/lib/sandbox/privileged-exec.ts"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "OpenShell transport preamble\n", + stderr: "", + } as never); + const privilegedArgv = vi + .spyOn(privilegedExec, "privilegedSandboxExecArgv") + .mockReturnValue([ + "exec", + "--user", + "root", + "openshell-hermes-box-generated", + "sh", + "-c", + "marked-command", + ]); + const dockerSpawnSync = vi.spyOn(dockerExec, "dockerSpawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(privilegedArgv).toHaveBeenCalledWith("hermes-box", [ + "sh", + "-c", + expect.stringContaining("echo SECRET_BOUNDARY_OK"), + ]); + expect(dockerSpawnSync.mock.calls[0]?.[0]).toEqual([ + "exec", + "--user", + "root", + "openshell-hermes-box-generated", + "sh", + "-c", + "marked-command", + ]); + }); +}); diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 17821a65e09..024acc2eab1 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -8,16 +8,9 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import type { SandboxForwardListEntry } from "../src/lib/actions/sandbox/process-recovery.js"; const requireSource = createRequire(import.meta.url); -const { - checkAndRecoverSandboxProcesses, - classifyForwardHealthWithReachability, - classifySandboxForwardHealth, - executeSandboxExecCommand, - resolveSandboxDashboardPort, -} = requireSource( +const { checkAndRecoverSandboxProcesses } = requireSource( "../src/lib/actions/sandbox/process-recovery.ts", ) as typeof import("../src/lib/actions/sandbox/process-recovery.js"); @@ -92,250 +85,6 @@ function compactTeamsMessagingPlan(port = "3978") { }; } -describe("resolveSandboxDashboardPort", () => { - it("uses the recorded OpenClaw dashboard port for multi-sandbox recovery", () => { - expect( - resolveSandboxDashboardPort("beta", { - getSessionAgent: () => null, - getSandbox: () => ({ name: "beta", dashboardPort: 18790 }), - }), - ).toBe(18790); - }); - - it("falls back to the default OpenClaw dashboard port when registry metadata is absent", () => { - expect( - resolveSandboxDashboardPort("legacy", { - getSessionAgent: () => null, - getSandbox: () => null, - }), - ).toBe(18789); - }); - - it("keeps non-OpenClaw agents on their declared forward port", () => { - expect( - resolveSandboxDashboardPort("hermes-box", { - getSessionAgent: () => ({ forwardPort: 8642 }), - getSandbox: () => ({ name: "hermes-box", dashboardPort: 18790 }), - }), - ).toBe(8642); - }); - - it("does not invent a dashboard port for terminal agents without declared forwards", () => { - expect( - resolveSandboxDashboardPort("terminal-box", { - getSessionAgent: () => ({ runtime: { kind: "terminal" } }), - getSandbox: () => ({ name: "terminal-box", dashboardPort: 18790 }), - }), - ).toBe(18790); - }); - - it("ignores invalid agent forward ports and falls back to registry metadata", () => { - expect( - resolveSandboxDashboardPort("beta", { - getSessionAgent: () => ({ forwardPort: 0 }), - getSandbox: () => ({ name: "beta", dashboardPort: 18790 }), - }), - ).toBe(18790); - }); -}); - -describe("classifySandboxForwardHealth", () => { - it("returns true for a running forward owned by the target sandbox", () => { - expect( - classifySandboxForwardHealth( - [{ sandboxName: "beta", port: "18790", status: "running" }], - "beta", - "18790", - ), - ).toBe(true); - }); - - it("returns occupied when another sandbox owns the expected port", () => { - expect( - classifySandboxForwardHealth( - [{ sandboxName: "alpha", port: "18790", status: "running" }], - "beta", - "18790", - ), - ).toBe("occupied"); - }); - - it("returns false for a missing forward", () => { - expect(classifySandboxForwardHealth([], "beta", "18790")).toBe(false); - }); - - it("returns false for a non-running forward owned by the target sandbox", () => { - expect( - classifySandboxForwardHealth( - [{ sandboxName: "beta", port: "18790", status: "dead" }], - "beta", - "18790", - ), - ).toBe(false); - }); -}); - -describe("classifyForwardHealthWithReachability", () => { - // Regression coverage for #3334: `openshell forward list` STATUS can lag the - // real state of the forward. When it shows a non-running entry but the - // local port still answers, the forward is functionally healthy and the - // probe must not trigger spurious "missing or dead" + "Failed to - // re-establish" log pairs. - it("treats a non-running entry as healthy when the local port answers", () => { - // Covers both branches that produce `false` from the underlying classifier: - // a missing entry, and an entry whose status is anything but "running". - const inputs: SandboxForwardListEntry[][] = [ - [], - [{ sandboxName: "beta", port: "18790", status: "dead" }], - ]; - for (const entries of inputs) { - expect(classifyForwardHealthWithReachability(entries, "beta", "18790", () => true)).toBe( - true, - ); - } - }); - - it("returns false when forward list says dead and the port does not answer", () => { - expect( - classifyForwardHealthWithReachability( - [{ sandboxName: "beta", port: "18790", status: "dead" }], - "beta", - "18790", - () => false, - ), - ).toBe(false); - }); - - it("returns true without probing when forward list already reports running", () => { - let probed = false; - const result = classifyForwardHealthWithReachability( - [{ sandboxName: "beta", port: "18790", status: "running" }], - "beta", - "18790", - () => { - probed = true; - return false; - }, - ); - expect(result).toBe(true); - expect(probed).toBe(false); - }); - - it("returns occupied even when the port answers if another sandbox owns it", () => { - // Reachability says yes, but the entry belongs to a different sandbox — - // we must not silently take over someone else's forward. - expect( - classifyForwardHealthWithReachability( - [{ sandboxName: "alpha", port: "18790", status: "running" }], - "beta", - "18790", - () => true, - ), - ).toBe("occupied"); - }); -}); - -describe("executeSandboxExecCommand", () => { - it("parses stdout-framed root exec output after the startup marker", () => { - const childProcess = requireSource("node:child_process"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: [ - "OpenShell sandbox exec output:", - "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__", - "stdout: SECRET_BOUNDARY_OK", - ].join("\n"), - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), - ); - - expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); - }); - - it("rejects a non-frame preamble that contains the startup marker", () => { - const childProcess = requireSource("node:child_process"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: [ - "operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout", - "stdout: RUNNING", - ].join("\n"), - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo RUNNING"), - ); - - expect(result).toBeNull(); - }); - - it("passes a newline-free Hermes validator payload to OpenShell", () => { - const childProcess = requireSource("node:child_process"); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand( - "hermes-box", - "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", - ), - ); - - const args = spawn.mock.calls[0]?.[1] as string[]; - const shellPayload = args.at(-1) ?? ""; - expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); - expect(shellPayload.includes("\n")).toBe(false); - expect(shellPayload.includes("\r")).toBe(false); - expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); - expect(shellPayload).toContain("base64 -d | sh"); - }); - - it("falls back to local Docker root exec when OpenShell exec output has no marker", () => { - const childProcess = requireSource("node:child_process"); - const dockerExec = requireSource("../src/lib/adapters/docker/exec.js"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "OpenShell transport preamble\n", - stderr: "", - } as never); - const dockerSpawnSync = vi - .spyOn(dockerExec, "dockerSpawnSync") - .mockReturnValueOnce({ - status: 0, - stdout: "abc123\topenshell-hermes-box\n", - stderr: "", - } as never) - .mockReturnValueOnce({ - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never); - - const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), - ); - - expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); - expect(dockerSpawnSync.mock.calls[0]?.[0]).toEqual(["ps", "--format", "{{.ID}}\t{{.Names}}"]); - expect(dockerSpawnSync.mock.calls[1]?.[0]).toEqual([ - "exec", - "-u", - "root", - "abc123", - "sh", - "-c", - expect.stringContaining("echo SECRET_BOUNDARY_OK"), - ]); - }); -}); - describe("checkAndRecoverSandboxProcesses", () => { it("does not attempt gateway recovery for terminal agents", () => { const agentRuntime = requireSource("../src/lib/agent/runtime.js"); @@ -387,7 +136,7 @@ beta 127.0.0.1 18789 12345 running`; agent: "openclaw", dashboardPort: 18789, }); - vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(false); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation((rawArgs: unknown) => { const args = Array.isArray(rawArgs) ? rawArgs : []; expect(args).toEqual(["forward", "list"]); @@ -529,6 +278,9 @@ beta 127.0.0.1 18789 12345 running`; wasRunning: true, recovered: false, forwardRecovered: false, + forwardRecoveryFailed: true, + forwardRecoveryFailureDetail: + "the messaging webhook host forward could not be re-established", }); expect(runOpenshell).toHaveBeenCalledWith( ["forward", "start", "--background", "3978", "beta"], @@ -536,141 +288,278 @@ beta 127.0.0.1 18789 12345 running`; ); }); - it("waits for a recovered sandbox gateway before declaring recovery", () => { + it("waits for stopped Hermes recovery after managed OpenShell control succeeds", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); const runningForward = `SANDBOX BIND PORT PID STATUS -beta 127.0.0.1 18789 12345 running`; - let healthProbeCalls = 0; +hermes-box 127.0.0.1 18789 12345 running`; + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; + const commands: string[] = []; + let restarted = false; + const requestGatewaySupervisorAction = vi.fn(() => { + restarted = true; + return { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }; + }); + + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "2"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "0"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + + try { + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (command: unknown, rawArgs: unknown) => { + const shellCommand = getSandboxExecShellCommand(rawArgs); + const isHealthProbe = shellCommand.includes("HTTP_CODE=$(curl"); + const probeStatus = restarted ? "RUNNING" : "STOPPED"; + const stdout = isHealthProbe + ? `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${probeStatus}\n` + : "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n"; + commands.push(String(command)); + return { status: 0, stdout, stderr: "" } as never; + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "hermes", + displayName: "Hermes Agent", + binary_path: "/usr/local/bin/hermes", + gateway_command: "hermes gateway run", + forwardPort: 18789, + forward_ports: [18789, 8642], + healthProbe: { url: "http://127.0.0.1:8642/health", port: 8642, timeout_seconds: 5 }, + configPaths: { + dir: "/sandbox/.hermes", + configFile: "/sandbox/.hermes/config.yaml", + envFile: "/sandbox/.hermes/.env", + format: "yaml", + }, + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "hermes-box", + agent: "hermes", + dashboardPort: 18789, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: runningForward, + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + + const result = withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), + ); + expect(result.recovered).toBe(true); + expect(result.wasRunning).toBe(false); + expect(commands).not.toContain("ssh"); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); + } finally { + previousWaitSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = previousWaitSeconds); + previousPollInterval === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = previousPollInterval); + previousSettleSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = previousSettleSeconds); + } + }); + + it.each([ + ["a recovery marker from a failed action", "GATEWAY_PID=4242\n", "dashboard recovery failed"], + ["an unavailable managed supervisor", "", "SUPERVISOR_UNAVAILABLE"], + ["a non-exact self-recovery marker", "", "prefix SUPERVISOR_UNAVAILABLE suffix"], + ["an extra self-recovery error", "", "SUPERVISOR_UNAVAILABLE\nGATEWAY_FAILED"], + ["a self-recovery marker on stdout", "SUPERVISOR_UNAVAILABLE", ""], + ])("does not accept %s for Hermes", (_label, stdout, stderr) => { + const agentRuntime = requireSource("../src/lib/agent/runtime.js"); + const registry = requireSource("../src/lib/state/registry.js"); + const childProcess = requireSource("node:child_process"); + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 1, + stdout, + stderr, + })); - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", "2"); - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "0"); - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS", "0"); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { - healthProbeCalls += 1; - const status = healthProbeCalls >= 3 ? "RUNNING" : "STOPPED"; return { status: 0, - stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${status}\n`, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSTOPPED\n", stderr: "", } as never; } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nGATEWAY_PID=123\n", - stderr: "", - } as never; + return { status: 1, stdout: "", stderr: "unexpected command" } as never; }, ); - vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "hermes", + displayName: "Hermes Agent", + binary_path: "/usr/local/bin/hermes", + gateway_command: "hermes gateway run", + forwardPort: 8642, + healthProbe: { + url: "http://127.0.0.1:8642/health", + port: 8642, + timeout_seconds: 90, + }, + }); vi.spyOn(registry, "getSandbox").mockReturnValue({ - name: "beta", - agent: "openclaw", + name: "hermes-box", + agent: "hermes", dashboardPort: 18789, }); - vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ - status: 0, - output: runningForward, - }); expect( - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true })), + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), + ), ).toEqual({ checked: true, wasRunning: false, - recovered: true, - forwardRecovered: true, + recovered: false, + forwardRecovered: false, }); - expect(healthProbeCalls).toBe(3); + const transientFailure = stdout === "" && stderr === "SUPERVISOR_UNAVAILABLE"; + expect(requestGatewaySupervisorAction).toHaveBeenCalledTimes(transientFailure ? 3 : 1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); }); - it("re-checks the Hermes secret boundary after recovery health and refuses a late poison", () => { + it("leaves enabled Hermes dashboard recovery to the PID 1 supervisor", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); + const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); - const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - let healthProbeCalls = 0; - let secretBoundaryCalls = 0; - - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS", "2"); - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS", "0"); - vi.stubEnv("NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS", "0"); - const execResponses: Array<[string, () => never]> = [ - [ - "HTTP_CODE=$(curl", - () => { - healthProbeCalls += 1; - const status = healthProbeCalls === 1 ? "STOPPED" : "RUNNING"; - return { - status: 0, - stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${status}\n`, - stderr: "", - } as never; + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; + const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; + const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; + const sshCommands: string[] = []; + let restarted = false; + const requestGatewaySupervisorAction = vi.fn(() => { + restarted = true; + return { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }; + }); + + process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = "0"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = "0"; + process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; + + try { + vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ + status: 0, + output: "Host openshell-hermes-box\n HostName 127.0.0.1\n", + } as never); + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (command: unknown, rawArgs: unknown) => { + if (command === "ssh") { + sshCommands.push(getSandboxExecShellCommand(rawArgs)); + return { status: 0, stdout: "DASHBOARD_PID=5252\n", stderr: "" } as never; + } + const shellCommand = getSandboxExecShellCommand(rawArgs); + if (shellCommand.includes("HTTP_CODE=$(curl")) { + return { + status: 0, + stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${restarted ? "RUNNING" : "STOPPED"}\n`, + stderr: "", + } as never; + } + return { status: 1, stdout: "", stderr: "unexpected command" } as never; }, - ], - [ - "echo SECRET_BOUNDARY_OK", - () => { - secretBoundaryCalls += 1; - return { - status: 1, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_REFUSED\n", - stderr: - "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values", - } as never; + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "hermes", + displayName: "Hermes Agent", + binary_path: "/usr/local/bin/hermes", + gateway_command: "hermes gateway run", + forwardPort: 8642, + healthProbe: { + url: "http://127.0.0.1:8642/health", + port: 8642, + timeout_seconds: 90, }, - ], - ]; - vi.spyOn(childProcess, "spawnSync").mockImplementation((_command: unknown, rawArgs: unknown) => - ( - execResponses.find(([needle]) => - getSandboxExecShellCommand(rawArgs).includes(needle), - )?.[1] ?? - (() => - ({ - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nGATEWAY_PID=123\n", - stderr: "", - }) as never) - )(), - ); - vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ - name: "hermes", - forwardPort: 8642, - displayName: "Hermes Agent", - }); + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "hermes-box", + agent: "hermes", + dashboardPort: 18789, + hermesDashboardEnabled: true, + hermesDashboardPort: 9119, + hermesDashboardInternalPort: 19119, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: + "SANDBOX BIND PORT PID STATUS\n" + + "hermes-box 127.0.0.1 8642 12345 running\n" + + "hermes-box 127.0.0.1 9119 12346 running", + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + + expect( + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), + ), + ).toEqual({ + checked: true, + wasRunning: false, + recovered: true, + forwardRecovered: true, + }); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); + expect(sshCommands).toHaveLength(0); + } finally { + previousWaitSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS = previousWaitSeconds); + previousPollInterval === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS = previousPollInterval); + previousSettleSeconds === undefined + ? delete process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS + : (process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = previousSettleSeconds); + } + }); + + it("keeps quiet stopped-Hermes recovery failures off stderr", () => { + const agentRuntime = requireSource("../src/lib/agent/runtime.js"); + const registry = requireSource("../src/lib/state/registry.js"); + const childProcess = requireSource("node:child_process"); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSTOPPED\n", + stderr: "", + } as never); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); vi.spyOn(registry, "getSandbox").mockReturnValue({ - name: "hermes-box", agent: "hermes", dashboardPort: 18789, - }); - const captureOpenshell = vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ - status: 0, - output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 18789 12345 running`, + name: "hermes-box", }); - expect( - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true })), - ).toEqual({ - checked: true, - wasRunning: false, - recovered: false, - forwardRecovered: false, - secretBoundaryRefused: true, - secretBoundaryReason: "raw-secret", - }); - expect(healthProbeCalls).toBe(2); - expect(secretBoundaryCalls).toBe(1); - expect(captureOpenshell).not.toHaveBeenCalled(); - expect(errorSpy).toHaveBeenCalledWith( - expect.stringContaining("Secret-boundary check refused recovery"), - ); + withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true })); + expect(errorSpy).not.toHaveBeenCalled(); }); it("re-establishes manifest-declared non-primary forward ports when only the primary is healthy", () => { @@ -685,24 +574,17 @@ hermes-box 127.0.0.1 18789 12345 running`; hermes-box 127.0.0.1 18789 12345 running hermes-box 127.0.0.1 8642 12346 running`; let secondaryStarted = false; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", - stderr: "", - } as never; - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", forwardPort: 18789, @@ -733,13 +615,20 @@ hermes-box 127.0.0.1 8642 12346 running`; }); expect( - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true })), + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), + ), ).toEqual({ checked: true, wasRunning: true, recovered: false, forwardRecovered: true, }); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); const startedNonPrimary = runOpenshell.mock.calls.some(([rawArgs]) => { const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; @@ -775,24 +664,17 @@ hermes-box 127.0.0.1 8642 12346 running`; const occupiedForwardList = `SANDBOX BIND PORT PID STATUS hermes-box 127.0.0.1 18789 12345 running sibling-box 127.0.0.1 8642 99999 running`; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", - stderr: "", - } as never; - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", forwardPort: 18789, @@ -815,11 +697,15 @@ sibling-box 127.0.0.1 8642 99999 running`; .mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result.checked).toBe(true); expect(result.wasRunning).toBe(true); expect(result.forwardRecovered).toBe(false); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); const touchedSecondary = runOpenshell.mock.calls.some(([rawArgs]) => { const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; @@ -836,30 +722,21 @@ sibling-box 127.0.0.1 8642 99999 running`; const childProcess = requireSource("node:child_process"); const primaryOnlyForward = `SANDBOX BIND PORT PID STATUS hermes-box 127.0.0.1 18789 12345 running`; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", - stderr: "", - } as never; - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", forwardPort: 18789, - // Mixed invalid entries the helper must skip: zero, negative, fractional, - // > 65535, non-numeric, and the primary entry. - forward_ports: [18789, 0, -1, 1.5, 70000, "8642" as unknown as number], + forward_ports: [18789, 0, -1, 1.5, 1023, 70000, "8642" as unknown as number], }); vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "hermes-box", @@ -875,8 +752,14 @@ hermes-box 127.0.0.1 18789 12345 running`; .spyOn(openshellRuntime, "runOpenshell") .mockReturnValue({ status: 0 } as never); - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("hermes-box", { quiet: true })); + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), + ); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); const issuedForwardStart = runOpenshell.mock.calls.some(([rawArgs]) => { const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; return args[0] === "forward" && args[1] === "start"; @@ -884,7 +767,7 @@ hermes-box 127.0.0.1 18789 12345 running`; expect(issuedForwardStart).toBe(false); }); - it("reports forwardRecovered=false when one declared secondary recovers and another fails", () => { + it("reports forward recovery failure when one declared secondary recovers and another fails", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); @@ -893,24 +776,17 @@ hermes-box 127.0.0.1 18789 12345 running`; const partialForward = `SANDBOX BIND PORT PID STATUS hermes-box 127.0.0.1 18789 12345 running hermes-box 127.0.0.1 8642 12346 running`; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", - stderr: "", - } as never; - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", forwardPort: 18789, @@ -935,21 +811,24 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(openshellRuntime, "runOpenshell").mockImplementation((rawArgs: unknown) => { const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; if (args[0] === "forward" && args[1] === "start" && args.includes("9100")) { - // Forward start succeeds at the OpenShell level but the post-start - // probe stays unhealthy — simulates a port that openshell launches - // and that immediately drops on the sandbox side. return { status: 0 } as never; } return { status: 0 } as never; }); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); void port9100Started; expect(result.checked).toBe(true); expect(result.wasRunning).toBe(true); expect(result.forwardRecovered).toBe(false); + expect(result.forwardRecoveryFailed).toBe(true); + expect(result.forwardRecoveryFailureDetail).toContain("agent-declared host forwards"); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); }); it("refuses recovery of a running Hermes gateway when /sandbox/.hermes/.env contains raw secret-shaped values", () => { @@ -958,8 +837,13 @@ hermes-box 127.0.0.1 8642 12346 running`; const registry = requireSource("../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - let secretBoundaryCalls = 0; let forwardListCalls = 0; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 1, + stdout: "SECRET_BOUNDARY_REFUSED\n", + stderr: + "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values\n[SECURITY] TELEGRAM_BOT_TOKEN (line 3)", + })); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -971,15 +855,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - return { - status: 1, - stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_REFUSED\n", - stderr: - "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values\n[SECURITY] TELEGRAM_BOT_TOKEN (line 3)", - } as never; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1007,7 +882,10 @@ hermes-box 127.0.0.1 8642 12346 running`; .mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1017,7 +895,8 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryRefused: true, secretBoundaryReason: "raw-secret", }); - expect(secretBoundaryCalls).toBe(1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); expect(forwardListCalls).toBe(0); expect(captureOpenshell).not.toHaveBeenCalled(); expect( @@ -1039,8 +918,8 @@ hermes-box 127.0.0.1 8642 12346 running`; const registry = requireSource("../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - let secretBoundaryCalls = 0; let forwardListCalls = 0; + const requestGatewaySupervisorAction = vi.fn(); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -1052,9 +931,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1076,7 +952,10 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1086,7 +965,7 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryRefused: true, secretBoundaryReason: "agent-missing", }); - expect(secretBoundaryCalls).toBe(0); + expect(requestGatewaySupervisorAction).not.toHaveBeenCalled(); expect(forwardListCalls).toBe(0); expect(captureOpenshell).not.toHaveBeenCalled(); const errorOutput = errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); @@ -1095,45 +974,22 @@ hermes-box 127.0.0.1 8642 12346 running`; ); }); - it("falls through when the Hermes secret-boundary check parses stdout-framed root exec markers", () => { + it.each([ + ["PID 1 supervisor", { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }], + ["OpenShell managed controller", { status: 0, stdout: "GATEWAY_PID=4242\n", stderr: "" }], + ])("falls through when the Hermes $label reports a healthy gateway", (_label, supervisorResult) => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); - let secretBoundaryCalls = 0; + const requestGatewaySupervisorAction = vi.fn(() => supervisorResult); - const execResponses: Array<[string, () => never]> = [ - [ - "HTTP_CODE=$(curl", - () => - ({ - status: 0, - stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", - stderr: "", - }) as never, - ], - [ - "validate-hermes-env-secret-boundary.py", - () => { - secretBoundaryCalls += 1; - return { - status: 0, - stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - }, - ], - ]; - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - return ( - execResponses.find(([needle]) => shellCommand.includes(needle))?.[1] ?? - (() => ({ status: 0, stdout: "", stderr: "" }) as never) - )(); - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "hermes", forwardPort: 8642, @@ -1147,12 +1003,14 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ status: 0, - output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 18789 12345 running`, + output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 8642 12346 running\nhermes-box 127.0.0.1 18789 12345 running`, }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1160,7 +1018,8 @@ hermes-box 127.0.0.1 8642 12346 running`; recovered: false, forwardRecovered: false, }); - expect(secretBoundaryCalls).toBe(1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); }); it("falls through to the forward-refresh path when the Hermes secret-boundary check passes", () => { @@ -1169,7 +1028,12 @@ hermes-box 127.0.0.1 8642 12346 running`; const registry = requireSource("../src/lib/state/registry.js"); const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); - let secretBoundaryCalls = 0; + let forwardStarted = false; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 0, + stdout: "GATEWAY_PID=4242\n", + stderr: "", + })); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -1181,14 +1045,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", - stderr: "", - } as never; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1203,22 +1059,38 @@ hermes-box 127.0.0.1 8642 12346 running`; dashboardPort: 18789, }); vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); - vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation(() => ({ status: 0, - output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 18789 12345 running`, - }); - vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 8642 12346 ${forwardStarted ? "running" : "dead"}\nhermes-box 127.0.0.1 18789 12345 running`, + })); + const runOpenshell = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockImplementation((rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + if (args[0] === "forward" && args[1] === "start" && args.includes("8642")) { + forwardStarted = true; + } + return { status: 0 } as never; + }); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, wasRunning: true, recovered: false, - forwardRecovered: false, + forwardRecovered: true, }); - expect(secretBoundaryCalls).toBe(1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); + expect(runOpenshell).toHaveBeenCalledWith( + ["forward", "start", "--background", "8642", "hermes-box"], + { ignoreError: true }, + ); }); it("refuses recovery when the Hermes secret-boundary validator is absent on an older sandbox image", () => { @@ -1228,6 +1100,11 @@ hermes-box 127.0.0.1 8642 12346 running`; const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 1, + stdout: "SECRET_BOUNDARY_VALIDATOR_MISSING\n", + stderr: "[gateway-recovery] ERROR: secret-boundary validator script missing", + })); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -1239,13 +1116,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_VALIDATOR_MISSING\n", - stderr: "", - } as never; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1267,7 +1137,10 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1277,34 +1150,28 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryRefused: true, secretBoundaryReason: "validator-missing", }); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); const errorOutput = errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); + expect(errorOutput).toContain("[gateway-recovery] ERROR"); expect(errorOutput).toContain( "Hermes secret-boundary validator missing in sandbox 'hermes-box'", ); expect(errorOutput).toContain("Re-image the sandbox with a current Hermes build."); }); - it("does not invoke the Hermes secret-boundary check for an OpenClaw sandbox", () => { + it("does not invoke the Hermes PID 1 supervisor path for a running OpenClaw sandbox", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); const forwardHealth = requireSource("../src/lib/actions/sandbox/forward-health.js"); const childProcess = requireSource("node:child_process"); - let secretBoundaryCalls = 0; + const requestGatewaySupervisorAction = vi.fn(); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const shellCommand = getSandboxExecShellCommand(rawArgs); - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - } - return { - status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", - stderr: "", - } as never; - }, - ); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stderr: "", + } as never); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null); vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "beta", @@ -1318,18 +1185,23 @@ hermes-box 127.0.0.1 8642 12346 running`; }); vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); - withFakeOpenshellBinary(() => checkAndRecoverSandboxProcesses("beta", { quiet: true })); - expect(secretBoundaryCalls).toBe(0); + withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("beta", { + quiet: true, + requestGatewaySupervisorAction, + }), + ); + expect(requestGatewaySupervisorAction).not.toHaveBeenCalled(); }); - it("fails safe on a running Hermes gateway when the root exec channel is unreachable", () => { + it("fails safe on a running Hermes gateway when the supervisor channel is unreachable", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - let secretBoundaryCalls = 0; let forwardListCalls = 0; + const requestGatewaySupervisorAction = vi.fn(() => null); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -1341,10 +1213,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - return { status: 1, stdout: "", stderr: "openshell: connection refused" } as never; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1370,7 +1238,10 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1380,7 +1251,8 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryRefused: true, secretBoundaryReason: "exec-failed", }); - expect(secretBoundaryCalls).toBe(1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); expect(forwardListCalls).toBe(0); expect(captureOpenshell).not.toHaveBeenCalled(); const errorOutput = errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); @@ -1389,13 +1261,17 @@ hermes-box 127.0.0.1 8642 12346 running`; ); }); - it("treats a non-zero boundary check without the REFUSED marker as inconclusive, not raw-secret", () => { + it("treats a non-zero boundary check without the REFUSED marker as unexpected, not raw-secret", () => { const openshellRuntime = requireSource("../src/lib/adapters/openshell/runtime.js"); const agentRuntime = requireSource("../src/lib/agent/runtime.js"); const registry = requireSource("../src/lib/state/registry.js"); const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - let secretBoundaryCalls = 0; + const requestGatewaySupervisorAction = vi.fn(() => ({ + status: 2, + stdout: "", + stderr: "python3: validator crashed: ImportError: no module named foo", + })); vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { @@ -1407,14 +1283,6 @@ hermes-box 127.0.0.1 8642 12346 running`; stderr: "", } as never; } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { - secretBoundaryCalls += 1; - return { - status: 2, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\n", - stderr: "python3: validator crashed: ImportError: no module named foo", - } as never; - } return { status: 0, stdout: "", stderr: "" } as never; }, ); @@ -1435,7 +1303,10 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); const result = withFakeOpenshellBinary(() => - checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + checkAndRecoverSandboxProcesses("hermes-box", { + quiet: true, + requestGatewaySupervisorAction, + }), ); expect(result).toEqual({ checked: true, @@ -1445,7 +1316,8 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryRefused: true, secretBoundaryReason: "unexpected-marker", }); - expect(secretBoundaryCalls).toBe(1); + expect(requestGatewaySupervisorAction).toHaveBeenCalledOnce(); + expect(requestGatewaySupervisorAction).toHaveBeenCalledWith("hermes-box", "recover"); const errorOutput = errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain("python3: validator crashed: ImportError: no module named foo"); expect(errorOutput).toContain( diff --git a/test/rebuild-shields-auto-unlock.test.ts b/test/rebuild-shields-auto-unlock.test.ts index 8aebb38ee11..515d075ca49 100644 --- a/test/rebuild-shields-auto-unlock.test.ts +++ b/test/rebuild-shields-auto-unlock.test.ts @@ -14,6 +14,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { killTimer } from "../src/lib/shields/timer-control"; const REPO_ROOT = path.join(import.meta.dirname, ".."); const NODE_BIN = path.dirname(process.execPath); @@ -21,6 +22,15 @@ const tmpFixtures: string[] = []; afterEach(() => { for (const dir of tmpFixtures.splice(0)) { + const previousHome = process.env.HOME; + try { + process.env.HOME = dir; + killTimer("my-assistant"); + } catch { + // Best effort; fixture removal below must still run. + } finally { + previousHome === undefined ? delete process.env.HOME : (process.env.HOME = previousHome); + } try { fs.rmSync(dir, { recursive: true, force: true }); } catch { @@ -216,11 +226,44 @@ if (a[0]==="exec") { index += 2; continue; } + if (a[index] === "--env") { + index += 2; + continue; + } break; } index++; // container name cmd = a.slice(index); } + const pythonIndex = cmd.indexOf("python3"); + if (pythonIndex >= 0) { + const helper = cmd[pythonIndex + 2]; + const action = cmd[pythonIndex + 3]; + if (helper === "/usr/local/lib/nemoclaw/openclaw-config-guard.py") { + if (action === "lock") writeLockState("locked"); + if (action === "unlock") writeLockState("unlocked"); + process.stdout.write(JSON.stringify({ + type: "result", + action, + status: "ok", + configDir: "/sandbox/.openclaw", + files: ["openclaw.json", ".config-hash"], + chattrApplied: action === "lock", + }) + "\\n"); + process.exit(0); + } + if (helper === "/usr/local/lib/nemoclaw/state-dir-guard.py") { + if (action === "lock") writeLockState("locked"); + if (action === "unlock") writeLockState("unlocked"); + process.stdout.write(JSON.stringify({ + type: "result", + action, + status: "ok", + issueCount: 0, + }) + "\\n"); + process.exit(0); + } + } // Verification reads: // stat -c '%a %U:%G' <path> → expect "660 sandbox:sandbox" or "2770 sandbox:sandbox" // lsattr -d <path> → "----i------" (locked) or no immutable bit (unlocked) @@ -229,7 +272,7 @@ if (a[0]==="exec") { // lsattr → "----i------" // We are testing the auto-unlock path: shields-down is called on a locked sandbox, // verification should look like 660 sandbox:sandbox / 2770 sandbox:sandbox. - if (cmd[0]==="python3" && cmd[1]==="-c") { writeLockState("unlocked"); process.exit(0); } + if (cmd[0]==="python3" && cmd[1]==="-I" && cmd[2]==="-c") { writeLockState("unlocked"); process.exit(0); } if (cmd[0]==="chattr" && cmd[1]==="-i") { writeLockState("unlocked"); process.exit(0); } if (cmd[0]==="chattr" && cmd[1]==="+i") { writeLockState("locked"); process.exit(0); } if (cmd[0]==="test" && cmd[1]==="-L") { process.exit(1); } @@ -240,6 +283,10 @@ if (a[0]==="exec") { if (cmd[0]==="stat") { const target = cmd[cmd.length-1]; const locked = readLockState() === "locked"; + if (target === "/sandbox") { + process.stdout.write("755 sandbox:sandbox\\n"); + process.exit(0); + } // Heuristic: directories tend to end with .openclaw or have no extension if (target.endsWith(".openclaw") || target.endsWith(".hermes") || /\\/(workspace|skills|hooks|cron|agents|extensions|plugins|memory|credentials|identity|devices|canvas|telegram)$/.test(target)) { process.stdout.write(locked ? "755 root:root\\n" : "2770 sandbox:sandbox\\n"); @@ -314,6 +361,13 @@ describe("rebuild auto-unlocks when shields are UP (#3113)", () => { const r = runRebuild(f); const output = (r.stdout || "") + (r.stderr || ""); + // This focused fixture intentionally stops later in rebuild when the fake + // gateway cannot perform the recreate. Assert the exact handled failure, + // rather than silently accepting a timeout/signal or null spawn status. + expect(r.status, output).toBe(1); + expect(r.signal).toBeNull(); + expect(r.error).toBeUndefined(); + // Without the fix this would be: // "Failed to back up sandbox state. Aborting rebuild to prevent data loss." expect(output).not.toContain("Aborting rebuild to prevent data loss"); @@ -332,6 +386,10 @@ describe("rebuild auto-unlocks when shields are UP (#3113)", () => { const r = runRebuild(f); const output = (r.stdout || "") + (r.stderr || ""); + expect(r.status, output).toBe(1); + expect(r.signal).toBeNull(); + expect(r.error).toBeUndefined(); + expect(output).not.toContain("Shields are UP"); expect(output).not.toContain("temporarily unlocking for rebuild backup"); expect(output).toContain("Backing up sandbox state"); diff --git a/test/rebuild-shields-window.test.ts b/test/rebuild-shields-window.test.ts index 5e1328acf78..28afd64c050 100644 --- a/test/rebuild-shields-window.test.ts +++ b/test/rebuild-shields-window.test.ts @@ -24,7 +24,7 @@ describe("rebuild shields window", () => { vi.spyOn(console, "error").mockImplementation(() => {}); }); - it("temporarily unlocks locked shields without starting an auto-restore timer", () => { + it("temporarily unlocks locked shields with a bounded auto-restore timer", () => { shieldsMock.isShieldsDown.mockReturnValue(false); const window = openRebuildShieldsWindow("locked-sandbox", "nemoclaw"); @@ -33,8 +33,10 @@ describe("rebuild shields window", () => { expect(window!.wasLocked).toBe(true); expect(shieldsMock.shieldsDown).toHaveBeenCalledWith("locked-sandbox", { reason: "auto-unlock for rebuild", - skipTimer: true, + timeout: "30m", throwOnError: true, + deferAutoRestoreWhileOwnerAlive: true, + allowLegacyHermesProtocol: true, }); }); @@ -47,6 +49,7 @@ describe("rebuild shields window", () => { expect(window.relocked).toBe(true); expect(shieldsMock.shieldsUp).toHaveBeenCalledWith("locked-sandbox", { throwOnError: true, + allowLegacyHermesProtocol: true, }); expect(relockRebuildShieldsWindow("locked-sandbox", window, true, "nemoclaw")).toBe(true); diff --git a/test/recover-port-forward.test.ts b/test/recover-port-forward.test.ts index db7ba0ba290..d7d86381482 100644 --- a/test/recover-port-forward.test.ts +++ b/test/recover-port-forward.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { type ChildProcess, spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -10,6 +10,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { execTimeout, testTimeoutOptions } from "./helpers/timeouts"; const tmpFixtures: string[] = []; +const listenerProcesses: ChildProcess[] = []; // Each fixture grabs a unique high port. Sharing port 18789 across tests // collides with real nemoclaw installs on the developer's machine: the @@ -20,15 +21,45 @@ const tmpFixtures: string[] = []; let nextFixturePort = 47000 + (process.pid % 10000); afterEach(() => { + for (const child of listenerProcesses.splice(0)) { + child.kill("SIGTERM"); + } for (const dir of tmpFixtures.splice(0)) { fs.rmSync(dir, { recursive: true, force: true }); } }); +function startReachableForward(port: string): void { + const child = spawn( + process.execPath, + [ + "-e", + `require("node:net").createServer(()=>{}).listen(${JSON.stringify(Number(port))},"127.0.0.1")`, + ], + { stdio: "ignore" }, + ); + listenerProcesses.push(child); + + const probe = + "const net=require('node:net');" + + `const s=net.createConnection({host:'127.0.0.1',port:${Number(port)}});` + + "s.setTimeout(100);" + + "s.on('connect',()=>{s.destroy();process.exit(0)});" + + "s.on('error',()=>process.exit(1));" + + "s.on('timeout',()=>{s.destroy();process.exit(1)});"; + const deadline = Date.now() + 2000; + let listenerReady = false; + while (Date.now() < deadline && !listenerReady) { + listenerReady = spawnSync(process.execPath, ["-e", probe], { stdio: "ignore" }).status === 0; + } + expect(listenerReady, `test forward listener failed to bind port ${port}`).toBe(true); +} + interface Fixture { tmpDir: string; sandboxName: string; invocationLog: string; + recoveryWaitMs: string; } function setupFixture(opts: { @@ -38,6 +69,9 @@ function setupFixture(opts: { /** When false, `forward start` exits 0 but the post-restart probe keeps * reporting the original dead/missing state — models a failed restart. */ forwardStartHeals?: boolean; + /** Number of post-start list probes that remain stale before ownership is visible. */ + forwardStartDelayPolls?: number; + recoveryWaitMs?: string; port?: string; }): Fixture { const sandboxName = opts.sandboxName; @@ -76,7 +110,9 @@ function setupFixture(opts: { : `${sandboxName} 127.0.0.1 ${port} 12345 ${opts.forwardListStatus}\n`; const recoveredForwardListBody = `${sandboxName} 127.0.0.1 ${port} 99999 running\n`; const forwardStateFile = path.join(tmpDir, "forward-state"); + const forwardPollCountFile = path.join(tmpDir, "forward-poll-count"); fs.writeFileSync(forwardStateFile, "initial"); + fs.writeFileSync(forwardPollCountFile, "0"); // Fake openshell: emits the requested gateway-probe and forward-list // shapes, swallows mutating subcommands (forward stop / forward start) @@ -122,7 +158,15 @@ if (args[0] === "sandbox" && args[1] === "exec") { } if (args[0] === "forward" && args[1] === "list") { - const state = fs.readFileSync(${JSON.stringify(forwardStateFile)}, "utf-8"); + let state = fs.readFileSync(${JSON.stringify(forwardStateFile)}, "utf-8"); + if (state === "pending") { + const polls = Number(fs.readFileSync(${JSON.stringify(forwardPollCountFile)}, "utf-8")) + 1; + fs.writeFileSync(${JSON.stringify(forwardPollCountFile)}, String(polls)); + if (polls >= ${opts.forwardStartDelayPolls ?? 0}) { + fs.writeFileSync(${JSON.stringify(forwardStateFile)}, "running"); + state = "running"; + } + } process.stdout.write(state === "running" ? ${JSON.stringify(recoveredForwardListBody)} : ${JSON.stringify(initialForwardListBody)}); @@ -131,7 +175,10 @@ if (args[0] === "forward" && args[1] === "list") { if (args[0] === "forward" && args[1] === "start") { if (${opts.forwardStartHeals === false ? "false" : "true"}) { - fs.writeFileSync(${JSON.stringify(forwardStateFile)}, "running"); + fs.writeFileSync( + ${JSON.stringify(forwardStateFile)}, + ${opts.forwardStartDelayPolls ? '"pending"' : '"running"'}, + ); } process.exit(0); } @@ -157,7 +204,18 @@ process.exit(0); { mode: 0o755 }, ); - return { tmpDir, sandboxName, invocationLog }; + // A running OpenShell row is only healthy when its local socket also + // answers. Keep the listener alive in a separate process because runRecover + // uses spawnSync and blocks this Vitest worker's event loop. + const reachablePorts = opts.forwardStartHeals !== false ? [port] : []; + reachablePorts.forEach(startReachableForward); + + return { + tmpDir, + sandboxName, + invocationLog, + recoveryWaitMs: opts.recoveryWaitMs ?? "0", + }; } function runRecover(fixture: Fixture) { @@ -173,6 +231,7 @@ function runRecover(fixture: Fixture) { HOME: fixture.tmpDir, PATH: "/usr/bin:/bin", NEMOCLAW_NO_CONNECT_HINT: "1", + NEMOCLAW_FORWARD_RECOVERY_WAIT_MS: fixture.recoveryWaitMs, }, timeout: execTimeout(15_000), }, @@ -205,6 +264,30 @@ describe("nemoclaw <name> recover", () => { }, ); + it( + "polls until the exact forward owner appears after background start", + testTimeoutOptions(20_000), + () => { + const fixture = setupFixture({ + sandboxName: "delayed-owner-sandbox", + gatewayProbe: "RUNNING", + forwardListStatus: "dead", + forwardStartDelayPolls: 3, + recoveryWaitMs: "2000", + }); + const result = runRecover(fixture); + expect(result.status).toBe(0); + + const calls = fs.readFileSync(fixture.invocationLog, "utf-8").split("\n"); + const startIdx = calls.findIndex((line) => line.startsWith("forward start ")); + const postStartListCalls = calls + .slice(startIdx + 1) + .filter((line) => line === "forward list"); + expect(startIdx).toBeGreaterThanOrEqual(0); + expect(postStartListCalls.length).toBeGreaterThanOrEqual(3); + }, + ); + it( "reports a failure when forward start succeeds but the post-restart probe still shows dead", testTimeoutOptions(20_000), @@ -216,12 +299,11 @@ describe("nemoclaw <name> recover", () => { forwardStartHeals: false, }); const result = runRecover(fixture); - expect(result.status).toBe(0); + expect(result.status).toBe(1); const combined = (result.stdout || "") + (result.stderr || ""); - // Probe wrapper falls back to the plain "is running" line; the success - // suffix must not appear because the forward never came back. expect(combined).toContain("gateway is running in 'stuck-sandbox'"); + expect(combined).toContain("primary dashboard/API host forward could not be re-established"); expect(combined).not.toContain("restored dashboard port forward"); }, ); diff --git a/test/repro-2681-group-writable.test.ts b/test/repro-2681-group-writable.test.ts index 00fa8ee53f0..8387f9c3f80 100644 --- a/test/repro-2681-group-writable.test.ts +++ b/test/repro-2681-group-writable.test.ts @@ -19,6 +19,19 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; const START_SCRIPT = path.join(import.meta.dirname, "..", "scripts", "nemoclaw-start.sh"); +const OPENCLAW_CONFIG_GUARD = "/usr/local/lib/nemoclaw/openclaw-config-guard.py"; +const STATE_DIR_GUARD = "/usr/local/lib/nemoclaw/state-dir-guard.py"; +const HERMES_RUNTIME_CONFIG_GUARD = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py"; +const HERMES_LOCK_TOKEN = "a".repeat(64); +const HERMES_SEALED_GUARD_HELP = [ + "begin-shields-transition", + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "--rollback-shields-mode", +].join(" "); function extractShellFunctionFromSource(src: string, name: string): string { const match = src.match(new RegExp(`${name}\\(\\) \\{([\\s\\S]*?)^\\}`, "m")); @@ -51,8 +64,10 @@ function withMockedDockerExecFileSync<T>( // eslint-disable-next-line @typescript-eslint/no-require-imports const dockerExecModule = require("../src/lib/adapters/docker/exec.js") as { dockerExecFileSync: (args: readonly string[]) => string; + dockerSpawnSync: (args: readonly string[]) => unknown; }; const originalDockerExecFileSync = dockerExecModule.dockerExecFileSync; + const originalDockerSpawnSync = dockerExecModule.dockerSpawnSync; const shieldsModulePath = require.resolve("../src/lib/shields/index.js"); const privilegedExecPath = require.resolve("../src/lib/sandbox/privileged-exec.js"); const priorPrivilegedExec = require.cache[privilegedExecPath]; @@ -70,8 +85,24 @@ function withMockedDockerExecFileSync<T>( const separator = args.indexOf("--"); const command = separator >= 0 ? args.slice(separator + 1) : [...args]; calls.push(command); - if (command[0] === "python3" && command[1] === "-c") { - for (const target of command.slice(6)) { + const hermesGuardIndex = command.indexOf(HERMES_RUNTIME_CONFIG_GUARD); + const hermesAction = command[hermesGuardIndex + 1] ?? ""; + const hermesResponse = + hermesGuardIndex < 0 + ? undefined + : (new Map<string, string>([ + ["--help", HERMES_SEALED_GUARD_HELP], + ["begin-shields-transition", `lock_token=${HERMES_LOCK_TOKEN} original_locked=0`], + ["apply-shields-transition", "shields_mode=mutable chattr_applied=0"], + ]).get(hermesAction) ?? ""); + switch (hermesResponse) { + case undefined: + break; + default: + return hermesResponse; + } + if (command[0] === "python3" && command[1] === "-I" && command[2] === "-c") { + for (const target of command.slice(7)) { if (options.symlinkedPaths?.has(target)) { throw new Error(`refusing symlink path: ${target}`); } @@ -80,8 +111,14 @@ function withMockedDockerExecFileSync<T>( } if (command[0] === "stat" && command[1] === "-c") { const target = command.at(-1); - if (target === "/sandbox/.openclaw") return "2770 sandbox:sandbox\n"; - if (target === "/sandbox/.hermes") return "3770 sandbox:sandbox\n"; + switch (target) { + case "/sandbox": + return "755 sandbox:sandbox\n"; + case "/sandbox/.openclaw": + return "2770 sandbox:sandbox\n"; + case "/sandbox/.hermes": + return "3770 sandbox:sandbox\n"; + } if (typeof target === "string" && target.startsWith("/sandbox/.hermes/")) { return "640 sandbox:sandbox\n"; } @@ -93,10 +130,93 @@ function withMockedDockerExecFileSync<T>( return ""; }); + dockerExecModule.dockerSpawnSync = vi.fn((args: readonly string[]) => { + const separator = args.indexOf("--"); + const command = separator >= 0 ? args.slice(separator + 1) : [...args]; + calls.push(command); + + const openClawGuardIndex = command.indexOf(OPENCLAW_CONFIG_GUARD); + const stateDirGuardIndex = command.indexOf(STATE_DIR_GUARD); + switch (true) { + case command[0] === "test" && + command[1] === "-r" && + (command[2] === OPENCLAW_CONFIG_GUARD || command[2] === STATE_DIR_GUARD): + return { + status: 0, + signal: null, + stdout: "", + stderr: "", + pid: 0, + output: [], + } as never; + case openClawGuardIndex >= 0: { + const action = command[openClawGuardIndex + 1]; + const symlinkedTarget = [...(options.symlinkedPaths ?? [])].find((target) => + target.startsWith("/sandbox/.openclaw/"), + ); + const refused = action === "preflight" && symlinkedTarget !== undefined; + const records = refused + ? [ + { + type: "issue", + code: "unsafe-path", + path: symlinkedTarget, + detail: `refusing symlink path: ${symlinkedTarget}`, + }, + { type: "result", action, status: "failed" }, + ] + : [ + { + type: "result", + action, + status: "ok", + configDir: "/sandbox/.openclaw", + files: ["openclaw.json", ".config-hash"], + chattrApplied: action === "lock", + }, + ]; + return { + status: refused ? 1 : 0, + signal: null, + stdout: `${records.map((record) => JSON.stringify(record)).join("\n")}\n`, + stderr: "", + pid: 0, + output: [], + } as never; + } + case stateDirGuardIndex >= 0: { + const action = command[stateDirGuardIndex + 1]; + return { + status: 0, + signal: null, + stdout: `${JSON.stringify({ + type: "result", + action, + status: "ok", + issueCount: 0, + })}\n`, + stderr: "", + pid: 0, + output: [], + } as never; + } + default: + return { + status: 0, + signal: null, + stdout: "", + stderr: "", + pid: 0, + output: [], + } as never; + } + }); + try { return run(); } finally { dockerExecModule.dockerExecFileSync = originalDockerExecFileSync; + dockerExecModule.dockerSpawnSync = originalDockerSpawnSync; delete require.cache[shieldsModulePath]; if (priorPrivilegedExec) require.cache[privilegedExecPath] = priorPrivilegedExec; else delete require.cache[privilegedExecPath]; @@ -237,41 +357,29 @@ describe("mutable agent config permissions", () => { }); }); - const configUnlock = commands.find( - (command) => command[0] === "python3" && command[1] === "-c", - ); - expect(configUnlock).toEqual( - expect.arrayContaining([ - "660", - "2770", - "sandbox:sandbox", - "/sandbox/.openclaw", - "/sandbox/.openclaw/openclaw.json", - "/sandbox/.openclaw/.config-hash", - ]), - ); - // The consolidated state-dir unlock script restores ownership and mode on - // every high-risk state dir (including `workspace`) inside a single - // `sh -c` invocation; the workspace-* glob is handled by a second - // `sh -c`. Both are asserted via the `arrayContaining` check below. - const shellInvocations = commands.filter( - (command) => command[0] === "sh" && command[1] === "-c", - ); + const openClawActions = commands + .filter((command) => command.includes(OPENCLAW_CONFIG_GUARD)) + .map((command) => command[command.indexOf(OPENCLAW_CONFIG_GUARD) + 1]) + .filter((action): action is string => typeof action === "string"); + const stateDirActions = commands + .filter((command) => command.includes(STATE_DIR_GUARD)) + .map((command) => command[command.indexOf(STATE_DIR_GUARD) + 1]) + .filter((action): action is string => typeof action === "string"); + expect(openClawActions).toEqual(["preflight", "unlock"]); + expect(stateDirActions).toEqual(["unlock"]); + expect(commands).toContainEqual(["test", "-r", OPENCLAW_CONFIG_GUARD]); + expect(commands).toContainEqual(["test", "-r", STATE_DIR_GUARD]); + expect(commands).toContainEqual(["stat", "-c", "%a %U:%G", "/sandbox/.openclaw/openclaw.json"]); + expect(commands).toContainEqual(["stat", "-c", "%a %U:%G", "/sandbox/.openclaw/.config-hash"]); expect( - shellInvocations.some( + commands.some( (command) => - command.includes("/sandbox/.openclaw") && - command.includes("sandbox:sandbox") && - command.includes("g+rwX,o-rwx") && - command.includes("2770") && - command.includes("workspace"), - ), - ).toBe(true); - expect( - shellInvocations.some( - (command) => typeof command[2] === "string" && command[2].includes("workspace-*"), + command[0] === "sh" && + command[1] === "-c" && + typeof command[2] === "string" && + command[2].includes("chown -R"), ), - ).toBe(true); + ).toBe(false); }); it("refuses to unlock OpenClaw config when a config path is a symlink", () => { @@ -306,22 +414,22 @@ describe("mutable agent config permissions", () => { ), ).toThrow("refusing symlink path"); - const configUnlock = commands.find( - (command) => command[0] === "python3" && command[1] === "-c", - ); - expect(configUnlock).toEqual( + const openClawPreflight = commands.find((command) => { + const guardIndex = command.indexOf(OPENCLAW_CONFIG_GUARD); + return guardIndex >= 0 && command[guardIndex + 1] === "preflight"; + }); + expect(openClawPreflight).toEqual( expect.arrayContaining([ + "python3", + "-I", + OPENCLAW_CONFIG_GUARD, + "preflight", + "--config-dir", "/sandbox/.openclaw", - "/sandbox/.openclaw/openclaw.json", - "/sandbox/.openclaw/.config-hash", ]), ); - const script = configUnlock?.[2] ?? ""; - expect(script).toContain("unlock_ok = False"); - expect(script).toContain('flags |= getattr(os, "O_NONBLOCK", 0)'); - expect(script).toContain("if unlock_ok:"); - expect(script).toContain("elif dir_stat is not None:"); - expect(script).toContain("os.fchmod(dir_fd, stat.S_IMODE(dir_stat.st_mode))"); + expect(commands).toContainEqual(["test", "-r", OPENCLAW_CONFIG_GUARD]); + expect(commands.some((command) => command.includes(STATE_DIR_GUARD))).toBe(false); expect( commands.some( (command) => @@ -357,19 +465,30 @@ describe("mutable agent config permissions", () => { }); }); - const configUnlock = commands.find( - (command) => command[0] === "python3" && command[1] === "-c", - ); - expect(configUnlock).toEqual( - expect.arrayContaining([ - "640", - "3770", - "sandbox:sandbox", - "/sandbox/.hermes", - "/sandbox/.hermes/config.yaml", - "/sandbox/.hermes/.env", - ]), + const hermesActions = commands + .filter((command) => command.includes(HERMES_RUNTIME_CONFIG_GUARD)) + .map((command) => command[command.indexOf(HERMES_RUNTIME_CONFIG_GUARD) + 1]); + expect(hermesActions).toEqual([ + "--help", + "begin-shields-transition", + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + ]); + const begin = commands.find((command) => command.includes("begin-shields-transition")); + expect(begin).toEqual( + expect.arrayContaining(["--shields-mode", "mutable", "--rollback-shields-mode", "mutable"]), ); + for (const action of [ + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + ]) { + const command = commands.find((candidate) => candidate.includes(action)); + expect(command).toEqual(expect.arrayContaining(["--lock-token", HERMES_LOCK_TOKEN])); + } + expect(commands).toContainEqual(["stat", "-c", "%a %U:%G", "/sandbox/.hermes/config.yaml"]); + expect(commands).toContainEqual(["stat", "-c", "%a %U:%G", "/sandbox/.hermes/.env"]); }); it("shields-up strips setgid from the OpenClaw config root before verifying lock", () => { @@ -381,6 +500,8 @@ describe("mutable agent config permissions", () => { const Module = require("node:module"); const originalLoad = Module._load; const calls = []; +const OPENCLAW_CONFIG_GUARD = ${JSON.stringify(OPENCLAW_CONFIG_GUARD)}; +const STATE_DIR_GUARD = ${JSON.stringify(STATE_DIR_GUARD)}; Module._load = function patchedLoad(request, parent, isMain) { if (request === "../adapters/docker/exec") { return { @@ -389,9 +510,9 @@ Module._load = function patchedLoad(request, parent, isMain) { const command = separator >= 0 ? args.slice(separator + 1) : args; calls.push(command); if (command[0] === "stat" && command[1] === "-c") { - return command.at(-1) === "/sandbox/.openclaw" - ? "755 root:root\n" - : "444 root:root\n"; + const target = command.at(-1); + if (target === "/sandbox") return "1775 root:sandbox\n"; + return target === "/sandbox/.openclaw" ? "755 root:root\n" : "444 root:root\n"; } if (command[0] === "lsattr") { return "----i----------------- " + command.at(-1) + "\n"; @@ -405,6 +526,55 @@ Module._load = function patchedLoad(request, parent, isMain) { } return ""; }, + dockerSpawnSync(args) { + const separator = args.indexOf("--"); + const command = separator >= 0 ? args.slice(separator + 1) : args; + calls.push(command); + if ( + command[0] === "test" && + command[1] === "-r" && + (command[2] === OPENCLAW_CONFIG_GUARD || command[2] === STATE_DIR_GUARD) + ) { + return { status: 0, signal: null, stdout: "", stderr: "", pid: 0, output: [] }; + } + const openClawGuardIndex = command.indexOf(OPENCLAW_CONFIG_GUARD); + if (openClawGuardIndex >= 0) { + const action = command[openClawGuardIndex + 1]; + return { + status: 0, + signal: null, + stdout: JSON.stringify({ + type: "result", + action, + status: "ok", + configDir: "/sandbox/.openclaw", + files: ["openclaw.json", ".config-hash"], + chattrApplied: action === "lock", + }) + "\n", + stderr: "", + pid: 0, + output: [], + }; + } + const stateDirGuardIndex = command.indexOf(STATE_DIR_GUARD); + if (stateDirGuardIndex >= 0) { + const action = command[stateDirGuardIndex + 1]; + return { + status: 0, + signal: null, + stdout: JSON.stringify({ + type: "result", + action, + status: "ok", + issueCount: 0, + }) + "\n", + stderr: "", + pid: 0, + output: [], + }; + } + return { status: 0, signal: null, stdout: "", stderr: "", pid: 0, output: [] }; + }, }; } if (request === "../sandbox/privileged-exec") { @@ -429,23 +599,37 @@ process.stdout.write(JSON.stringify(calls)); { encoding: "utf-8", timeout: 5000 }, ); - expect(probe.status).toBe(0); + expect(probe.status, probe.stderr).toBe(0); const commands = JSON.parse(probe.stdout) as string[][]; - const stateDirLockIndex = commands.findIndex( - (command) => - command[0] === "sh" && - command[1] === "-c" && - command.includes("/sandbox/.openclaw") && - command.includes("root:sandbox") && - command.includes("go-w") && - command.includes("755"), + const openClawCapabilityIndex = commands.findIndex( + (command) => command.join("\0") === ["test", "-r", OPENCLAW_CONFIG_GUARD].join("\0"), + ); + const openClawLockIndex = commands.findIndex((command) => { + const guardIndex = command.indexOf(OPENCLAW_CONFIG_GUARD); + return guardIndex >= 0 && command[guardIndex + 1] === "lock"; + }); + const stateDirCapabilityIndex = commands.findIndex( + (command) => command.join("\0") === ["test", "-r", STATE_DIR_GUARD].join("\0"), ); - const stripSetgidIndex = commands.findIndex( - (command) => command.join("\0") === ["chmod", "g-s", "/sandbox/.openclaw"].join("\0"), + const stateDirLockIndex = commands.findIndex((command) => { + const guardIndex = command.indexOf(STATE_DIR_GUARD); + return guardIndex >= 0 && command[guardIndex + 1] === "lock"; + }); + const verificationIndex = commands.findIndex( + (command, index) => + index > stateDirLockIndex && + command[0] === "stat" && + command[1] === "-c" && + command.at(-1) === "/sandbox/.openclaw", ); + expect(openClawCapabilityIndex).toBeGreaterThan(-1); + expect(openClawLockIndex).toBeGreaterThan(openClawCapabilityIndex); + expect(stateDirCapabilityIndex).toBeGreaterThan(openClawLockIndex); expect(stateDirLockIndex).toBeGreaterThan(-1); - expect(stripSetgidIndex).toBeGreaterThan(stateDirLockIndex); - expect(commands).toContainEqual(["chmod", "755", "/sandbox/.openclaw"]); + expect(stateDirLockIndex).toBeGreaterThan(stateDirCapabilityIndex); + expect(verificationIndex).toBeGreaterThan(stateDirLockIndex); + expect(commands).not.toContainEqual(["chmod", "g-s", "/sandbox/.openclaw"]); + expect(commands).not.toContainEqual(["chmod", "755", "/sandbox/.openclaw"]); }); it("does not relax a root-owned config tree while shields are up", () => { diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index ea172d43713..9d3a2a8c10f 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -72,9 +72,14 @@ describe("sandbox build context staging", () => { fs.chmodSync(path.join(sourceRoot, "nemoclaw-blueprint", "model-specific-setup"), 0o700); fs.chmodSync(blueprintManifestDir, 0o700); writeFixture(path.join("scripts", "nemoclaw-start.sh")); + writeFixture(path.join("scripts", "gateway-control.sh")); + writeFixture(path.join("scripts", "managed-gateway-control.py")); + writeFixture(path.join("scripts", "state-dir-guard.py")); + writeFixture(path.join("scripts", "openclaw-config-guard.py")); writeFixture(path.join("scripts", "codex-acp-wrapper.sh")); writeFixture(path.join("scripts", "generate-openclaw-config.mts")); writeFixture(path.join("scripts", "lib", "sandbox-init.sh")); + writeFixture(path.join("scripts", "lib", "gateway-supervisor.sh")); writeFixture(path.join("scripts", "lib", "sandbox-rlimits.sh")); writeFixture(path.join("scripts", "lib", "openclaw_device_approval_policy.py")); writeFixture(path.join("scripts", "lib", "clean_runtime_shell_env_shim.py")); @@ -265,6 +270,12 @@ describe("sandbox build context staging", () => { ), ).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "nemoclaw-start.sh"))).toBe(true); + expect(fs.existsSync(path.join(buildCtx, "scripts", "gateway-control.sh"))).toBe(true); + expect(fs.existsSync(path.join(buildCtx, "scripts", "managed-gateway-control.py"))).toBe( + true, + ); + expect(fs.existsSync(path.join(buildCtx, "scripts", "state-dir-guard.py"))).toBe(true); + expect(fs.existsSync(path.join(buildCtx, "scripts", "openclaw-config-guard.py"))).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "codex-acp-wrapper.sh"))).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "generate-openclaw-config.mts"))).toBe( true, @@ -300,6 +311,9 @@ describe("sandbox build context staging", () => { true, ); expect(fs.existsSync(path.join(buildCtx, "scripts", "lib", "sandbox-init.sh"))).toBe(true); + expect(fs.existsSync(path.join(buildCtx, "scripts", "lib", "gateway-supervisor.sh"))).toBe( + true, + ); expect(fs.existsSync(path.join(buildCtx, "scripts", "lib", "sandbox-rlimits.sh"))).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "setup.sh"))).toBe(false); } finally { diff --git a/test/sandbox-connect-inference/auto-pair-approval.test.ts b/test/sandbox-connect-inference/auto-pair-approval.test.ts index 653756acf93..07e19f7d5ec 100644 --- a/test/sandbox-connect-inference/auto-pair-approval.test.ts +++ b/test/sandbox-connect-inference/auto-pair-approval.test.ts @@ -31,6 +31,23 @@ function findApprovalExec(sandboxExecCalls: string[][]): string[] | undefined { }); } +function findGatewayControlExec(dockerCalls: string[][]): string[] | undefined { + return dockerCalls.find((call) => { + const userIndex = call.indexOf("--user"); + return ( + call[0] === "exec" && + userIndex > 1 && + call.includes("LD_PRELOAD=") && + call.includes("PYTHONUSERBASE=") && + call.includes("PYTHONNOUSERSITE=1") && + call[userIndex + 1] === "root" && + call[userIndex + 3] === "/usr/local/bin/nemoclaw-gateway-control" && + call[userIndex + 4] === "recover" && + call.length === userIndex + 6 + ); + }); +} + describe("sandbox connect auto-pair approval pass (#4263)", () => { it( "runs a bounded openclaw devices approval pass before opening SSH", @@ -49,7 +66,7 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { ); const result = runConnect(tmpDir, sandboxName); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const script = extractApprovalPassScript(stateFile, sandboxName); // Hardened script content: source the proxy env, require local tools, @@ -94,7 +111,7 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { ); const result = runConnect(tmpDir, sandboxName); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const script = extractApprovalPassScript(stateFile, sandboxName); // Disallowed/malformed/unknown requests are skipped by the policy before // an approve is even attempted (they `continue` before the attempt @@ -172,7 +189,7 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { ); const result = runConnect(tmpDir, sandboxName); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const script = extractApprovalPassScript(stateFile, sandboxName); const run = runApprovalPassScript( script, @@ -214,7 +231,7 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { const result = runConnect(tmpDir, sandboxName, { NEMOCLAW_TEST_FAIL_APPROVAL_PASS: "1", }); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const state = JSON.parse(fs.readFileSync(stateFile, "utf-8")); // Approval-pass exec was attempted (and the fake openshell exited // non-zero for it, per the hook above). @@ -244,9 +261,9 @@ describe("sandbox connect scope-upgrade approval on recover/probe (#4504)", () = "runs the approval pass on the --probe-only (recover) path", testTimeoutOptions(20_000), () => { - // The probe takes the wasRunning branch (the fake openshell health probe - // reports RUNNING), so the recover path must run the sweep — and must NOT - // open an SSH session. + // The probe starts with a stopped gateway, recovers it through the + // root-only PID 1 control helper, then runs the sweep without opening an + // SSH session. const { tmpDir, stateFile, sandboxName } = setupFixture( { name: "probe-approval-sandbox", @@ -257,12 +274,27 @@ describe("sandbox connect scope-upgrade approval on recover/probe (#4504)", () = }, "anthropic-prod", "claude-sonnet-4-20250514", + { gatewaySupervisorRecovery: true }, ); const result = runConnect(tmpDir, sandboxName, {}, ["--probe-only"]); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const state = JSON.parse(fs.readFileSync(stateFile, "utf-8")); + const controlExec = findGatewayControlExec(state.dockerCalls as string[][]); + const userIndex = controlExec?.indexOf("--user") ?? -1; + expect(controlExec?.slice(userIndex, userIndex + 5)).toEqual([ + "--user", + "root", + `openshell-${sandboxName}-fixture`, + "/usr/local/bin/nemoclaw-gateway-control", + "recover", + ]); + expect(controlExec).toContain("LD_PRELOAD="); + expect(controlExec).toContain("PYTHONUSERBASE="); + expect(controlExec).toContain("PYTHONNOUSERSITE=1"); + expect(controlExec?.[userIndex + 5]).toMatch(/^[0-9a-f]{64}$/); + expect(state.gatewayRunning).toBe(true); const approvalExec = findApprovalExec(state.sandboxExecCalls as string[][]); expect(approvalExec).toBeDefined(); expect(approvalExec).toContain("sandbox"); @@ -290,12 +322,13 @@ describe("sandbox connect scope-upgrade approval on recover/probe (#4504)", () = }, "anthropic-prod", "claude-sonnet-4-20250514", + { gatewaySupervisorRecovery: true }, ); const result = runConnect(tmpDir, sandboxName, { NEMOCLAW_TEST_FAIL_APPROVAL_PASS: "1" }, [ "--probe-only", ]); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const state = JSON.parse(fs.readFileSync(stateFile, "utf-8")); const approvalExec = findApprovalExec(state.sandboxExecCalls as string[][]); @@ -355,10 +388,11 @@ describe("sandbox connect scope-upgrade approval on recover/probe (#4504)", () = }, "anthropic-prod", "claude-sonnet-4-20250514", + { gatewaySupervisorRecovery: true }, ); const result = runConnect(tmpDir, sandboxName, {}, ["--probe-only"]); - expect(result.status).toBe(0); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const script = extractApprovalPassScript(stateFile, sandboxName); expect(script).toContain("approve_env = gateway_approval_env(os.environ)"); @@ -393,6 +427,7 @@ describe("sandbox connect scope-upgrade approval on recover/probe (#4504)", () = }, "anthropic-prod", "claude-sonnet-4-20250514", + { gatewaySupervisorRecovery: true }, ); const result = runConnect(tmpDir, sandboxName, {}, ["--probe-only"]); diff --git a/test/sandbox-connect-inference/helpers.ts b/test/sandbox-connect-inference/helpers.ts index b983a16c344..fdee51ac555 100644 --- a/test/sandbox-connect-inference/helpers.ts +++ b/test/sandbox-connect-inference/helpers.ts @@ -1,11 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { type ChildProcess, spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { expect } from "vitest"; +import { afterEach, expect } from "vitest"; import { execTimeout } from "../helpers/timeouts"; /** @@ -17,6 +17,7 @@ import { execTimeout } from "../helpers/timeouts"; export type SandboxEntryFixture = { name: string; + dashboardPort?: number; model?: string | null; provider?: string | null; nimContainer?: string | null; @@ -33,8 +34,85 @@ export type SetupFixtureOptions = { inferenceProbeResponses?: string[]; inferenceSetStatus?: number; writeOllamaProxyState?: boolean; + gatewaySupervisorRecovery?: boolean; }; +const fixtureForwardListeners = new Map<string, ChildProcess>(); + +// A fixture can invoke runConnect more than once. Keep its advertised forward +// live for the whole test, then tear down the child and temp tree together. +function startFixtureForwardListener(tmpDir: string): number { + const readyPath = path.join(tmpDir, "forward-listener-ready"); + const errorPath = path.join(tmpDir, "forward-listener-error"); + const listener = spawn( + process.execPath, + [ + "-e", + [ + 'const fs = require("node:fs");', + 'const net = require("node:net");', + `const readyPath = ${JSON.stringify(readyPath)};`, + `const readyTempPath = ${JSON.stringify(`${readyPath}.tmp`)};`, + `const errorPath = ${JSON.stringify(errorPath)};`, + "const server = net.createServer((socket) => socket.end());", + "server.on('error', (error) => { fs.writeFileSync(errorPath, String(error)); process.exit(1); });", + "server.listen(0, '127.0.0.1', () => { fs.writeFileSync(readyTempPath, String(server.address().port)); fs.renameSync(readyTempPath, readyPath); });", + "const stop = () => server.close(() => process.exit(0));", + "process.on('SIGTERM', stop);", + "process.on('SIGINT', stop);", + "setTimeout(() => process.exit(0), 60000).unref();", + ].join("\n"), + ], + { stdio: "ignore" }, + ); + fixtureForwardListeners.set(tmpDir, listener); + + const waitCell = new Int32Array(new SharedArrayBuffer(4)); + const deadline = Date.now() + 5_000; + while (!fs.existsSync(readyPath) && !fs.existsSync(errorPath) && Date.now() < deadline) { + Atomics.wait(waitCell, 0, 0, 10); + } + if (!fs.existsSync(readyPath)) { + listener.kill("SIGTERM"); + const detail = fs.existsSync(errorPath) ? fs.readFileSync(errorPath, "utf-8") : "timeout"; + throw new Error(`Fixture forward listener failed to start: ${detail}`); + } + + const port = Number(fs.readFileSync(readyPath, "utf-8")); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + listener.kill("SIGTERM"); + throw new Error(`Fixture forward listener returned invalid port: ${String(port)}`); + } + return port; +} + +async function stopFixtureForwardListener(tmpDir: string): Promise<void> { + const listener = fixtureForwardListeners.get(tmpDir); + fixtureForwardListeners.delete(tmpDir); + if (!listener || listener.exitCode !== null) return; + + await new Promise<void>((resolve) => { + let finished = false; + const finish = () => { + if (finished) return; + finished = true; + clearTimeout(forceTimer); + clearTimeout(abandonTimer); + resolve(); + }; + const forceTimer = setTimeout(() => listener.kill("SIGKILL"), 1_000); + const abandonTimer = setTimeout(finish, 3_000); + listener.once("exit", finish); + listener.kill("SIGTERM"); + }); +} + +afterEach(async () => { + const fixtureDirs = [...fixtureForwardListeners.keys()]; + await Promise.all(fixtureDirs.map((tmpDir) => stopFixtureForwardListener(tmpDir))); + for (const tmpDir of fixtureDirs) fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + export function isHostWsl() { return ( process.platform === "linux" && @@ -97,6 +175,9 @@ function initStateFile(stateFile: string, options: SetupFixtureOptions) { inferenceSetCalls: [], sandboxConnectCalls: [], sandboxExecCalls: [], + gatewayControlCalls: [], + gatewaySupervisorRecovery: options.gatewaySupervisorRecovery ?? false, + gatewayRunning: options.gatewaySupervisorRecovery !== true, }), ); } @@ -110,6 +191,7 @@ function writeOpenshellStub( stateFile: string, sandboxName: string, inferenceBlock: string, + dashboardPort: number, options: SetupFixtureOptions, ) { writeExecutable( @@ -179,7 +261,8 @@ if (args[0] === "sandbox" && args[1] === "exec") { process.stdout.write("__NEMOCLAW_SANDBOX_EXEC_STARTED__\\nSTOPPED\\n"); process.exit(0); } - process.stdout.write("__NEMOCLAW_SANDBOX_EXEC_STARTED__\\nRUNNING\\n"); + const gatewayStatus = state.gatewayRunning === false ? "STOPPED" : "RUNNING"; + process.stdout.write("__NEMOCLAW_SANDBOX_EXEC_STARTED__\\n" + gatewayStatus + "\\n"); process.exit(0); } const response = state.inferenceProbeResponses.length @@ -215,6 +298,11 @@ if (args[0] === "logs") { process.exit(0); } +if (args[0] === "forward" && args[1] === "list") { + process.stdout.write("${sandboxName} 127.0.0.1 ${dashboardPort} 12345 running\\n"); + process.exit(0); +} + if (args[0] === "forward") { process.exit(0); } @@ -236,9 +324,44 @@ const state = JSON.parse(fs.readFileSync(stateFile, "utf8")); state.dockerCalls.push(args); fs.writeFileSync(stateFile, JSON.stringify(state)); const cmd = args.join(" "); +const userIndex = args.indexOf("--user"); +const sanitizedPrefix = + userIndex > 1 && + (userIndex - 1) % 2 === 0 && + args.slice(1, userIndex).every((value, index) => + index % 2 === 0 ? value === "--env" : /^[A-Z0-9_]+=.*$/.test(value) + ); if (args[0] === "ps") { - process.stdout.write("openshell-cluster-nemoclaw\\n"); + const directContainer = state.gatewaySupervisorRecovery + ? "openshell-${sandboxName}-fixture\\n" + : ""; + process.stdout.write("openshell-cluster-nemoclaw\\n" + directContainer); + process.exit(0); +} + +if ( + args[0] === "exec" && + sanitizedPrefix && + args.includes("LD_PRELOAD=") && + args.includes("PYTHONUSERBASE=") && + args.includes("PYTHONNOUSERSITE=1") && + args.length === userIndex + 6 && + args[userIndex + 1] === "root" && + args[userIndex + 2] === "openshell-${sandboxName}-fixture" && + args[userIndex + 3] === "/usr/local/bin/nemoclaw-gateway-control" && + args[userIndex + 4] === "recover" +) { + state.gatewayControlCalls.push(args); + const nonce = args[userIndex + 5] || ""; + if (!state.gatewaySupervisorRecovery || !/^[0-9a-f]{64}$/.test(nonce)) { + fs.writeFileSync(stateFile, JSON.stringify(state)); + process.stderr.write("PRIVILEGED_CONTROL_UNAVAILABLE\\n"); + process.exit(65); + } + state.gatewayRunning = true; + fs.writeFileSync(stateFile, JSON.stringify(state)); + process.stdout.write("GATEWAY_PID=4242\\n"); process.exit(0); } @@ -360,14 +483,19 @@ export function setupFixture( const curlPath = path.join(homeLocalBin, "curl"); const psPath = path.join(homeLocalBin, "ps"); const sandboxName = String(sandboxEntry.name); + // The OpenShell stub advertises this forward as running. Back that claim + // with a real listener so probe-only forward ownership checks behave the + // same on Linux and macOS, not according to whether a host happens to have + // the historical default port open. + const dashboardPort = startFixtureForwardListener(tmpDir); fs.mkdirSync(homeLocalBin, { recursive: true }); fs.mkdirSync(registryDir, { recursive: true }); const inferenceBlock = buildInferenceBlock(liveInferenceProvider, liveInferenceModel); - writeRegistryState(registryDir, sandboxName, sandboxEntry, options); + writeRegistryState(registryDir, sandboxName, { ...sandboxEntry, dashboardPort }, options); initStateFile(stateFile, options); - writeOpenshellStub(openshellPath, stateFile, sandboxName, inferenceBlock, options); + writeOpenshellStub(openshellPath, stateFile, sandboxName, inferenceBlock, dashboardPort, options); writeDockerStub(dockerPath, stateFile, sandboxName); writeCurlStub(curlPath, stateFile); writePsStub(psPath); @@ -415,6 +543,14 @@ export function runConnect( connectArgs: string[] = [], ) { const repoRoot = path.join(import.meta.dirname, "..", ".."); + const state = JSON.parse(fs.readFileSync(path.join(tmpDir, "state.json"), "utf-8")); + const recoveryEnv = state.gatewaySupervisorRecovery + ? { + NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS: "2", + NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS: "0", + NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS: "0", + } + : {}; return spawnSync( process.execPath, [path.join(repoRoot, "bin", "nemoclaw.js"), sandboxName, "connect", ...connectArgs], @@ -429,6 +565,7 @@ export function runConnect( NEMOCLAW_OLLAMA_PORT: "11434", NEMOCLAW_OLLAMA_PROXY_PORT: "11435", VITEST: "true", + ...recoveryEnv, ...extraEnv, }, timeout: execTimeout(30_000), diff --git a/test/sandbox-connect-inference/route-swap-repair.test.ts b/test/sandbox-connect-inference/route-swap-repair.test.ts index f9bd0a04541..e20d99ff8e6 100644 --- a/test/sandbox-connect-inference/route-swap-repair.test.ts +++ b/test/sandbox-connect-inference/route-swap-repair.test.ts @@ -23,6 +23,7 @@ describe("sandbox connect inference route swap (#1248)", () => { }, "anthropic-prod", "claude-sonnet-4-20250514", + { inferenceProbeResponses: ["OK 200", "OK 200"] }, ); const bogus = { NEMOCLAW_VLLM_MODEL: "definitely-not-a-real-vllm-model" }; const PREFLIGHT_HINT = "NEMOCLAW_VLLM_MODEL is consumed by"; @@ -36,6 +37,13 @@ describe("sandbox connect inference route swap (#1248)", () => { expect(probe.status).toBe(0); expect(probeOut).not.toContain(PREFLIGHT_HINT); + // A fixture remains truthful across repeated CLI invocations in one + // test: its advertised running forward keeps listening until afterEach. + const repeatedProbe = runConnect(fixture.tmpDir, fixture.sandboxName, bogus, [ + "--probe-only", + ]); + expect(repeatedProbe.status).toBe(0); + // A full connect still runs the preflight and fails fast on the bogus value. const full = runConnect(fixture.tmpDir, fixture.sandboxName, bogus, []); const fullOut = (full.stdout || "") + (full.stderr || ""); diff --git a/test/sandbox-init.test.ts b/test/sandbox-init.test.ts index a5dd71e7e65..1973171feef 100644 --- a/test/sandbox-init.test.ts +++ b/test/sandbox-init.test.ts @@ -999,6 +999,10 @@ EOF join(libDir, "sandbox-init.sh"), "export NEMOCLAW_TEST_SANDBOX_INIT_LOADED=1\n", ); + writeFileSync( + join(libDir, "gateway-supervisor.sh"), + "export NEMOCLAW_TEST_GATEWAY_SUPERVISOR_LOADED=1\n", + ); const wrapperPath = join(scriptDir, "nemoclaw-start.sh"); writeFileSync( wrapperPath, @@ -1006,14 +1010,14 @@ EOF "#!/usr/bin/env bash", "set -euo pipefail", src.slice(start, end), - 'printf "LOADED=%s\\n" "${NEMOCLAW_TEST_SANDBOX_INIT_LOADED:-0}"', + 'printf "INIT_LOADED=%s SUPERVISOR_LOADED=%s\\n" "${NEMOCLAW_TEST_SANDBOX_INIT_LOADED:-0}" "${NEMOCLAW_TEST_GATEWAY_SUPERVISOR_LOADED:-0}"', ].join("\n"), { mode: 0o700 }, ); try { const result = execFileSync("bash", [wrapperPath], { encoding: "utf-8" }).trim(); - expect(result).toBe("LOADED=1"); + expect(result).toBe("INIT_LOADED=1 SUPERVISOR_LOADED=1"); } finally { rmSync(workDir, { recursive: true, force: true }); } diff --git a/test/sandbox-provisioning-helper-permissions.test.ts b/test/sandbox-provisioning-helper-permissions.test.ts new file mode 100644 index 00000000000..6c9aa4e6844 --- /dev/null +++ b/test/sandbox-provisioning-helper-permissions.test.ts @@ -0,0 +1,199 @@ +// 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 ROOT = path.resolve(import.meta.dirname, ".."); +const DOCKERFILE = path.join(ROOT, "Dockerfile"); + +function dockerRunCommandBetween( + dockerfile: string, + startMarker: string, + endMarker: string, +): string { + const start = dockerfile.indexOf(startMarker); + const end = dockerfile.indexOf(endMarker, start); + expect(start, `Expected Dockerfile start marker: ${startMarker}`).toBeGreaterThanOrEqual(0); + expect(end, `Expected Dockerfile end marker: ${endMarker}`).toBeGreaterThan(start); + const runIndex = dockerfile.indexOf("RUN ", start); + expect(runIndex, `Expected RUN instruction after ${startMarker}`).toBeGreaterThanOrEqual(start); + expect(runIndex, `Expected RUN instruction before ${endMarker}`).toBeLessThan(end); + const runBlock = dockerfile.slice(runIndex, end).split("\n"); + const completeLineIndex = runBlock.findIndex((line) => !line.trimEnd().endsWith("\\")); + expect( + completeLineIndex, + `Expected complete RUN instruction before ${endMarker}`, + ).toBeGreaterThanOrEqual(0); + const runLines = runBlock.slice(0, completeLineIndex + 1); + return runLines + .join("\n") + .trim() + .replace(/^RUN\s+/, "") + .replace(/\\\n/g, " "); +} + +function runLoggedDockerShell(command: string, tmp: string, functionDefs: string[] = []) { + const logPath = path.join(tmp, "calls.log"); + const scriptPath = path.join(tmp, "run-docker-block.sh"); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `call_log=${JSON.stringify(logPath)}`, + ...functionDefs, + command, + ].join("\n"), + { mode: 0o700 }, + ); + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000 }); + return { result }; +} + +describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () => { + it("normalizes copied blueprint permissions before non-root config generation", () => { + const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-blueprint-mode-")); + const blueprintRoot = path.join(tmp, "opt", "nemoclaw-blueprint"); + const nemoclawRoot = path.join(tmp, "opt", "nemoclaw"); + const manifestDir = path.join(blueprintRoot, "model-specific-setup", "openclaw"); + const manifestPath = path.join(manifestDir, "kimi-k2.6-managed-inference.json"); + const pluginPackageJson = path.join(nemoclawRoot, "package.json"); + + try { + fs.mkdirSync(manifestDir, { recursive: true }); + fs.writeFileSync(manifestPath, "{}\n", { mode: 0o600 }); + fs.chmodSync(path.join(blueprintRoot, "model-specific-setup"), 0o700); + fs.chmodSync(manifestDir, 0o700); + fs.chmodSync(manifestPath, 0o600); + fs.mkdirSync(nemoclawRoot, { recursive: true }); + fs.writeFileSync(pluginPackageJson, "{}\n", { mode: 0o400 }); + fs.chmodSync(nemoclawRoot, 0o700); + fs.chmodSync(pluginPackageJson, 0o400); + + const command = dockerRunCommandBetween( + dockerfile, + "# Copy built plugin and blueprint", + "# Install runtime dependencies only", + ) + .replaceAll("/opt/nemoclaw-blueprint", "__BLUEPRINT__") + .replaceAll("/opt/nemoclaw", nemoclawRoot) + .replaceAll("__BLUEPRINT__", blueprintRoot); + const { result } = runLoggedDockerShell(command, tmp); + + expect(result.status, result.stderr).toBe(0); + expect((fs.statSync(manifestDir).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(manifestPath).mode & 0o777).toString(8)).toBe("644"); + expect((fs.statSync(nemoclawRoot).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(pluginPackageJson).mode & 0o777).toString(8)).toBe("444"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("normalizes the config generator mode after Docker COPY preserves a restrictive source mode", () => { + const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-helper-mode-")); + const localBin = path.join(tmp, "usr", "local", "bin"); + const localLib = path.join(tmp, "usr", "local", "lib", "nemoclaw"); + const localShare = path.join(tmp, "usr", "local", "share", "nemoclaw"); + const localSrc = path.join(tmp, "src"); + const localScripts = path.join(tmp, "scripts"); + const generatorPath = path.join(localScripts, "generate-openclaw-config.mts"); + const applierPath = path.join( + localSrc, + "lib", + "messaging", + "applier", + "build", + "messaging-build-applier.mts", + ); + const messagingHookPath = path.join( + localSrc, + "lib", + "messaging", + "channels", + "fixture", + "hooks", + "example.ts", + ); + const pluginDir = path.join(localShare, "openclaw-plugins", "kimi-inference-compat"); + const pluginFile = path.join(pluginDir, "index.js"); + const nestedPluginDir = path.join(pluginDir, "lib"); + const nestedPluginFile = path.join(nestedPluginDir, "helper.js"); + const gatewayControlPath = path.join(localBin, "nemoclaw-gateway-control"); + const gatewaySupervisorPath = path.join(localLib, "gateway-supervisor.sh"); + const stateDirGuardPath = path.join(localLib, "state-dir-guard.py"); + const configGuardPath = path.join(localLib, "openclaw-config-guard.py"); + const managedGatewayControlPath = path.join(localLib, "managed-gateway-control.py"); + const files = [ + path.join(localBin, "nemoclaw-start"), + path.join(localBin, "nemoclaw-codex-acp"), + gatewayControlPath, + path.join(localLib, "sandbox-init.sh"), + path.join(localLib, "sandbox-rlimits.sh"), + gatewaySupervisorPath, + stateDirGuardPath, + configGuardPath, + managedGatewayControlPath, + path.join(localLib, "openclaw_device_approval_policy.py"), + path.join(localLib, "clean_runtime_shell_env_shim.py"), + generatorPath, + applierPath, + messagingHookPath, + path.join(localLib, "ws-proxy-fix.js"), + pluginFile, + nestedPluginFile, + ]; + + try { + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(localLib, { recursive: true }); + fs.mkdirSync(localScripts, { recursive: true }); + fs.mkdirSync(nestedPluginDir, { recursive: true }); + fs.mkdirSync(path.dirname(applierPath), { recursive: true }); + fs.mkdirSync(path.dirname(messagingHookPath), { recursive: true }); + for (const file of files) { + fs.writeFileSync(file, "# fixture\n", { mode: 0o600 }); + fs.chmodSync(file, 0o600); + } + + const command = dockerRunCommandBetween( + dockerfile, + "# Copy startup script and shared sandbox initialisation library", + "# Build args for config that varies per deployment.", + ) + .replaceAll("/usr/local/bin", localBin) + .replaceAll("/usr/local/lib/nemoclaw", localLib) + .replaceAll("/usr/local/share/nemoclaw", localShare) + .replaceAll("/src", localSrc) + .replaceAll("/scripts", localScripts); + const { result } = runLoggedDockerShell(command, tmp, ["chown() { :; }"]); + + expect(result.status, result.stderr).toBe(0); + expect((fs.statSync(generatorPath).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(applierPath).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(messagingHookPath).mode & 0o777).toString(8)).toBe("644"); + expect( + ( + fs.statSync(path.join(localLib, "openclaw_device_approval_policy.py")).mode & 0o777 + ).toString(8), + ).toBe("644"); + expect((fs.statSync(pluginDir).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(pluginFile).mode & 0o777).toString(8)).toBe("644"); + expect((fs.statSync(nestedPluginDir).mode & 0o777).toString(8)).toBe("755"); + expect((fs.statSync(nestedPluginFile).mode & 0o777).toString(8)).toBe("644"); + expect((fs.statSync(gatewayControlPath).mode & 0o777).toString(8)).toBe("700"); + expect((fs.statSync(gatewaySupervisorPath).mode & 0o777).toString(8)).toBe("444"); + expect((fs.statSync(stateDirGuardPath).mode & 0o777).toString(8)).toBe("500"); + expect((fs.statSync(configGuardPath).mode & 0o777).toString(8)).toBe("500"); + expect((fs.statSync(managedGatewayControlPath).mode & 0o777).toString(8)).toBe("500"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/sandbox-provisioning.test.ts b/test/sandbox-provisioning.test.ts index 7e6ab20ab62..725fc961ba2 100644 --- a/test/sandbox-provisioning.test.ts +++ b/test/sandbox-provisioning.test.ts @@ -147,7 +147,7 @@ function runOpenclawRepairLayoutCase(legacy: boolean) { const cleanupBlock = dockerRunCommandBetween( dockerfile, "# Flatten stale published base images", - "# Stale-base fallback for the gateway-in-sandbox-group setup", + "# Stale-base fallback for the gateway/root-in-sandbox-group setup", ); const permissionBlock = dockerRunCommandBetween( dockerfile, @@ -224,6 +224,39 @@ function runOpenclawRepairLayoutCase(legacy: boolean) { } } +function runOpenclawUserSetupBlock() { + const dockerfile = fs.readFileSync(DOCKERFILE_BASE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-users-")); + const sandboxRoot = path.join(tmp, "sandbox"); + const command = dockerRunCommandBetween( + dockerfile, + "# Create sandbox user (matches OpenShell convention)", + "# Create .openclaw with all state subdirs directly", + ).replaceAll("/sandbox", sandboxRoot); + const result = runLoggedDockerShell(command, tmp, [ + 'groupadd() { printf "groupadd %s\\n" "$*" >> "$call_log"; }', + 'useradd() { printf "useradd %s\\n" "$*" >> "$call_log"; }', + 'usermod() { printf "usermod %s\\n" "$*" >> "$call_log"; }', + 'chown() { printf "chown %s\\n" "$*" >> "$call_log"; }', + ]); + return { ...result, tmp, sandboxRoot }; +} + +function runOpenclawStaleGroupFallback() { + const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-groups-")); + const command = dockerRunCommandBetween( + dockerfile, + "# Stale-base fallback for the gateway/root-in-sandbox-group setup", + "# Keep the image readable to the root entrypoint", + ); + const result = runLoggedDockerShell(command, tmp, [ + 'id() { case "$*" in "gateway"|"sandbox"|"root") return 0 ;; "-nG gateway") printf "gateway\\n" ;; "-nG root") printf "root\\n" ;; *) return 1 ;; esac; }', + 'usermod() { printf "usermod %s\\n" "$*" >> "$call_log"; }', + ]); + return { ...result, tmp }; +} + describe("sandbox provisioning: runtime npm online state", () => { it("replays the Dockerfile ENV directives so the runtime image inherits NPM_CONFIG_OFFLINE=false", () => { const exports = collectDockerfileEnvExports(DOCKERFILE); @@ -336,6 +369,10 @@ function collectDockerfileEnvExports(file: string): string[] { return dockerfileEnvDirectives(text).flatMap(envDirectiveToExports); } +function linuxProcStat(pid: string, starttime: string, ppid = "1", state = "S"): string { + return `${pid} (openclaw) ${state} ${ppid} ${Array(17).fill("0").join(" ")} ${starttime}\n`; +} + function stageDockerfileUntil(file: string, runMarker: string): string[] { const text = fs.readFileSync(file, "utf-8"); const cutoff = text.indexOf(runMarker); @@ -409,24 +446,41 @@ describe("sandbox provisioning: image health checks (#1430)", () => { // failing the container outright — it falls back to verifying that the // OpenClaw gateway process is still alive in this container. describe("falls back to local liveness when the in-container dashboard port has no listener (#3975)", () => { + const nulArgv = (...argv: string[]) => `${argv.join("\0")}\0`; + const unterminatedArgv = (...argv: string[]) => argv.join("\0"); + const npmGatewayCmdline = nulArgv( + "node", + "/usr/local/lib/node_modules/openclaw/openclaw.mjs", + "gateway", + "run", + "--port", + "18789", + ); + function runProductionHealthProbe({ curlExit, - pgrepExit, + gatewayCmdline = npmGatewayCmdline, gatewayLog = "gateway log line\n", // The /tmp/nemoclaw-gateway-local marker is dropped by nemoclaw-start // only when this container runs the in-container OpenClaw gateway. Most // probes here exercise that path, so default it to present. gatewayLocalMarker = true, + recordedStartIdentity = "12345", + observedStartIdentity = "12345", }: { curlExit: number; - pgrepExit: number; + gatewayCmdline?: string | null; gatewayLog?: string; gatewayLocalMarker?: boolean; + recordedStartIdentity?: string; + observedStartIdentity?: string; }) { const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-health-fallback-")); const logPath = path.join(tmp, "gateway.log"); const markerPath = path.join(tmp, "nemoclaw-gateway-local"); + const pidPath = path.join(tmp, "nemoclaw-gateway.pid"); + const procRoot = path.join(tmp, "proc"); const rawCommand = dockerHealthCommandBetween( dockerfile, "# Health check: poll the gateway's /health endpoint", @@ -434,7 +488,9 @@ describe("sandbox provisioning: image health checks (#1430)", () => { ); const command = rawCommand .replaceAll("/tmp/gateway.log", logPath) - .replaceAll("/tmp/nemoclaw-gateway-local", markerPath); + .replaceAll("/tmp/nemoclaw-gateway-local", markerPath) + .replaceAll("/tmp/nemoclaw-gateway.pid", pidPath) + .replaceAll("/proc/", `${procRoot}/`); if (gatewayLog !== "") { fs.writeFileSync(logPath, gatewayLog); @@ -442,11 +498,22 @@ describe("sandbox provisioning: image health checks (#1430)", () => { if (gatewayLocalMarker) { fs.writeFileSync(markerPath, ""); } + gatewayCmdline === null + ? undefined + : (() => { + const pid = "4242"; + fs.mkdirSync(path.join(procRoot, pid), { recursive: true }); + fs.writeFileSync( + path.join(procRoot, pid, "stat"), + linuxProcStat(pid, observedStartIdentity), + ); + fs.writeFileSync(path.join(procRoot, pid, "cmdline"), gatewayCmdline); + fs.writeFileSync(pidPath, `${pid} ${recordedStartIdentity}\n`); + })(); try { const probe = runLoggedDockerShell(command, tmp, [ `curl() { printf "curl %s\\n" "$*" >> "$call_log"; return ${curlExit}; }`, - `pgrep() { printf "pgrep %s\\n" "$*" >> "$call_log"; return ${pgrepExit}; }`, ]); return probe; } finally { @@ -455,154 +522,117 @@ describe("sandbox provisioning: image health checks (#1430)", () => { } it("reports healthy when in-container curl works (Docker-driver / standalone)", () => { - const probe = runProductionHealthProbe({ curlExit: 0, pgrepExit: 1, gatewayLog: "" }); + const probe = runProductionHealthProbe({ + curlExit: 0, + gatewayCmdline: null, + gatewayLog: "", + }); expect(probe.result.status).toBe(0); expect(probe.calls).toContain("curl"); - // Fast path: should not consult pgrep at all. - expect(probe.calls).not.toContain("pgrep"); }); - it("reports healthy when curl gets connection refused but openclaw is alive and started (DGX Spark / OpenShell-managed)", () => { - const probe = runProductionHealthProbe({ curlExit: 7, pgrepExit: 0 }); + it("reports healthy when curl gets connection refused but the tracked npm OpenClaw gateway is alive", () => { + const probe = runProductionHealthProbe({ curlExit: 7 }); expect(probe.result.status).toBe(0); expect(probe.calls).toContain("curl"); - // --ignore-ancestors prevents pgrep from self-matching the - // healthcheck shell whose argv contains the gateway pattern. - // The [ -] class matches both `openclaw gateway` (launcher) and - // `openclaw-gateway` (re-execed binary). Bare `openclaw` is verified - // through the recorded PID fallback below so unrelated CLI invocations - // cannot keep the container healthy. - expect(probe.calls).toContain("pgrep --ignore-ancestors -f openclaw[ -]gateway"); }); - it("uses a pgrep liveness pattern that matches gateway argv and rewritten titles but not ordinary openclaw CLI use (#4710)", () => { - const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); - const match = dockerfile.match(/pgrep --ignore-ancestors -f '([^']+)'/); - const pattern = match?.[1] ?? "$.^"; - const matches = (cmdline: string) => - spawnSync("grep", ["-qE", pattern], { input: cmdline, encoding: "utf-8" }).status === 0; - - // The launcher argv and legacy rewritten-title form must match. - expect(matches("node /usr/local/bin/openclaw gateway run --port 18789")).toBe(true); - expect(matches("openclaw-gateway")).toBe(true); - - // Bare `openclaw` and ordinary agent CLI invocations must not satisfy the - // pgrep liveness probe; the #4952 path below checks bare gateway argv - // through the recorded PID instead. - expect(matches("openclaw")).toBe(false); - expect(matches("openclaw plugins registry --refresh")).toBe(false); - expect(matches("node /usr/local/bin/openclaw devices list")).toBe(false); - expect(matches("vim openclaw-notes.txt")).toBe(false); + it("rejects a live PID whose start identity differs from the recorded gateway", () => { + const probe = runProductionHealthProbe({ + curlExit: 7, + recordedStartIdentity: "12345", + observedStartIdentity: "67890", + }); + + expect(probe.result.status).toBe(1); }); it("reports unhealthy when curl times out (wedged HTTP server, not namespace mismatch)", () => { // A connect timeout means a listener exists but is not responding, // e.g. a wedged HTTP server. We deliberately do not fall back to the // process check there — Docker should restart the container. - const probe = runProductionHealthProbe({ curlExit: 28, pgrepExit: 0 }); + const probe = runProductionHealthProbe({ curlExit: 28, gatewayCmdline: null }); expect(probe.result.status).toBe(1); - expect(probe.calls).not.toContain("pgrep"); }); it("reports unhealthy when curl gets connection refused and openclaw is not running", () => { - const probe = runProductionHealthProbe({ curlExit: 7, pgrepExit: 1 }); + const probe = runProductionHealthProbe({ curlExit: 7, gatewayCmdline: null }); expect(probe.result.status).toBe(1); }); it("reports unhealthy when curl gets connection refused and the gateway log was never written (openclaw never started)", () => { - const probe = runProductionHealthProbe({ curlExit: 7, pgrepExit: 0, gatewayLog: "" }); + const probe = runProductionHealthProbe({ curlExit: 7, gatewayLog: "" }); expect(probe.result.status).toBe(1); }); it("does not fall back when curl reports an HTTP error (gateway answered with failure)", () => { - const probe = runProductionHealthProbe({ curlExit: 22, pgrepExit: 0 }); + const probe = runProductionHealthProbe({ curlExit: 22, gatewayCmdline: null }); expect(probe.result.status).toBe(1); // HTTP errors from the in-container probe should bypass the fallback; // a 4xx/5xx means the gateway is reachable and unhappy, not a - // namespace mismatch — so pgrep should not run. - expect(probe.calls).not.toContain("pgrep"); + // namespace mismatch. }); // #4503: OpenShell docker-driver sandboxes deliver the OpenClaw gateway // outside this container's network namespace (it runs on the host), so // nemoclaw-start never drops the /tmp/nemoclaw-gateway-local marker. The - // in-container curl gets connection-refused and the in-container pgrep - // finds no gateway process, yet `nemoclaw status`/OpenShell report Ready. + // in-container curl gets connection-refused and no in-container process + // can prove gateway liveness, yet `nemoclaw status`/OpenShell report Ready. // Without the marker the healthcheck must NOT mark the container unhealthy // off a signal it cannot observe. describe("does not falsely fail when the gateway runs outside this container's namespace (#4503)", () => { it("reports healthy on curl exit 7 with no in-container gateway process when the marker is absent", () => { const probe = runProductionHealthProbe({ curlExit: 7, - pgrepExit: 1, + gatewayCmdline: null, gatewayLog: "gateway log line\n", gatewayLocalMarker: false, }); expect(probe.result.status).toBe(0); - // The process-name fallback is meaningless out-of-namespace, so the - // healthcheck must short-circuit before consulting pgrep. - expect(probe.calls).not.toContain("pgrep"); }); it("reports healthy on curl exit 7 even when no gateway log exists and the marker is absent", () => { const probe = runProductionHealthProbe({ curlExit: 7, - pgrepExit: 1, + gatewayCmdline: null, gatewayLog: "", gatewayLocalMarker: false, }); expect(probe.result.status).toBe(0); - expect(probe.calls).not.toContain("pgrep"); }); it("still reports unhealthy on a wedged listener (curl exit 28) regardless of the marker", () => { const probe = runProductionHealthProbe({ curlExit: 28, - pgrepExit: 0, gatewayLocalMarker: false, }); expect(probe.result.status).toBe(1); - expect(probe.calls).not.toContain("pgrep"); }); }); - // #4952: recent OpenClaw (v0.0.44 / 2026.5.18+) re-execs the long-running - // gateway into a process whose argv is plain `openclaw` — no `gateway` - // token at all (see the gateway_pid() helper in - // probe fails (connection refused, exit 7) on runtime shapes where the - // dashboard port lives outside this namespace, so the healthcheck falls - // back to the in-container gateway-liveness check. A pgrep that only - // matches `openclaw[ -]gateway` cannot see the re-execed plain-`openclaw` - // process, so the marker-present container is reported permanently - // unhealthy even though the gateway is alive and serving. - // - // The fallback must stay gateway-specific: matching *any* process named - // `openclaw` would keep Docker green when the real gateway has died but an - // unrelated `openclaw` one-shot (e.g. `openclaw agent ...`) is running, - // defeating restart/self-healing. So nemoclaw-start records the live - // gateway PID in /tmp/nemoclaw-gateway.pid and the fallback confirms THAT - // pid is still a live `openclaw` process. - // - // Unlike runProductionHealthProbe above (which forces pgrep's exit code - // and therefore can never exercise the pattern), this drives a pgrep mock - // that matches its pattern against a simulated process table and a ps mock - // that resolves the recorded PID — so the probe's outcome depends on the - // real argv shape AND on whether the recorded gateway PID is alive. + // #4952: OpenClaw can rewrite the gateway argv to a bare process title. + // Exercise exact NUL-delimited launcher/title shapes against the recorded + // PID and kernel start identity so unrelated OpenClaw processes cannot + // keep a dead gateway container healthy. describe("matches the re-execed plain-`openclaw` gateway argv (#4952)", () => { - // procTable entries are `comm|args`: `pgrep -f PAT` matches PAT (ERE) - // against args; bare `pgrep PAT` matches PAT (ERE) against comm. - // psTable maps a recorded PID to the `comm` that `ps -p <pid> -o comm=` - // returns (an absent PID models a dead/reused process: empty output). function runHealthProbe({ - procTable = [], gatewayPid = null, - psTable = {}, + gatewayCmdline = nulArgv("openclaw"), + processPresent = true, + recordedStart = "12345", + observedStart = "12345", + observedStartAfter, + observedState = "S", curlExit = 7, gatewayLog = "gateway log line\n", }: { - procTable?: string[]; gatewayPid?: string | null; - psTable?: Record<string, string>; + gatewayCmdline?: string | null; + processPresent?: boolean; + recordedStart?: string; + observedStart?: string; + observedStartAfter?: string; + observedState?: string; curlExit?: number; gatewayLog?: string; }) { @@ -611,6 +641,8 @@ describe("sandbox provisioning: image health checks (#1430)", () => { const logPath = path.join(tmp, "gateway.log"); const markerPath = path.join(tmp, "nemoclaw-gateway-local"); const pidPath = path.join(tmp, "nemoclaw-gateway.pid"); + const procRoot = path.join(tmp, "proc"); + let identityChangePrelude: string[] = []; const command = dockerHealthCommandBetween( dockerfile, "# Health check: poll the gateway's /health endpoint", @@ -618,7 +650,8 @@ describe("sandbox provisioning: image health checks (#1430)", () => { ) .replaceAll("/tmp/gateway.log", logPath) .replaceAll("/tmp/nemoclaw-gateway-local", markerPath) - .replaceAll("/tmp/nemoclaw-gateway.pid", pidPath); + .replaceAll("/tmp/nemoclaw-gateway.pid", pidPath) + .replaceAll("/proc/", `${procRoot}/`); // Gateway is up and the marker is present: this container runs the // in-container gateway, so the liveness fallback is meaningful. @@ -627,126 +660,164 @@ describe("sandbox provisioning: image health checks (#1430)", () => { } fs.writeFileSync(markerPath, ""); if (gatewayPid !== null) { - fs.writeFileSync(pidPath, `${gatewayPid}\n`); + const statPath = path.join(procRoot, gatewayPid, "stat"); + const cmdlinePath = path.join(procRoot, gatewayPid, "cmdline"); + const changesIdentityDuringCmdline = + processPresent && gatewayCmdline !== null && observedStartAfter !== undefined; + fs.writeFileSync(pidPath, `${gatewayPid} ${recordedStart}\n`); + processPresent && fs.mkdirSync(path.join(procRoot, gatewayPid), { recursive: true }); + processPresent && + fs.writeFileSync( + statPath, + linuxProcStat(gatewayPid, observedStart, "1", observedState), + ); + changesIdentityDuringCmdline && + expect(spawnSync("mkfifo", [cmdlinePath], { encoding: "utf-8" }).status).toBe(0); + processPresent && + gatewayCmdline !== null && + !changesIdentityDuringCmdline && + fs.writeFileSync(cmdlinePath, gatewayCmdline); + identityChangePrelude = changesIdentityDuringCmdline + ? [ + `python3 -c 'import pathlib,sys; stream = open(sys.argv[1], "wb"); stream.write(bytes.fromhex(sys.argv[2])); stream.flush(); pathlib.Path(sys.argv[3]).write_bytes(bytes.fromhex(sys.argv[4])); stream.close()' ${JSON.stringify(cmdlinePath)} ${Buffer.from(gatewayCmdline ?? "").toString("hex")} ${JSON.stringify(statPath)} ${Buffer.from(linuxProcStat(gatewayPid, observedStartAfter ?? observedStart, "1", observedState)).toString("hex")} &`, + ] + : []; } - const pgrepMock = [ - "pgrep() {", - ' printf "pgrep %s\\n" "$*" >> "$call_log";', - " local use_f=0 exact=0 pat='';", - ' for a in "$@"; do', - ' case "$a" in', - " --ignore-ancestors) ;;", - " -f) use_f=1 ;;", - " -x) exact=1 ;;", - " -*) ;;", - ' *) pat="$a" ;;', - " esac;", - " done;", - ' local found=1 oldifs="$IFS" line comm args;', - " IFS=$'\\n';", - " for line in $FAKE_PROCS; do", - ' [ -n "$line" ] || continue;', - ' comm="${line%%|*}"; args="${line#*|}";', - ' if [ "$use_f" = 1 ]; then', - ' printf "%s" "$args" | grep -Eq "$pat" && { found=0; break; };', - ' elif [ "$exact" = 1 ]; then', - ' [ "$comm" = "$pat" ] && { found=0; break; };', - " else", - ' printf "%s" "$comm" | grep -Eq "$pat" && { found=0; break; };', - " fi;", - " done;", - ' IFS="$oldifs"; return $found;', - "}", - ].join("\n"); - - // `ps -p <pid> -o comm=` → the recorded process name, empty when the - // PID is not in the table (dead/reused). - const psMock = [ - "ps() {", - ' printf "ps %s\\n" "$*" >> "$call_log";', - ' local pid="" prev="";', - ' for a in "$@"; do [ "$prev" = "-p" ] && pid="$a"; prev="$a"; done;', - " local line oldifs=\"$IFS\"; IFS=$'\\n';", - " for line in $PS_TABLE; do", - ' [ -n "$line" ] || continue;', - ' if [ "${line%%=*}" = "$pid" ]; then printf "%s\\n" "${line#*=}"; IFS="$oldifs"; return 0; fi;', - " done;", - ' IFS="$oldifs"; return 1;', - "}", - ].join("\n"); - - const psEnv = Object.entries(psTable) - .map(([pid, comm]) => `${pid}=${comm}`) - .join("\n"); - try { - return runLoggedDockerShell( - command, - tmp, - [ - `curl() { printf "curl %s\\n" "$*" >> "$call_log"; return ${curlExit}; }`, - pgrepMock, - psMock, - ], - { FAKE_PROCS: procTable.join("\n"), PS_TABLE: psEnv }, - ); + return runLoggedDockerShell(command, tmp, [ + ...identityChangePrelude, + `curl() { printf "curl %s\\n" "$*" >> "$call_log"; return ${curlExit}; }`, + ]); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } } - it("reports healthy when the live gateway re-execed to a plain `openclaw` argv", () => { - // The gateway carries no `gateway` token in its argv (the #4952 - // shape); liveness is proven by the recorded PID resolving to an - // `openclaw` process. - const probe = runHealthProbe({ - procTable: ["openclaw|openclaw"], - gatewayPid: "4242", - psTable: { "4242": "openclaw" }, - }); + it.each([ + ["a bare rewritten title", nulArgv("openclaw")], + ["the legacy rewritten title", nulArgv("openclaw-gateway")], + ["a padded rewritten title", "openclaw-gateway\0\0\0"], + [ + "the direct launcher", + nulArgv("/usr/local/bin/openclaw", "gateway", "run", "--port", "18789"), + ], + [ + "the npm-installed Node launcher", + nulArgv( + "/usr/local/bin/node", + "/usr/local/lib/node_modules/openclaw/openclaw.mjs", + "gateway", + "run", + "--port", + "18789", + ), + ], + [ + "the equals-form gateway port", + nulArgv("nodejs", "/usr/local/bin/openclaw", "gateway", "run", "--port=18789"), + ], + ])("reports healthy for %s", (_label, gatewayCmdline) => { + const probe = runHealthProbe({ gatewayPid: "4242", gatewayCmdline }); expect(probe.result.status).toBe(0); }); - it("still reports healthy for the launcher-form `openclaw gateway run` argv", () => { - // pgrep matches the gateway-token form directly; no PID lookup needed. - const probe = runHealthProbe({ procTable: ["openclaw|openclaw gateway run --port 18789"] }); - expect(probe.result.status).toBe(0); + it("reports unhealthy when no openclaw process is alive and no gateway PID was recorded", () => { + const probe = runHealthProbe({ gatewayPid: null }); + expect(probe.result.status).toBe(1); }); - it("still reports healthy for the legacy re-execed `openclaw-gateway` argv", () => { + // The tightening that closes the self-healing gap: an unrelated + // `openclaw` one-shot is running (a bare `pgrep -x openclaw` would have + // matched it and falsely reported healthy), but the recorded gateway PID + // is dead. The container must report unhealthy so Docker restarts it. + it("reports unhealthy when the recorded gateway PID is dead even if a non-gateway `openclaw` process exists", () => { const probe = runHealthProbe({ - procTable: ["openclaw-gateway|openclaw-gateway --port 18789"], + gatewayPid: "9999", + processPresent: false, }); - expect(probe.result.status).toBe(0); + expect(probe.result.status).not.toBe(0); }); - it("reports unhealthy when no openclaw process is alive and no gateway PID was recorded", () => { + it("reports unhealthy when the recorded gateway PID was reused by a non-openclaw process", () => { const probe = runHealthProbe({ - procTable: ["bash|bash /usr/local/bin/nemoclaw-start"], - gatewayPid: null, + gatewayPid: "4242", + gatewayCmdline: nulArgv("bash"), }); expect(probe.result.status).toBe(1); }); - // The tightening that closes the self-healing gap: an unrelated - // `openclaw` one-shot is running (a bare `pgrep -x openclaw` would have - // matched it and falsely reported healthy), but the recorded gateway PID - // is dead. The container must report unhealthy so Docker restarts it. - it("reports unhealthy when the recorded gateway PID is dead even if a non-gateway `openclaw` process exists", () => { + it.each([ + [ + "an unrelated Node script", + nulArgv("node", "/tmp/openclaw-helper.mjs", "gateway", "run", "--port", "18789"), + ], + [ + "a same-basename Node script outside the installed path", + nulArgv("node", "/tmp/openclaw.mjs", "gateway", "run", "--port", "18789"), + ], + [ + "a same-basename direct launcher outside the installed path", + nulArgv("/tmp/openclaw", "gateway", "run", "--port", "18789"), + ], + ["a same-basename rewritten title outside the installed path", nulArgv("/tmp/openclaw")], + [ + "a same-basename Node interpreter outside an installed path", + nulArgv("/tmp/node", "/usr/local/bin/openclaw", "gateway", "run", "--port", "18789"), + ], + ["an OpenClaw one-shot command", nulArgv("openclaw", "agent", "run-task")], + [ + "an OpenClaw gateway on the wrong port", + nulArgv( + "node", + "/usr/local/lib/node_modules/openclaw/openclaw.mjs", + "gateway", + "run", + "--port", + "19000", + ), + ], + [ + "a launcher with a trailing empty argument", + nulArgv("node", "/usr/local/bin/openclaw", "gateway", "run", "--port", "18789", ""), + ], + [ + "an unterminated launcher cmdline", + unterminatedArgv("node", "/usr/local/bin/openclaw", "gateway", "run", "--port", "18789"), + ], + ["an unterminated rewritten title", "openclaw-gateway"], + ["an empty cmdline", ""], + ["a missing cmdline", null], + ])("reports unhealthy for %s", (_label, gatewayCmdline) => { + const probe = runHealthProbe({ gatewayPid: "4242", gatewayCmdline }); + expect(probe.result.status).toBe(1); + }); + + it("reports unhealthy when an OpenClaw-looking reused PID has a different starttime", () => { const probe = runHealthProbe({ - procTable: ["openclaw|openclaw agent run-task"], - gatewayPid: "9999", - psTable: {}, // 9999 is gone + gatewayPid: "4242", + recordedStart: "12345", + observedStart: "99999", + gatewayCmdline: nulArgv("openclaw"), }); expect(probe.result.status).toBe(1); }); - it("reports unhealthy when the recorded gateway PID was reused by a non-openclaw process", () => { + it("reports unhealthy when the PID identity changes while cmdline is read", () => { + const probe = runHealthProbe({ + gatewayPid: "4242", + observedStart: "12345", + observedStartAfter: "99999", + gatewayCmdline: nulArgv("openclaw"), + }); + expect(probe.result.status).toBe(1); + }); + + it("reports unhealthy when the recorded gateway identity is a zombie", () => { const probe = runHealthProbe({ - procTable: ["bash|bash"], gatewayPid: "4242", - psTable: { "4242": "bash" }, // PID reuse + observedState: "Z", + gatewayCmdline: nulArgv("openclaw"), }); expect(probe.result.status).toBe(1); }); @@ -775,6 +846,22 @@ describe("sandbox provisioning: image health checks (#1430)", () => { }); describe("sandbox provisioning: unified .openclaw layout (#2227)", () => { + it("keeps root in the sandbox group for capability-dropped lifecycle guards", () => { + const base = runOpenclawUserSetupBlock(); + const fallback = runOpenclawStaleGroupFallback(); + try { + expect(base.result.status, base.result.stderr).toBe(0); + expect(base.calls).toContain("usermod -aG sandbox gateway"); + expect(base.calls).toContain("usermod -aG sandbox root"); + expect(fallback.result.status, fallback.result.stderr).toBe(0); + expect(fallback.calls).toContain("usermod -aG sandbox gateway"); + expect(fallback.calls).toContain("usermod -aG sandbox root"); + } finally { + fs.rmSync(base.tmp, { recursive: true, force: true }); + fs.rmSync(fallback.tmp, { recursive: true, force: true }); + } + }); + it("uses targeted permission repair unless legacy migration ran", () => { const modern = runOpenclawRepairLayoutCase(false); expect(modern.cleanup.result.status).toBe(0); @@ -1089,142 +1176,65 @@ describe("sandbox provisioning: base runtime tools", () => { }); }); -describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () => { - it("normalizes copied blueprint permissions before non-root config generation", () => { - const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-blueprint-mode-")); - const blueprintRoot = path.join(tmp, "opt", "nemoclaw-blueprint"); - const nemoclawRoot = path.join(tmp, "opt", "nemoclaw"); - const manifestDir = path.join(blueprintRoot, "model-specific-setup", "openclaw"); - const manifestPath = path.join(manifestDir, "kimi-k2.6-managed-inference.json"); - const pluginPackageJson = path.join(nemoclawRoot, "package.json"); - - try { - fs.mkdirSync(manifestDir, { recursive: true }); - fs.writeFileSync(manifestPath, "{}\n", { mode: 0o600 }); - fs.chmodSync(path.join(blueprintRoot, "model-specific-setup"), 0o700); - fs.chmodSync(manifestDir, 0o700); - fs.chmodSync(manifestPath, 0o600); - fs.mkdirSync(nemoclawRoot, { recursive: true }); - fs.writeFileSync(pluginPackageJson, "{}\n", { mode: 0o400 }); - fs.chmodSync(nemoclawRoot, 0o700); - fs.chmodSync(pluginPackageJson, 0o400); - - const command = dockerRunCommandBetween( - dockerfile, - "# Copy built plugin and blueprint", - "# Install runtime dependencies only", - ) - .replaceAll("/opt/nemoclaw-blueprint", "__BLUEPRINT__") - .replaceAll("/opt/nemoclaw", nemoclawRoot) - .replaceAll("__BLUEPRINT__", blueprintRoot); - const { result } = runLoggedDockerShell(command, tmp); - - expect(result.status, result.stderr).toBe(0); - expect((fs.statSync(manifestDir).mode & 0o777).toString(8)).toBe("755"); - expect((fs.statSync(manifestPath).mode & 0o777).toString(8)).toBe("644"); - expect((fs.statSync(nemoclawRoot).mode & 0o777).toString(8)).toBe("755"); - expect((fs.statSync(pluginPackageJson).mode & 0o777).toString(8)).toBe("444"); - } finally { - fs.rmSync(tmp, { recursive: true, force: true }); - } - }); - - it("normalizes the config generator mode after Docker COPY preserves a restrictive source mode", () => { - const dockerfile = fs.readFileSync(DOCKERFILE, "utf-8"); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-helper-mode-")); +describe("Hermes sandbox provisioning", () => { + it("stages privileged lifecycle helpers with root-only Hermes image modes", () => { + const dockerfile = fs.readFileSync(HERMES_DOCKERFILE, "utf-8"); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-helper-modes-")); const localBin = path.join(tmp, "usr", "local", "bin"); const localLib = path.join(tmp, "usr", "local", "lib", "nemoclaw"); - const localShare = path.join(tmp, "usr", "local", "share", "nemoclaw"); - const localSrc = path.join(tmp, "src"); - const localScripts = path.join(tmp, "scripts"); - const generatorPath = path.join(localScripts, "generate-openclaw-config.mts"); - const applierPath = path.join( - localSrc, - "lib", - "messaging", - "applier", - "build", - "messaging-build-applier.mts", - ); - const messagingHookPath = path.join( - localSrc, - "lib", - "messaging", - "channels", - "fixture", - "hooks", - "example.ts", - ); - const pluginDir = path.join(localShare, "openclaw-plugins", "kimi-inference-compat"); - const pluginFile = path.join(pluginDir, "index.js"); - const nestedPluginDir = path.join(pluginDir, "lib"); - const nestedPluginFile = path.join(nestedPluginDir, "helper.js"); + const etcDir = path.join(tmp, "etc"); + const profileDir = path.join(etcDir, "profile.d"); + const bashrcPath = path.join(etcDir, "bash.bashrc"); + const gatewayControlPath = path.join(localBin, "nemoclaw-gateway-control"); + const gatewaySupervisorPath = path.join(localLib, "gateway-supervisor.sh"); + const stateDirGuardPath = path.join(localLib, "state-dir-guard.py"); + const managedGatewayControlPath = path.join(localLib, "managed-gateway-control.py"); const files = [ path.join(localBin, "nemoclaw-start"), - path.join(localBin, "nemoclaw-codex-acp"), + gatewayControlPath, path.join(localLib, "sandbox-init.sh"), + path.join(localLib, "validate-hermes-env-secret-boundary.py"), + path.join(localLib, "seed-hermes-dashboard-config.py"), + path.join(localLib, "hermes-runtime-config-guard.py"), + gatewaySupervisorPath, + stateDirGuardPath, + managedGatewayControlPath, path.join(localLib, "sandbox-rlimits.sh"), - path.join(localLib, "openclaw_device_approval_policy.py"), - path.join(localLib, "clean_runtime_shell_env_shim.py"), - generatorPath, - applierPath, - messagingHookPath, - path.join(localLib, "ws-proxy-fix.js"), - pluginFile, - nestedPluginFile, ]; + const command = dockerRunCommandBetween( + dockerfile, + "# Dockerfile.base is the source of truth for rlimit hooks.", + "# Wrap the hermes CLI", + ) + .replaceAll("/usr/local/bin", localBin) + .replaceAll("/usr/local/lib/nemoclaw", localLib) + .replaceAll("/etc/profile.d", profileDir) + .replaceAll("/etc/bash.bashrc", bashrcPath); try { fs.mkdirSync(localBin, { recursive: true }); fs.mkdirSync(localLib, { recursive: true }); - fs.mkdirSync(localScripts, { recursive: true }); - fs.mkdirSync(nestedPluginDir, { recursive: true }); - fs.mkdirSync(path.dirname(applierPath), { recursive: true }); - fs.mkdirSync(path.dirname(messagingHookPath), { recursive: true }); - for (const file of files) { - fs.writeFileSync(file, "# fixture\n", { mode: 0o600 }); - fs.chmodSync(file, 0o600); - } + fs.mkdirSync(etcDir, { recursive: true }); + fs.writeFileSync(bashrcPath, "# fixture\n", { mode: 0o600 }); + for (const file of files) fs.writeFileSync(file, "# fixture\n", { mode: 0o600 }); - const command = dockerRunCommandBetween( - dockerfile, - "# Copy startup script and shared sandbox initialisation library", - "# Build args for config that varies per deployment.", - ) - .replaceAll("/usr/local/bin", localBin) - .replaceAll("/usr/local/lib/nemoclaw", localLib) - .replaceAll("/usr/local/share/nemoclaw", localShare) - .replaceAll("/src", localSrc) - .replaceAll("/scripts", localScripts); - const { result } = runLoggedDockerShell(command, tmp); + const { result, calls } = runLoggedDockerShell(command, tmp, [ + 'chown() { printf "chown %s\\n" "$*" >> "$call_log"; }', + ]); expect(result.status, result.stderr).toBe(0); - const generatorMode = (fs.statSync(generatorPath).mode & 0o777).toString(8); - const applierMode = (fs.statSync(applierPath).mode & 0o777).toString(8); - const messagingHookMode = (fs.statSync(messagingHookPath).mode & 0o777).toString(8); - const approvalPolicyMode = ( - fs.statSync(path.join(localLib, "openclaw_device_approval_policy.py")).mode & 0o777 - ).toString(8); - const pluginDirMode = (fs.statSync(pluginDir).mode & 0o777).toString(8); - const pluginMode = (fs.statSync(pluginFile).mode & 0o777).toString(8); - const nestedPluginDirMode = (fs.statSync(nestedPluginDir).mode & 0o777).toString(8); - const nestedPluginMode = (fs.statSync(nestedPluginFile).mode & 0o777).toString(8); - expect(generatorMode).toBe("755"); - expect(applierMode).toBe("755"); - expect(messagingHookMode).toBe("644"); - expect(approvalPolicyMode).toBe("644"); - expect(pluginDirMode).toBe("755"); - expect(pluginMode).toBe("644"); - expect(nestedPluginDirMode).toBe("755"); - expect(nestedPluginMode).toBe("644"); + expect(calls).toContain( + `chown root:root ${gatewayControlPath} ${gatewaySupervisorPath} ${stateDirGuardPath} ${managedGatewayControlPath}`, + ); + expect((fs.statSync(gatewayControlPath).mode & 0o777).toString(8)).toBe("700"); + expect((fs.statSync(gatewaySupervisorPath).mode & 0o777).toString(8)).toBe("444"); + expect((fs.statSync(stateDirGuardPath).mode & 0o777).toString(8)).toBe("500"); + expect((fs.statSync(managedGatewayControlPath).mode & 0o777).toString(8)).toBe("500"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } }); -}); -describe("Hermes sandbox provisioning", () => { function runHermesPathValidation(pathEntriesBeforeManifest: string[] = []) { const dockerfile = fs.readFileSync(HERMES_DOCKERFILE, "utf-8"); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-path-")); diff --git a/test/sandbox-rlimit-hooks.test.ts b/test/sandbox-rlimit-hooks.test.ts index 08ae83a8684..c61b65615b7 100644 --- a/test/sandbox-rlimit-hooks.test.ts +++ b/test/sandbox-rlimit-hooks.test.ts @@ -222,6 +222,10 @@ function expectRlimitLibRejectsUnboundedPosixShNoFile(rlimitLib: string): void { const probe = [ "set -e", `. ${JSON.stringify(rlimitLib)}`, + // This probe isolates nofile validation. Host nproc hard/soft defaults vary + // (notably on macOS), so do not let an unrelated nproc diagnostic mask the + // deliberately unbounded nofile result asserted below. + '_nemoclaw_supports_resource_limit() { [ "$1" = "n" ]; }', 'current_nproc="$(command ulimit -u 2>/dev/null || printf "%s" 512)"', 'case "$current_nproc" in "" | *[!0-9]*) current_nproc=512 ;; esac', 'current_nofile="$(command ulimit -n 2>/dev/null || printf "%s" 0)"', @@ -404,7 +408,11 @@ describe("sandbox rlimit system hooks (#2173)", () => { const validator = path.join(localLib, "validate-hermes-env-secret-boundary.py"); const dashboardSeeder = path.join(localLib, "seed-hermes-dashboard-config.py"); const runtimeGuard = path.join(localLib, "hermes-runtime-config-guard.py"); + const gatewaySupervisor = path.join(localLib, "gateway-supervisor.sh"); + const stateDirGuard = path.join(localLib, "state-dir-guard.py"); + const managedGatewayControl = path.join(localLib, "managed-gateway-control.py"); const startBin = path.join(tmp, "nemoclaw-start"); + const gatewayControl = path.join(tmp, "nemoclaw-gateway-control"); const bashrc = path.join(tmp, "bash.bashrc"); const expectedRlimitShim = rlimitShim(rlimitLib); @@ -416,22 +424,33 @@ describe("sandbox rlimit system hooks (#2173)", () => { fs.writeFileSync(validator, "# validator fixture\n"); fs.writeFileSync(dashboardSeeder, "# dashboard seeder fixture\n"); fs.writeFileSync(runtimeGuard, "# runtime guard fixture\n"); + fs.writeFileSync(gatewaySupervisor, "# gateway supervisor fixture\n"); + fs.writeFileSync(stateDirGuard, "# state-dir guard fixture\n"); + fs.writeFileSync(managedGatewayControl, "# managed gateway control fixture\n"); fs.writeFileSync(startBin, "#!/usr/bin/env bash\n"); + fs.writeFileSync(gatewayControl, "#!/usr/bin/env sh\n"); fs.writeFileSync(bashrc, "# stale hermes bashrc\n"); - const command = dockerRunCommandBetween( + const replay = dockerRunCommandBetween( dockerfile, "# Copy startup script and the secret-boundary validator.", "# Wrap the hermes CLI", ) .replaceAll("/usr/local/bin/nemoclaw-start", startBin) + .replaceAll("/usr/local/bin/nemoclaw-gateway-control", gatewayControl) .replaceAll("/usr/local/lib/nemoclaw/sandbox-init.sh", initLib) + .replaceAll("/usr/local/lib/nemoclaw/gateway-supervisor.sh", gatewaySupervisor) .replaceAll("/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py", validator) .replaceAll("/usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py", dashboardSeeder) .replaceAll("/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", runtimeGuard) + .replaceAll("/usr/local/lib/nemoclaw/state-dir-guard.py", stateDirGuard) + .replaceAll("/usr/local/lib/nemoclaw/managed-gateway-control.py", managedGatewayControl) .replaceAll("/usr/local/lib/nemoclaw/sandbox-rlimits.sh", rlimitLib) .replaceAll("/etc/profile.d/nemoclaw-rlimits.sh", profileHook) .replaceAll("/etc/profile.d", path.dirname(profileHook)) .replaceAll("/etc/bash.bashrc", bashrc); + // The Docker image has a root:root group contract. macOS names gid 0 + // "wheel", so stub chown while preserving every chmod and hook write. + const command = ["chown() { :; }", replay].join("\n"); const result = runLoggedDockerShell(command, tmp); expect(result.status, result.stderr).toBe(0); diff --git a/test/seccomp-guard.test.ts b/test/seccomp-guard.test.ts index 9296675dc37..5bf4040e6d0 100644 --- a/test/seccomp-guard.test.ts +++ b/test/seccomp-guard.test.ts @@ -2,11 +2,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { spawnSync } from "node:child_process"; -import { describe, it, expect } from "vitest"; +import { describe, expect, it } from "vitest"; const START_SCRIPT = path.join(import.meta.dirname, "..", "scripts", "nemoclaw-start.sh"); const SECCOMP_GUARD_SOURCE = path.join( @@ -33,6 +33,16 @@ function extractRuntimeShellEnvSnippet(src: string): string { return `${src.slice(start, end).trimEnd()}\nwrite_runtime_shell_env`; } +function extractShellFunction(source: string, name: string): string { + const header = `${name}() {`; + const start = source.indexOf(header); + expect(start, `expected ${name} in nemoclaw-start.sh`).not.toBe(-1); + const body = source.slice(start + header.length); + const closing = body.match(/^}$/m); + expect(closing, `expected closing brace for ${name}`).not.toBeNull(); + return `${name}() {${body.slice(0, closing?.index ?? 0)}\n}`; +} + describe("Seccomp guard preload", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -62,14 +72,25 @@ describe("Seccomp guard preload", () => { `source ${JSON.stringify(path.join(import.meta.dirname, "..", "scripts", "lib", "sandbox-init.sh"))}`, 'emit_sandbox_sourced_file() { local target="$1"; cat > "$target"; chmod 444 "$target"; }', "NODE_OPTIONS='--require /already-loaded.js'", + "NODE_USE_ENV_PROXY=0", + extractShellFunction(src, "node_options_has_require"), + extractShellFunction(src, "append_node_require_once"), + `_SANDBOX_SAFETY_NET=${JSON.stringify(path.join(tempDir, "safety-net.js"))}`, + `_SANDBOX_SAFETY_NET_SOURCE=${JSON.stringify(SECCOMP_GUARD_SOURCE)}`, + `_PROXY_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "proxy-fix.js"))}`, + `_PROXY_FIX_SOURCE=${JSON.stringify(SECCOMP_GUARD_SOURCE)}`, + `_NEMOTRON_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "nemotron-fix.js"))}`, + `_NEMOTRON_FIX_SOURCE=${JSON.stringify(SECCOMP_GUARD_SOURCE)}`, + `_CIAO_GUARD_SCRIPT=${JSON.stringify(path.join(tempDir, "ciao-guard.js"))}`, + `_CIAO_GUARD_SOURCE=${JSON.stringify(SECCOMP_GUARD_SOURCE)}`, + `_WS_FIX_SCRIPT=${JSON.stringify(path.join(tempDir, "ws-fix.js"))}`, + `_WS_FIX_SOURCE=${JSON.stringify(path.join(tempDir, "missing-ws-source.js"))}`, block, 'PROXY_HOST="10.200.0.1"', 'PROXY_PORT="3128"', '_PROXY_URL="http://${PROXY_HOST}:${PROXY_PORT}"', '_NO_PROXY_VAL="localhost,127.0.0.1,::1,${PROXY_HOST}"', "_TOOL_REDIRECTS=()", - '_PROXY_FIX_SCRIPT="/tmp/nemoclaw-http-proxy-fix.js"', - '_NEMOTRON_FIX_SCRIPT="/tmp/nemoclaw-nemotron-inference-fix.js"', "set +u", persistBlock, "printf 'NODE_OPTIONS=%s\\n' \"$NODE_OPTIONS\"", diff --git a/test/shields-deferred-exit-lock.test.ts b/test/shields-deferred-exit-lock.test.ts new file mode 100644 index 00000000000..1899964889f --- /dev/null +++ b/test/shields-deferred-exit-lock.test.ts @@ -0,0 +1,55 @@ +// 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 REPO_ROOT = path.join(import.meta.dirname, ".."); +const SHIELDS_SOURCE = path.join(REPO_ROOT, "src", "lib", "shields", "index.ts"); +const SOURCE_REQUIRE_HOOK = path.join(REPO_ROOT, "test", "helpers", "onboard-script-mocks.cjs"); + +describe("shields command exit serialization", () => { + it("releases the token-bound lock before a repeated shields-down exits the process", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-real-exit-")); + const stateDir = path.join(home, ".nemoclaw", "state"); + const lockPath = path.join(stateDir, "shields-transition-lock-alpha.json"); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(stateDir, "shields-alpha.json"), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: "2026-06-27T00:00:00.000Z", + updatedAt: "2026-06-27T00:00:00.000Z", + }), + { mode: 0o600 }, + ); + + try { + const result = spawnSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + `require(${JSON.stringify(SHIELDS_SOURCE)}).shieldsDown("alpha", { processToken: ${JSON.stringify("a".repeat(32))} });`, + ], + { + encoding: "utf-8", + env: { ...process.env, HOME: home, NEMOCLAW_NON_INTERACTIVE: "1", NODE_OPTIONS: "" }, + timeout: 10_000, + }, + ); + + expect(result.status, result.stderr).toBe(1); + expect(`${result.stdout}\n${result.stderr}`).toContain("already unlocked"); + expect(fs.existsSync(lockPath)).toBe(false); + expect(fs.readdirSync(stateDir).some((name) => name.includes(".acquire-"))).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/test/shields-up-runtime-perms.test.ts b/test/shields-up-runtime-perms.test.ts index 9c32fda0280..cca7ac5f0ac 100644 --- a/test/shields-up-runtime-perms.test.ts +++ b/test/shields-up-runtime-perms.test.ts @@ -2,12 +2,25 @@ // 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"; +import { + CONFIDENTIALITY_STATE_DIRS, + HIGH_RISK_STATE_DIRS, + WRITABLE_RUNTIME_SUBPATHS, +} from "../src/lib/shields/state-dir-lock"; -function runLockAgentConfigProbe(): string[][] { +const OPENCLAW_GUARD = "/usr/local/lib/nemoclaw/openclaw-config-guard.py"; +const STATE_DIR_GUARD = "/usr/local/lib/nemoclaw/state-dir-guard.py"; + +type GuardProbeResult = { + calls: string[][]; + status: number | null; + stderr: string; +}; + +function runLockAgentConfigProbe( + options: { stateDirIssuePath?: string; malformedStateDirOutput?: boolean } = {}, +): GuardProbeResult { const probe = spawnSync( process.execPath, [ @@ -16,17 +29,33 @@ function runLockAgentConfigProbe(): string[][] { const Module = require("node:module"); const originalLoad = Module._load; const calls = []; +const stateDirIssuePath = ${JSON.stringify(options.stateDirIssuePath ?? null)}; +const malformedStateDirOutput = ${JSON.stringify(options.malformedStateDirOutput === true)}; + +function commandFromArgs(args) { + const separator = args.indexOf("--"); + return separator >= 0 ? args.slice(separator + 1) : args; +} + +function completed(stdout = "", status = 0) { + return { status, signal: null, stdout, stderr: "" }; +} + +function guardAction(command, helper) { + const helperIndex = command.indexOf(helper); + return helperIndex >= 0 ? command[helperIndex + 1] : null; +} + Module._load = function patchedLoad(request, parent, isMain) { if (request === "../adapters/docker/exec") { return { dockerExecFileSync(args) { - const separator = args.indexOf("--"); - const command = separator >= 0 ? args.slice(separator + 1) : args; + const command = commandFromArgs(args); calls.push(command); if (command[0] === "stat" && command[1] === "-c") { - return command.at(-1) === "/sandbox/.openclaw" - ? "755 root:root\n" - : "444 root:root\n"; + if (command.at(-1) === "/sandbox") return "1775 root:sandbox\n"; + if (command.at(-1) === "/sandbox/.openclaw") return "755 root:root\n"; + return "444 root:root\n"; } if (command[0] === "lsattr") { return "----i----------------- " + command.at(-1) + "\n"; @@ -40,76 +69,57 @@ Module._load = function patchedLoad(request, parent, isMain) { } return ""; }, - }; - } - if (request === "../sandbox/privileged-exec") { - return { - privilegedSandboxExecArgv(_sandboxName, cmd) { - return [...cmd]; - }, - }; - } - return originalLoad.call(this, request, parent, isMain); -}; -const { lockAgentConfig } = require("./src/lib/shields/index.ts"); -lockAgentConfig("sandbox-pod", { - agentName: "openclaw", - configPath: "/sandbox/.openclaw/openclaw.json", - configDir: "/sandbox/.openclaw", - sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], -}); -process.stdout.write(JSON.stringify(calls)); -`, - ], - { encoding: "utf-8", timeout: 5000 }, - ); - expect(probe.status).toBe(0); - return JSON.parse(probe.stdout) as string[][]; -} - -function runLockAgentConfigProbeExpectingThrow(symlinkedPath: string): { - stdout: string; - stderr: string; - status: number | null; -} { - return spawnSync( - process.execPath, - [ - "-e", - String.raw` -const Module = require("node:module"); -const originalLoad = Module._load; -const symlinkedPath = ${JSON.stringify(symlinkedPath)}; -Module._load = function patchedLoad(request, parent, isMain) { - if (request === "../adapters/docker/exec") { - return { - dockerExecFileSync(args) { - const separator = args.indexOf("--"); - const command = separator >= 0 ? args.slice(separator + 1) : args; - if ( - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - !command[2].includes("symlinked-root") - ) { - return symlinkedPath + "\n"; - } - if (command[0] === "stat" && command[1] === "-c") { - return command.at(-1) === "/sandbox/.openclaw" - ? "755 root:root\n" - : "444 root:root\n"; - } - if (command[0] === "lsattr") { - return "----i----------------- " + command.at(-1) + "\n"; + dockerSpawnSync(args) { + const command = commandFromArgs(args); + calls.push(command); + if (command[0] === "test" && command[1] === "-r") return completed(); + + const openClawAction = guardAction(command, ${JSON.stringify(OPENCLAW_GUARD)}); + if (openClawAction) { + return completed( + JSON.stringify({ + type: "result", + action: openClawAction, + status: "ok", + configDir: "/sandbox/.openclaw", + files: ["openclaw.json", ".config-hash"], + chattrApplied: true, + }) + "\n", + ); } - if (command[0] === "sha256sum") { - return ( - "0000000000000000000000000000000000000000000000000000000000000001 " + - command.at(-1) + - "\n" + + const stateDirAction = guardAction(command, ${JSON.stringify(STATE_DIR_GUARD)}); + if (stateDirAction) { + if (malformedStateDirOutput) return completed("not-json\n"); + if (stateDirIssuePath && stateDirAction === "lock") { + return completed( + [ + JSON.stringify({ + type: "issue", + code: "state-root-symlink", + path: stateDirIssuePath, + detail: "state-dir roots must not be symlinks", + }), + JSON.stringify({ + type: "result", + action: "lock", + status: "failed", + issueCount: 1, + }), + ].join("\n") + "\n", + 1, + ); + } + return completed( + JSON.stringify({ + type: "result", + action: stateDirAction, + status: "ok", + issueCount: 0, + }) + "\n", ); } - return ""; + return completed("", 127); }, }; } @@ -122,327 +132,113 @@ Module._load = function patchedLoad(request, parent, isMain) { } return originalLoad.call(this, request, parent, isMain); }; + try { const { lockAgentConfig } = require("./src/lib/shields/index.ts"); - lockAgentConfig("sandbox-pod", { - agentName: "openclaw", - configPath: "/sandbox/.openclaw/openclaw.json", - configDir: "/sandbox/.openclaw", - sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], - }); - process.stdout.write("UNEXPECTED_SUCCESS"); - process.exit(0); -} catch (err) { - process.stderr.write(err && err.message ? err.message : String(err)); - process.exit(2); + lockAgentConfig( + "sandbox-pod", + { + agentName: "openclaw", + configPath: "/sandbox/.openclaw/openclaw.json", + configDir: "/sandbox/.openclaw", + sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], + }, + false, + ); + process.stdout.write(JSON.stringify(calls)); +} catch (error) { + process.stdout.write(JSON.stringify(calls)); + process.stderr.write(error && error.message ? error.message : String(error)); + process.exitCode = 2; } `, ], { encoding: "utf-8", timeout: 5000 }, ); + return { + calls: probe.stdout ? (JSON.parse(probe.stdout) as string[][]) : [], + status: probe.status, + stderr: probe.stderr, + }; } -function findStateDirLockShell(commands: string[][]): string[] | undefined { - return commands.find( - (command) => - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - command[2].includes('chown -R "$owner"') && - command.includes("root:sandbox") && - command.includes("agents") && - command.includes("extensions"), - ); +function helperCalls(calls: string[][], helper: string, action?: string): string[][] { + return calls.filter((command) => { + const helperIndex = command.indexOf(helper); + if (helperIndex < 0) return false; + return action === undefined || command[helperIndex + 1] === action; + }); } describe("shields-up state-dir lock preserves sandbox-group access + runtime sessions writable", () => { - it("locks the high-risk state dirs via a single sh-c script with root:sandbox ownership", () => { - const commands = runLockAgentConfigProbe(); - - const stateDirLockShell = findStateDirLockShell(commands); - expect(stateDirLockShell).toBeDefined(); - expect(stateDirLockShell).toEqual(expect.arrayContaining(["root:sandbox", "go-w", "755"])); - expect(stateDirLockShell).toEqual( - expect.arrayContaining(["agents", "agent", "extensions", "skills", "hooks"]), - ); + it("uses the installed descriptor-safe guards for top-level and recursive lockdown", () => { + const result = runLockAgentConfigProbe(); + expect(result.status, result.stderr).toBe(0); + + const configLocks = helperCalls(result.calls, OPENCLAW_GUARD, "lock"); + const stateLocks = helperCalls(result.calls, STATE_DIR_GUARD, "lock"); + expect(configLocks).toHaveLength(1); + expect(stateLocks).toHaveLength(1); + for (const command of [...configLocks, ...stateLocks]) { + expect(command).toEqual(expect.arrayContaining(["python3", "-I"])); + expect(command).toEqual(expect.arrayContaining(["--config-dir", "/sandbox/.openclaw"])); + } }); - it("guards the state-dir lock script against symlinked roots", () => { - const commands = runLockAgentConfigProbe(); - const stateDirLockShell = findStateDirLockShell(commands); - expect(stateDirLockShell).toBeDefined(); - const script = stateDirLockShell?.[2] ?? ""; - expect(script).toContain('if [ -L "$path" ]; then'); - expect(script).toContain("symlinked-root"); - expect(script).toContain('[ -d "$path" ] || continue'); - }); + it("freezes the canonical config before recursive state containment", () => { + const result = runLockAgentConfigProbe(); + expect(result.status, result.stderr).toBe(0); - it("guards the workspace-* lock script against symlinked roots", () => { - const commands = runLockAgentConfigProbe(); - const workspaceMutationShell = commands.find( - (command) => - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - command[2].includes("workspace-*") && - command[2].includes('chown -R "$owner"'), + const configLockIndex = result.calls.findIndex( + (command) => helperCalls([command], OPENCLAW_GUARD, "lock").length === 1, ); - expect(workspaceMutationShell).toBeDefined(); - const script = workspaceMutationShell?.[2] ?? ""; - expect(script).toContain('if [ -L "$dir" ]; then'); - expect(script).toContain("symlinked-root"); + const stateLockIndex = result.calls.findIndex( + (command) => helperCalls([command], STATE_DIR_GUARD, "lock").length === 1, + ); + expect(configLockIndex).toBeGreaterThanOrEqual(0); + expect(stateLockIndex).toBeGreaterThan(configLockIndex); }); - it("runs a symlink-preflight script before any mutation", () => { - const commands = runLockAgentConfigProbe(); - const preflightShell = commands.find( - (command) => - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - command[2].includes("workspace-*") && - !command[2].includes("chown") && - !command[2].includes("chmod"), + it("keeps the complete protected inventory and writable sessions carve-out", () => { + expect(HIGH_RISK_STATE_DIRS).toEqual( + expect.arrayContaining(["skills", "agent", "hooks", "agents", "extensions", "workspace"]), ); - expect(preflightShell).toBeDefined(); - const script = preflightShell?.[2] ?? ""; - expect(script).toContain('if [ -L "$path" ]; then printf'); - expect(script).toContain('if [ -L "$dir" ]; then printf'); - expect(preflightShell).toEqual(expect.arrayContaining(["agent"])); + expect(CONFIDENTIALITY_STATE_DIRS).toEqual(["credentials", "identity", "pairing"]); + expect(WRITABLE_RUNTIME_SUBPATHS).toEqual(["agents/*/sessions"]); }); - // A symlinked state-dir root must abort shields-up; otherwise the lock - // would report success while the dir still points at a writable host - // path. - it("throws when shields-up encounters a symlinked state-dir root", () => { - const result = runLockAgentConfigProbeExpectingThrow("/sandbox/.openclaw/extensions"); - expect(result.status).toBe(2); - expect(result.stderr).toContain("Config not locked"); - expect(result.stderr).toContain("state dir root is a symlink"); - expect(result.stderr).toContain("/sandbox/.openclaw/extensions"); - }); + it.each([ + "extensions", + "agent", + ])("surfaces a recursive guard refusal for a symlinked %s root", (root) => { + const unsafePath = `/sandbox/.openclaw/${root}`; + const result = runLockAgentConfigProbe({ stateDirIssuePath: unsafePath }); - it("throws when shields-up encounters a symlinked Deep Agents agent dir", () => { - const result = runLockAgentConfigProbeExpectingThrow("/sandbox/.openclaw/agent"); expect(result.status).toBe(2); expect(result.stderr).toContain("Config not locked"); - expect(result.stderr).toContain("state dir root is a symlink"); - expect(result.stderr).toContain("/sandbox/.openclaw/agent"); - }); - - // Atomicity: when the preflight detects a symlinked state-dir root, - // no chown/chmod must run on any of the other (non-symlinked) state - // dirs in the same lock attempt. Without this guarantee, earlier - // entries in HIGH_RISK_STATE_DIRS could be silently re-owned to - // root:sandbox before the later symlink is reached and the lock - // bails out, leaving a half-locked tree behind. - it("does not mutate any state dir when the preflight reports a symlinked root", () => { - const probe = spawnSync( - process.execPath, - [ - "-e", - String.raw` -const Module = require("node:module"); -const originalLoad = Module._load; -const calls = []; -Module._load = function patchedLoad(request, parent, isMain) { - if (request === "../adapters/docker/exec") { - return { - dockerExecFileSync(args) { - const separator = args.indexOf("--"); - const command = separator >= 0 ? args.slice(separator + 1) : args; - calls.push(command); - if ( - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - !command[2].includes("symlinked-root") - ) { - return "/sandbox/.openclaw/extensions\n"; - } - return ""; - }, - }; - } - if (request === "../sandbox/privileged-exec") { - return { - privilegedSandboxExecArgv(_sandboxName, cmd) { - return [...cmd]; - }, - }; - } - return originalLoad.call(this, request, parent, isMain); -}; -try { - const { lockAgentConfig } = require("./src/lib/shields/index.ts"); - lockAgentConfig("sandbox-pod", { - agentName: "openclaw", - configPath: "/sandbox/.openclaw/openclaw.json", - configDir: "/sandbox/.openclaw", - sensitiveFiles: ["/sandbox/.openclaw/.config-hash"], + expect(result.stderr).toContain("state-dir guard lock [state-root-symlink]"); + expect(result.stderr).toContain(unsafePath); + expect(result.stderr).toContain("state-dir roots must not be symlinks"); }); - process.stdout.write("UNEXPECTED_SUCCESS\n"); - process.stdout.write(JSON.stringify(calls)); - process.exit(0); -} catch (err) { - process.stdout.write(JSON.stringify(calls)); - process.stderr.write(err && err.message ? err.message : String(err)); - process.exit(2); -} -`, - ], - { encoding: "utf-8", timeout: 5000 }, - ); - expect(probe.status).toBe(2); - expect(probe.stderr).toContain("state dir root is a symlink"); - - const calls = JSON.parse(probe.stdout) as string[][]; - // Mutation pass scripts contain "symlinked-root\\t" in their script body. - // If any such call was recorded, atomicity is broken. - const mutationCalls = calls.filter( - (command) => - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - command[2].includes("symlinked-root"), - ); - expect(mutationCalls).toEqual([]); - // Restore-writable-subpaths must also not run (it would mkdir - // agents/<id>/sessions inside what could be a half-locked tree). - const restoreCalls = calls.filter( - (command) => - command[0] === "sh" && - command[1] === "-c" && - typeof command[2] === "string" && - command[2].includes("agents/*/sessions"), - ); - expect(restoreCalls).toEqual([]); - }); - - it("keeps the top-level config dir owned by root:root (lock contract unchanged)", () => { - const commands = runLockAgentConfigProbe(); - expect(commands).toContainEqual(["chown", "root:root", "/sandbox/.openclaw"]); - expect(commands).toContainEqual(["chown", "root:root", "/sandbox/.openclaw/openclaw.json"]); - }); - - it("restores agents/*/sessions to sandbox:sandbox 2770 after the main lock loop", () => { - const commands = runLockAgentConfigProbe(); - const restoreShell = commands.find( - (command) => - command[0] === "sh" && - command[1] === "-c" && - command.includes("/sandbox/.openclaw") && - command.includes("agents/*/sessions") && - typeof command[2] === "string" && - command[2].includes("chown -R sandbox:sandbox") && - command[2].includes("chmod 2770"), - ); - expect(restoreShell).toBeDefined(); - }); - - // Behavioral check against a real filesystem fixture: the restore script - // must mkdir `agents/<id>/sessions` even when the leaf does not yet exist - // (fresh sandbox, never-run TUI). The pre-fix script's case-`*` guard - // skipped the literal pattern when the glob matched nothing, leaving - // `sessions/` uncreated and the post-lockdown TUI mkdir blocked. - it("creates agents/<id>/sessions under a fresh agent dir that has no sessions yet", () => { - const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-runtime-")); - const configDir = path.join(fixture, ".openclaw"); - const agentDir = path.join(configDir, "agents", "main"); - fs.mkdirSync(agentDir, { recursive: true }); - - const restoreShell = runLockAgentConfigProbe().find( - (command) => - command[0] === "sh" && command[1] === "-c" && command.includes("agents/*/sessions"), - ); - if (!restoreShell) { - throw new Error("restore-writable-runtime-subpaths shell command not found"); - } - const script = restoreShell[2]; - // Captured argv: ["sh", "-c", script, "sh", "/sandbox/.openclaw", ...patterns]. - // Drop everything up to and including the probed configDir so the fixture - // configDir is passed exactly once when re-running the script body. - const patterns = restoreShell.slice(5); - - const result = spawnSync("sh", ["-c", `${script}\n`, "sh", configDir, ...patterns], { - encoding: "utf-8", - timeout: 5000, - }); - expect(result.status).toBe(0); - expect(fs.existsSync(path.join(agentDir, "sessions"))).toBe(true); - expect(fs.statSync(path.join(agentDir, "sessions")).isDirectory()).toBe(true); - - fs.rmSync(fixture, { recursive: true, force: true }); - }); - - // If a pre-lockdown agent swaps a high-risk state dir (here `extensions`) - // for a symlink to a host path, the consolidated state-dir lock script - // must skip the symlink without recursing into the target. - it("does not chown/chmod through a symlinked high-risk state dir", () => { - const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-statedir-symlink-")); - const configDir = path.join(fixture, ".openclaw"); - const hostTarget = path.join(fixture, "host-target"); - fs.mkdirSync(configDir, { recursive: true }); - fs.mkdirSync(hostTarget, { recursive: true }); - const innocentFile = path.join(hostTarget, "host-file"); - fs.writeFileSync(innocentFile, "untouched\n", { mode: 0o600 }); - const hostFilePerms = fs.statSync(innocentFile).mode & 0o7777; - fs.symlinkSync(hostTarget, path.join(configDir, "extensions")); - - const stateDirLockShell = findStateDirLockShell(runLockAgentConfigProbe()); - if (!stateDirLockShell) { - throw new Error("state-dir lock shell command not found"); - } - const script = stateDirLockShell[2]; - // Captured argv: ["sh", "-c", script, "sh", configDir, owner, - // recursiveMode, dirMode, clearSetgid, ...stateDirs]. Drop the probed - // configDir from index 4 and substitute the fixture path. - const args = stateDirLockShell.slice(4); - args[0] = configDir; - const result = spawnSync("sh", ["-c", `${script}\n`, "sh", ...args], { - encoding: "utf-8", - timeout: 5000, + it("preserves the top-level seal when recursive containment refuses", () => { + const result = runLockAgentConfigProbe({ + stateDirIssuePath: "/sandbox/.openclaw/extensions", }); - expect(result.status).toBe(0); - expect(fs.lstatSync(path.join(configDir, "extensions")).isSymbolicLink()).toBe(true); - expect(fs.statSync(innocentFile).mode & 0o7777).toBe(hostFilePerms); + expect(result.status).toBe(2); - fs.rmSync(fixture, { recursive: true, force: true }); + expect(helperCalls(result.calls, OPENCLAW_GUARD, "lock")).toHaveLength(2); + expect(helperCalls(result.calls, OPENCLAW_GUARD, "unlock")).toHaveLength(0); + expect(helperCalls(result.calls, STATE_DIR_GUARD, "lock")).toHaveLength(1); }); - // Defense in depth: if a malicious agent points `agents/<id>` at /etc or - // any other host path before shields-up runs, the privileged restore - // helper must not mkdir/chown/chmod through that symlink. The script - // must drop symlinked parents (and symlinked targets) before touching - // them. - it("refuses to follow a symlinked agents/<id> parent during the runtime-subpath restore", () => { - const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-shields-symlink-")); - const configDir = path.join(fixture, ".openclaw"); - const agentsRoot = path.join(configDir, "agents"); - const hostTarget = path.join(fixture, "host-target"); - fs.mkdirSync(agentsRoot, { recursive: true }); - fs.mkdirSync(hostTarget, { recursive: true }); - fs.symlinkSync(hostTarget, path.join(agentsRoot, "main")); - - const restoreShell = runLockAgentConfigProbe().find( - (command) => - command[0] === "sh" && command[1] === "-c" && command.includes("agents/*/sessions"), - ); - if (!restoreShell) { - throw new Error("restore-writable-runtime-subpaths shell command not found"); - } - const script = restoreShell[2]; - const patterns = restoreShell.slice(5); - - const result = spawnSync("sh", ["-c", `${script}\n`, "sh", configDir, ...patterns], { - encoding: "utf-8", - timeout: 5000, - }); - expect(result.status).toBe(0); - expect(fs.existsSync(path.join(hostTarget, "sessions"))).toBe(false); - expect(fs.existsSync(path.join(agentsRoot, "main", "sessions"))).toBe(false); + it("fails closed when the recursive helper violates its output contract", () => { + const result = runLockAgentConfigProbe({ malformedStateDirOutput: true }); - fs.rmSync(fixture, { recursive: true, force: true }); + expect(result.status).toBe(2); + expect(result.stderr).toContain("state-dir guard returned non-JSON output"); + expect(result.stderr).toContain("state-dir guard returned 0 result records"); + expect(helperCalls(result.calls, OPENCLAW_GUARD, "lock")).toHaveLength(2); + expect(helperCalls(result.calls, OPENCLAW_GUARD, "unlock")).toHaveLength(0); }); }); diff --git a/test/startup-process-identity.test.ts b/test/startup-process-identity.test.ts new file mode 100644 index 00000000000..cbe0f42bf88 --- /dev/null +++ b/test/startup-process-identity.test.ts @@ -0,0 +1,228 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const IDENTITY_HARNESS = String.raw` +import importlib.util +import json +import os +import sys +import tempfile + +spec = importlib.util.spec_from_file_location("runtime_guard", sys.argv[1]) +guard = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = guard +spec.loader.exec_module(guard) + +def write_process( + proc_root, + pid, + start_time, + cmdline, + namespace_path, + effective_uid=0, + inner_pid=1, + parent_pid=0, +): + process_dir = os.path.join(proc_root, str(pid)) + os.makedirs(os.path.join(process_dir, "ns")) + fields = ["S", str(parent_pid)] + (["0"] * 17) + [str(start_time)] + with open(os.path.join(process_dir, "stat"), "w", encoding="ascii") as stream: + stream.write(f"{pid} (nemoclaw) {' '.join(fields)}\n") + with open(os.path.join(process_dir, "cmdline"), "wb") as stream: + stream.write(cmdline) + with open(os.path.join(process_dir, "status"), "w", encoding="ascii") as stream: + stream.write( + f"Uid:\t{effective_uid}\t{effective_uid}\t{effective_uid}\t{effective_uid}\n" + f"NSpid:\t{pid}\t{inner_pid}\n" + ) + os.link(namespace_path, os.path.join(process_dir, "ns", "pid")) + +def scenario( + processes, + expected_start="424242", + expected_namespace="trusted", + limit=32768, +): + with tempfile.TemporaryDirectory() as root: + proc_root = os.path.join(root, "proc") + os.mkdir(proc_root) + namespaces = {} + for name in {"trusted", "other"}: + namespace_path = os.path.join(root, name) + with open(namespace_path, "wb") as stream: + stream.write(name.encode("ascii")) + namespaces[name] = namespace_path + for process in processes: + pid, start_time, cmdline, namespace, *identity = process + write_process( + proc_root, + pid, + start_time, + cmdline, + namespaces[namespace], + *identity, + ) + guard.PROC_ROOT = proc_root + guard.MAX_PROC_ENTRIES = limit + return guard._startup_process_identity_is_live( + expected_start, + os.stat(namespaces[expected_namespace]).st_ino, + ) + +def supervised_scenario( + processes, + supervisor_cmdline=b"/opt/openshell/bin/openshell-sandbox\0", + limit=32768, + required_pid=None, + namespace_access=True, +): + with tempfile.TemporaryDirectory() as root: + proc_root = os.path.join(root, "proc") + os.mkdir(proc_root) + namespace_path = os.path.join(root, "shared") + with open(namespace_path, "wb") as stream: + stream.write(b"shared") + write_process( + proc_root, + 1, + "111111", + supervisor_cmdline, + namespace_path, + effective_uid=0, + inner_pid=1, + parent_pid=0, + ) + for process in processes: + pid, start_time, cmdline, effective_uid, inner_pid, parent_pid = process + write_process( + proc_root, + pid, + start_time, + cmdline, + namespace_path, + effective_uid=effective_uid, + inner_pid=inner_pid, + parent_pid=parent_pid, + ) + guard.PROC_ROOT = proc_root + guard.MAX_PROC_ENTRIES = limit + original_namespace_reader = guard._proc_pid_namespace_inode + if not namespace_access: + guard._proc_pid_namespace_inode = lambda _proc_pid_fd: None + elif namespace_access == "child_only": + supervisor_stat = os.stat(os.path.join(proc_root, "1")) + def child_only_namespace_reader(proc_pid_fd): + proc_pid_stat = os.fstat(proc_pid_fd) + if ( + proc_pid_stat.st_dev == supervisor_stat.st_dev + and proc_pid_stat.st_ino == supervisor_stat.st_ino + ): + return None + return original_namespace_reader(proc_pid_fd) + guard._proc_pid_namespace_inode = child_only_namespace_reader + try: + return guard._openshell_supervised_nonroot_start_is_live( + 0, + 1000, + required_pid, + ) + finally: + guard._proc_pid_namespace_inode = original_namespace_reader + +entrypoint = b"bash\0/usr/local/bin/nemoclaw-start\0" +spoof = b"bash\0/tmp/nemoclaw-start-spoof\0" +proof = { + "remapped": scenario([(412, "424242", entrypoint, "trusted")]), + "stale": scenario([(412, "999999", entrypoint, "trusted")]), + "spoof": scenario([(412, "424242", spoof, "trusted")]), + "nonroot": scenario([(412, "424242", entrypoint, "trusted", 1000)]), + "noninit": scenario([(412, "424242", entrypoint, "trusted", 0, 2)]), + "wrong_namespace": scenario([(412, "424242", entrypoint, "other")]), + "duplicate": scenario([ + (412, "424242", entrypoint, "trusted"), + (413, "424242", entrypoint, "trusted"), + ]), + "bounded": scenario([ + (412, "424242", entrypoint, "trusted"), + (413, "999999", spoof, "other"), + ], limit=1), +} +proof.update({ + "openshell_supervised": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ]), + "openshell_landlock_all_namespaces_denied": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ], namespace_access=False), + "openshell_landlock_supervisor_namespace_denied": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ], namespace_access="child_only"), + "openshell_wrong_supervisor": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ], supervisor_cmdline=b"/usr/bin/foreign-supervisor\0"), + "openshell_root_child": supervised_scenario([ + (412, "424242", entrypoint, 0, 412, 1), + ]), + "openshell_nested_child": supervised_scenario([ + (412, "424242", entrypoint, 1000, 1, 1), + ]), + "openshell_non_direct_child": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 77), + ]), + "openshell_spoof": supervised_scenario([ + (412, "424242", spoof, 1000, 412, 1), + ]), + "openshell_duplicate": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + (413, "525252", entrypoint, 1000, 413, 1), + ]), + "openshell_required_child": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ], required_pid=412), + "openshell_wrong_required_child": supervised_scenario([ + (412, "424242", entrypoint, 1000, 412, 1), + ], required_pid=413), +}) +print(json.dumps(proof)) +`; + +const GUARDS = [ + ["OpenClaw", path.resolve("scripts/openclaw-config-guard.py")], + ["Hermes", path.resolve("agents/hermes/runtime-config-guard.py")], +] as const; + +describe.each(GUARDS)("%s startup process identity", (_name, guardPath) => { + it("authenticates exactly one root namespace init and rejects stale or spoofed identities (#2426)", () => { + const result = spawnSync("python3", ["-c", IDENTITY_HARNESS, guardPath], { + encoding: "utf-8", + timeout: 5000, + }); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + remapped: true, + stale: false, + spoof: false, + nonroot: false, + noninit: false, + wrong_namespace: false, + duplicate: false, + bounded: false, + openshell_supervised: true, + openshell_landlock_all_namespaces_denied: true, + openshell_landlock_supervisor_namespace_denied: true, + openshell_wrong_supervisor: false, + openshell_root_child: false, + openshell_nested_child: false, + openshell_non_direct_child: false, + openshell_spoof: false, + openshell_duplicate: false, + openshell_required_child: true, + openshell_wrong_required_child: false, + }); + }); +}); diff --git a/test/state-dir-guard.test.ts b/test/state-dir-guard.test.ts new file mode 100644 index 00000000000..3e63af56c23 --- /dev/null +++ b/test/state-dir-guard.test.ts @@ -0,0 +1,601 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { testTimeoutOptions } from "./helpers/timeouts"; + +const GUARD_PATH = path.resolve("scripts/state-dir-guard.py"); +const fixtures: string[] = []; + +const RUN_GUARD_AS_CURRENT_USER = String.raw` +import importlib.util +import os +import sys + +guard_path, action, config_dir = sys.argv[1:4] +spec = importlib.util.spec_from_file_location("nemoclaw_state_dir_guard", guard_path) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +identity = module.Identity( + root_uid=os.getuid(), + root_gid=os.getgid(), + sandbox_uid=os.getuid(), + sandbox_gid=os.getgid(), +) +module.os.geteuid = lambda: 0 +module._production_identity = lambda: identity +if os.environ.get("NEMOCLAW_TEST_MAX_ENTRIES"): + module.MAX_ENTRIES_PER_PASS = int(os.environ["NEMOCLAW_TEST_MAX_ENTRIES"]) +if os.environ.get("NEMOCLAW_TEST_MAX_COPY_BYTES"): + module.MAX_COPIED_BYTES_PER_PASS = int(os.environ["NEMOCLAW_TEST_MAX_COPY_BYTES"]) +raise SystemExit(module.main([action, "--config-dir", config_dir])) +`; + +const RUN_FAKE_IMMUTABLE_TRANSITION = String.raw` +import importlib.util +import json +import os +import struct +import sys + +guard_path, config_dir, file_path = sys.argv[1:4] +spec = importlib.util.spec_from_file_location("nemoclaw_state_dir_guard_flags", guard_path) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +identity = module.Identity( + root_uid=os.getuid(), root_gid=os.getgid(), + sandbox_uid=os.getuid(), sandbox_gid=os.getgid(), +) +flags = {} +initial = os.stat(file_path) +flags[(initial.st_dev, initial.st_ino)] = module.FS_IMMUTABLE_FL + +def fake_ioctl(fd, operation, payload): + st = os.fstat(fd) + key = (st.st_dev, st.st_ino) + if operation == module.FS_IOC_GETFLAGS: + return struct.pack("I", flags.get(key, 0)) + if operation == module.FS_IOC_SETFLAGS: + flags[key] = struct.unpack("I", payload)[0] + return payload + raise AssertionError(operation) + +module.fcntl.ioctl = fake_ioctl +locked = module.run_guard("lock", config_dir, identity) +locked_stat = os.stat(file_path) +locked_flags = flags.get((locked_stat.st_dev, locked_stat.st_ino), 0) +unlocked = module.run_guard("unlock", config_dir, identity) +unlocked_stat = os.stat(file_path) +unlocked_flags = flags.get((unlocked_stat.st_dev, unlocked_stat.st_ino), 0) +print(json.dumps({ + "lock_ok": locked.ok, + "unlock_ok": unlocked.ok, + "inode_replaced": locked_stat.st_ino != initial.st_ino, + "locked_flags": locked_flags, + "unlocked_flags": unlocked_flags, +})) +`; + +interface GuardLine { + type: "issue" | "result"; + code?: string; + path?: string; + detail?: string; + action?: string; + status?: string; + issueCount?: number; + removedEntries?: number; +} + +function fixture(): { root: string; configDir: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-dir-guard-")); + fixtures.push(root); + const configDir = path.join(root, ".agent"); + fs.mkdirSync(configDir, { recursive: true }); + // macOS exposes /var through a symlink. The production helper refuses + // symlinked ancestors, so pass the descriptor-resolved fixture path too. + return { root, configDir: fs.realpathSync(configDir) }; +} + +function runGuard( + action: "preflight" | "lock" | "unlock", + configDir: string, + env: Record<string, string> = {}, +) { + const result = spawnSync( + "python3", + ["-c", RUN_GUARD_AS_CURRENT_USER, GUARD_PATH, action, configDir], + { encoding: "utf-8", timeout: 15_000, env: { ...process.env, ...env } }, + ); + const lines = result.stdout + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as GuardLine); + return { ...result, lines }; +} + +function mode(filePath: string): number { + return fs.lstatSync(filePath).mode & 0o7777; +} + +afterEach(() => { + for (const root of fixtures.splice(0)) { + fs.chmodSync(root, 0o700); + const configDir = path.join(root, ".agent"); + for (const existingConfigDir of fs.existsSync(configDir) ? [configDir] : []) { + fs.chmodSync(existingConfigDir, 0o700); + } + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("state-dir-guard", () => { + it("rejects an external nested symlink without touching its target", () => { + const { root, configDir } = fixture(); + const pluginDir = path.join(configDir, "plugins", "nested"); + const externalDir = path.join(root, "outside"); + const externalFile = path.join(externalDir, "innocent.txt"); + fs.mkdirSync(pluginDir, { recursive: true }); + fs.mkdirSync(externalDir); + fs.writeFileSync(externalFile, "untouched\n", { mode: 0o666 }); + const externalMode = mode(externalFile); + fs.symlinkSync(externalDir, path.join(pluginDir, "escape")); + + const result = runGuard("preflight", configDir); + + expect(result.status).toBe(1); + expect(result.stderr).toBe(""); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "issue", + code: "symlink-outside-protected-root", + path: path.join(pluginDir, "escape"), + }), + expect.objectContaining({ + type: "result", + action: "preflight", + status: "failed", + issueCount: 1, + }), + ]), + ); + expect(fs.readFileSync(externalFile, "utf-8")).toBe("untouched\n"); + expect(mode(externalFile)).toBe(externalMode); + }); + + it("allows a symlink whose fully resolved target stays in a protected root", () => { + const { configDir } = fixture(); + const pluginDir = path.join(configDir, "plugins"); + const versionDir = path.join(pluginDir, "versions", "v1"); + fs.mkdirSync(versionDir, { recursive: true }); + fs.writeFileSync(path.join(versionDir, "plugin.js"), "export {};\n", { mode: 0o664 }); + fs.symlinkSync("versions/v1", path.join(pluginDir, "current")); + + const preflight = runGuard("preflight", configDir); + const locked = runGuard("lock", configDir); + + expect(preflight.status).toBe(0); + expect(locked.status).toBe(0); + expect(fs.readlinkSync(path.join(pluginDir, "current"))).toBe("versions/v1"); + expect(mode(pluginDir)).toBe(0o755); + expect(mode(path.join(versionDir, "plugin.js"))).toBe(0o644); + }); + + it("rejects links from protected code into the writable sessions carveout", () => { + const { configDir } = fixture(); + const pluginDir = path.join(configDir, "plugins"); + const pluginPath = path.join(pluginDir, "trusted.js"); + const sessionsDir = path.join(configDir, "agents", "main", "sessions"); + const sessionPayload = path.join(sessionsDir, "payload.js"); + fs.mkdirSync(pluginDir); + fs.mkdirSync(sessionsDir, { recursive: true }); + fs.writeFileSync(pluginPath, "trusted\n"); + fs.writeFileSync(sessionPayload, "mutable\n"); + fs.symlinkSync("../agents/main/sessions/payload.js", path.join(pluginDir, "evil")); + + const result = runGuard("preflight", configDir); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "issue", + code: "symlink-crosses-runtime-carveout", + path: path.join(pluginDir, "evil"), + }), + ]), + ); + }); + + it("fresh-replaces locked files so an old writable FD cannot mutate the visible path", () => { + const { configDir } = fixture(); + const nestedDir = path.join(configDir, "extensions", "nested"); + const toolPath = path.join(nestedDir, "tool.sh"); + fs.mkdirSync(nestedDir, { recursive: true }); + fs.writeFileSync(toolPath, "stable\n", { mode: 0o775 }); + const preservedTime = new Date("2025-01-02T03:04:05.000Z"); + fs.utimesSync(toolPath, preservedTime, preservedTime); + const timestampsBefore = fs.statSync(toolPath); + const oldInode = fs.statSync(toolPath).ino; + const staleFd = fs.openSync(toolPath, "r+"); + + try { + const result = runGuard("lock", configDir); + expect(result.status).toBe(0); + expect(result.lines.at(-1)).toEqual( + expect.objectContaining({ type: "result", action: "lock", status: "ok" }), + ); + expect(fs.statSync(toolPath).ino).not.toBe(oldInode); + expect(mode(nestedDir)).toBe(0o755); + expect(mode(toolPath)).toBe(0o755); + const timestampsAfter = fs.statSync(toolPath); + expect(timestampsAfter.atimeMs).toBe(timestampsBefore.atimeMs); + expect(timestampsAfter.mtimeMs).toBe(timestampsBefore.mtimeMs); + + fs.writeSync(staleFd, Buffer.from("MUTATE\n"), 0, 7, 0); + fs.fsyncSync(staleFd); + expect(fs.readFileSync(toolPath, "utf-8")).toBe("stable\n"); + } finally { + fs.closeSync(staleFd); + } + }); + + it( + "fresh-seals a file even while an attacker continuously writes an old descriptor", + testTimeoutOptions(20_000), + async () => { + const { root, configDir } = fixture(); + const pluginDir = path.join(configDir, "plugins"); + const pluginPath = path.join(pluginDir, "racing.bin"); + const readyPath = path.join(root, "writer-ready"); + fs.mkdirSync(pluginDir); + fs.writeFileSync(pluginPath, Buffer.alloc(8 * 1024 * 1024, 0x41), { mode: 0o660 }); + const oldInode = fs.statSync(pluginPath).ino; + const writer = spawn( + process.execPath, + [ + "-e", + [ + "const fs=require('fs')", + "const file=process.argv[1]", + "const ready=process.argv[2]", + "const fd=fs.openSync(file,'r+')", + "const chunk=Buffer.alloc(1024*1024,0x5a)", + "fs.writeFileSync(ready,'ready')", + "setInterval(()=>{try{fs.writeSync(fd,chunk,0,chunk.length,0)}catch{}},0)", + ].join(";"), + pluginPath, + readyPath, + ], + { stdio: "ignore" }, + ); + + try { + const deadline = Date.now() + 5_000; + while (!fs.existsSync(readyPath) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(fs.existsSync(readyPath)).toBe(true); + + const result = runGuard("lock", configDir); + + expect(result.status, result.stderr).toBe(0); + expect(fs.statSync(pluginPath).ino).not.toBe(oldInode); + expect(mode(pluginPath)).toBe(0o640); + } finally { + writer.kill("SIGKILL"); + } + }, + ); + + it( + "streams a large file into a fresh inode while preserving read and execute bits", + testTimeoutOptions(20_000), + () => { + const { configDir } = fixture(); + const workspaceDir = path.join(configDir, "workspace-large"); + const payloadPath = path.join(workspaceDir, "model.bin"); + const payload = Buffer.alloc(1024 * 1024, 0xa5); + fs.mkdirSync(workspaceDir); + fs.writeFileSync(payloadPath, payload, { mode: 0o751 }); + const oldInode = fs.statSync(payloadPath).ino; + + const result = runGuard("lock", configDir); + + expect(result.status).toBe(0); + expect(fs.statSync(payloadPath).ino).not.toBe(oldInode); + expect(mode(payloadPath)).toBe(0o751); + expect(fs.readFileSync(payloadPath)).toEqual(payload); + }, + ); + + it("preserves sparse holes instead of expanding logical size into copied bytes", () => { + const { configDir } = fixture(); + const workspaceDir = path.join(configDir, "workspace-sparse"); + const payloadPath = path.join(workspaceDir, "sparse.bin"); + fs.mkdirSync(workspaceDir); + const fd = fs.openSync(payloadPath, "w", 0o660); + try { + fs.writeSync(fd, Buffer.from("head"), 0, 4, 0); + fs.writeSync(fd, Buffer.from("tail"), 0, 4, 64 * 1024 * 1024 - 4); + } finally { + fs.closeSync(fd); + } + const before = fs.statSync(payloadPath); + + const result = runGuard("lock", configDir, { + NEMOCLAW_TEST_MAX_COPY_BYTES: String(1024 * 1024), + }); + + expect(result.status).toBe(0); + const after = fs.statSync(payloadPath); + expect(after.size).toBe(before.size); + const verifyFd = fs.openSync(payloadPath, "r"); + try { + const head = Buffer.alloc(4); + const tail = Buffer.alloc(4); + fs.readSync(verifyFd, head, 0, 4, 0); + fs.readSync(verifyFd, tail, 0, 4, after.size - 4); + expect(head.toString()).toBe("head"); + expect(tail.toString()).toBe("tail"); + } finally { + fs.closeSync(verifyFd); + } + // st_blocks is 512-byte units. Allow filesystem metadata variance while + // proving the 64 MiB logical hole was not materialized. + expect(after.blocks * 512).toBeLessThan(1024 * 1024); + }); + + it("rejects adversarial entry and copy budgets before unbounded work", () => { + const { configDir } = fixture(); + const pluginsDir = path.join(configDir, "plugins"); + fs.mkdirSync(pluginsDir); + for (let index = 0; index < 5; index += 1) { + fs.writeFileSync(path.join(pluginsDir, `entry-${index}.txt`), "payload\n"); + } + + const result = runGuard("preflight", configDir, { + NEMOCLAW_TEST_MAX_ENTRIES: "3", + }); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "work-entry-limit" }), + ]), + ); + }); + + it.each([ + ["OpenClaw", "NEMOCLAW_TEST_OPENCLAW_FAIL_CLOSED"], + ["Hermes", "NEMOCLAW_TEST_HERMES_FAIL_CLOSED"], + ])("leaves the %s config root fail-closed when a state-tree budget aborts lock", (_agent, env) => { + const { configDir } = fixture(); + const pluginsDir = path.join(configDir, "plugins"); + const pluginPath = path.join(pluginsDir, "entry-0.txt"); + fs.mkdirSync(pluginsDir); + for (let index = 0; index < 5; index += 1) { + fs.writeFileSync(path.join(pluginsDir, `entry-${index}.txt`), "payload\n"); + } + const staleFd = fs.openSync(pluginPath, "r+"); + + try { + const result = runGuard("lock", configDir, { + NEMOCLAW_TEST_MAX_ENTRIES: "3", + [env]: "1", + }); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "work-entry-limit" }), + ]), + ); + expect(mode(configDir)).toBe(0o500); + fs.writeSync(staleFd, Buffer.from("stale\n"), 0, 6, 0); + expect(mode(configDir)).not.toBe(0o755); + } finally { + fs.closeSync(staleFd); + } + }); + + it("serializes an orphaned recursive unlock ahead of the restoring lock", async () => { + const { root, configDir } = fixture(); + const pluginDir = path.join(configDir, "plugins"); + const pluginFile = path.join(pluginDir, "plugin.js"); + fs.mkdirSync(pluginDir); + fs.writeFileSync(pluginFile, "module.exports = true;\n", { mode: 0o660 }); + const ready = path.join(root, "unlock-holds-mutex"); + const commonEnv = { + ...process.env, + NEMOCLAW_TEST_OPENCLAW_TRANSACTION_LOCK: "1", + }; + const unlock = spawn( + "python3", + ["-c", RUN_GUARD_AS_CURRENT_USER, GUARD_PATH, "unlock", configDir], + { + env: { + ...commonEnv, + NEMOCLAW_TEST_TRANSACTION_LOCK_HOLD_MS: "700", + NEMOCLAW_TEST_TRANSACTION_LOCK_READY: ready, + }, + stdio: "ignore", + }, + ); + + try { + const deadline = Date.now() + 5_000; + while (!fs.existsSync(ready) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(fs.existsSync(ready)).toBe(true); + + const startedAt = Date.now(); + const locked = spawnSync( + "python3", + ["-c", RUN_GUARD_AS_CURRENT_USER, GUARD_PATH, "lock", configDir], + { env: commonEnv, encoding: "utf-8", timeout: 10_000 }, + ); + + expect(locked.status, locked.stderr).toBe(0); + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(500); + expect(mode(pluginFile)).toBe(0o640); + } finally { + unlock.kill("SIGKILL"); + } + }); + + it("charges empty workspace roots against the same bounded inventory", () => { + const { configDir } = fixture(); + for (let index = 0; index < 5; index += 1) { + fs.mkdirSync(path.join(configDir, `workspace-${index}`)); + } + + const result = runGuard("preflight", configDir, { + NEMOCLAW_TEST_MAX_ENTRIES: "3", + }); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "work-entry-limit" }), + ]), + ); + }); + + it("descriptor-clears legacy immutable flags and reapplies them only to the locked inode", () => { + const { configDir } = fixture(); + const pluginsDir = path.join(configDir, "plugins"); + const pluginPath = path.join(pluginsDir, "legacy-immutable.js"); + fs.mkdirSync(pluginsDir); + fs.writeFileSync(pluginPath, "export {};\n", { mode: 0o660 }); + + const result = spawnSync( + "python3", + ["-c", RUN_FAKE_IMMUTABLE_TRANSITION, GUARD_PATH, configDir, pluginPath], + { encoding: "utf-8", timeout: 15_000 }, + ); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout.trim())).toEqual({ + lock_ok: true, + unlock_ok: true, + inode_replaced: true, + locked_flags: 0x10, + unlocked_flags: 0, + }); + }); + + it("applies distinct confidentiality, workspace, mutable, and session-carveout modes", () => { + const { configDir } = fixture(); + const secretDir = path.join(configDir, "credentials"); + const secretPath = path.join(secretDir, "token.json"); + const workspaceDir = path.join(configDir, "workspace-research"); + const executablePath = path.join(workspaceDir, "run.sh"); + const agentDir = path.join(configDir, "agents", "main"); + const sessionsDir = path.join(agentDir, "sessions"); + const sessionPath = path.join(sessionsDir, "active.jsonl"); + const sessionBacklink = path.join(sessionsDir, "runtime-link"); + const sessionFifo = path.join(sessionsDir, "runtime-events.fifo"); + const agentCodePath = path.join(agentDir, "agent.js"); + fs.mkdirSync(secretDir, { recursive: true }); + fs.mkdirSync(workspaceDir); + fs.mkdirSync(sessionsDir, { recursive: true }); + fs.writeFileSync(secretPath, "secret\n", { mode: 0o640 }); + fs.writeFileSync(executablePath, "#!/bin/sh\n", { mode: 0o775 }); + fs.writeFileSync(sessionPath, "runtime\n", { mode: 0o660 }); + fs.writeFileSync(agentCodePath, "export {};\n", { mode: 0o664 }); + fs.symlinkSync("../../../plugins/runtime-only", sessionBacklink); + expect(spawnSync("mkfifo", [sessionFifo]).status).toBe(0); + const initialSessionMode = mode(sessionPath); + const oldSessionInode = fs.statSync(sessionPath).ino; + const oldAgentCodeInode = fs.statSync(agentCodePath).ino; + + const locked = runGuard("lock", configDir); + + expect(locked.status).toBe(0); + expect(mode(secretDir)).toBe(0o700); + expect(mode(secretPath)).toBe(0o600); + expect(mode(workspaceDir)).toBe(0o755); + expect(mode(executablePath)).toBe(0o755); + expect(mode(path.join(configDir, "agents"))).toBe(0o755); + expect(mode(agentDir)).toBe(0o755); + expect(fs.statSync(agentCodePath).ino).not.toBe(oldAgentCodeInode); + expect(mode(sessionsDir)).toBe(0o2770); + expect(mode(sessionPath)).toBe(initialSessionMode); + expect(fs.statSync(sessionPath).ino).toBe(oldSessionInode); + expect(fs.readlinkSync(sessionBacklink)).toBe("../../../plugins/runtime-only"); + expect(fs.lstatSync(sessionFifo).isFIFO()).toBe(true); + + const unlocked = runGuard("unlock", configDir); + + expect(unlocked.status).toBe(0); + expect(mode(secretDir)).toBe(0o2770); + expect(mode(secretPath)).toBe(0o660); + expect(mode(workspaceDir)).toBe(0o2770); + expect(mode(executablePath)).toBe(0o770); + expect(mode(path.join(configDir, "agents"))).toBe(0o2770); + expect(mode(agentDir)).toBe(0o2770); + }); + + it("rejects hardlinks and special entries during the read-only preflight", () => { + const { configDir } = fixture(); + const skillsDir = path.join(configDir, "skills"); + const firstPath = path.join(skillsDir, "first.txt"); + fs.mkdirSync(skillsDir); + fs.writeFileSync(firstPath, "same inode\n"); + fs.linkSync(firstPath, path.join(skillsDir, "second.txt")); + const fifo = spawnSync("mkfifo", [path.join(skillsDir, "events.fifo")]); + expect(fifo.status).toBe(0); + + const result = runGuard("preflight", configDir); + + expect(result.status).toBe(1); + expect(result.lines).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "issue", code: "hardlinked-entry" }), + expect.objectContaining({ type: "issue", code: "special-entry" }), + ]), + ); + }); + + it("contains unsupported state entries during lock without following their targets", () => { + const { root, configDir } = fixture(); + const skillsDir = path.join(configDir, "skills"); + const firstPath = path.join(skillsDir, "first.txt"); + const secondPath = path.join(skillsDir, "second.txt"); + const fifoPath = path.join(skillsDir, "events.fifo"); + const externalDir = path.join(root, "outside"); + const externalFile = path.join(externalDir, "untouched.txt"); + const escapePath = path.join(skillsDir, "escape"); + const invalidRoot = path.join(configDir, "workspace-host"); + fs.mkdirSync(skillsDir); + fs.mkdirSync(externalDir); + fs.writeFileSync(firstPath, "same inode\n"); + fs.linkSync(firstPath, secondPath); + fs.writeFileSync(externalFile, "untouched\n"); + fs.symlinkSync(externalDir, escapePath); + fs.symlinkSync(externalDir, invalidRoot); + expect(spawnSync("mkfifo", [fifoPath]).status).toBe(0); + + const result = runGuard("lock", configDir); + + expect(result.status, result.stderr).toBe(0); + expect(fs.statSync(firstPath).ino).not.toBe(fs.statSync(secondPath).ino); + expect(fs.existsSync(fifoPath)).toBe(false); + expect(fs.existsSync(escapePath)).toBe(false); + expect(fs.existsSync(invalidRoot)).toBe(false); + expect(fs.readFileSync(externalFile, "utf-8")).toBe("untouched\n"); + expect(result.lines.at(-1)).toEqual( + expect.objectContaining({ type: "result", status: "ok", removedEntries: 3 }), + ); + }); +}); diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 53cc64eee93..bd16436537d 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -38,6 +38,8 @@ export type ConnectHarnessOptions = { wasRunning?: boolean; recovered?: boolean; forwardRecovered?: boolean; + forwardRecoveryFailed?: boolean; + forwardRecoveryFailureDetail?: string; secretBoundaryRefused?: boolean; secretBoundaryReason?: SecretBoundaryRefusalReason; }; diff --git a/test/test-boundary-guards.test.ts b/test/test-boundary-guards.test.ts index 596d09160d1..f124addb872 100644 --- a/test/test-boundary-guards.test.ts +++ b/test/test-boundary-guards.test.ts @@ -20,6 +20,7 @@ describe("compiled-test import boundary", () => { it("detects every supported compiled-internal reference shape", () => { const specifier = (target: string) => ["..", "dist", target].join("/"); const fixture = [ + 'import path from "node:path";', `import value from ${JSON.stringify(specifier("lib/value.js"))};`, `export { value } from ${JSON.stringify(specifier("commands/value.js"))};`, `require(${JSON.stringify(specifier("lib/required.js"))});`, @@ -39,6 +40,378 @@ describe("compiled-test import boundary", () => { ); }); + it("detects createRequire aliases, constants, type imports, and generated scripts", () => { + const specifier = (target: string) => ["..", "dist", target].join("/"); + const embeddedScript = [ + "const script = String.raw`", + `const dist = (...parts) => path.join(root, ${JSON.stringify("dist")}, ${JSON.stringify("lib")}, ...parts);`, + 'require(dist("runner.js"));', + "`;", + ].join("\n"); + const fixture = [ + 'import { createRequire } from "node:module";', + "const load = createRequire(import.meta.url);", + `load(${JSON.stringify(specifier("lib/aliased.js"))});`, + `const resolvedTarget = ${JSON.stringify(specifier("commands/resolved.js"))};`, + "load.resolve(resolvedTarget);", + `type Loaded = typeof import(${JSON.stringify(specifier("lib/typed.js"))});`, + `const generated = path.resolve(${JSON.stringify("dist/lib/generated.js")});`, + embeddedScript, + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(5); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + expect.stringContaining("aliased.js"), + expect.stringContaining("resolved.js"), + expect.stringContaining("typed.js"), + "constructs a path into dist/lib", + ]), + ); + expect( + violations.filter(({ detail }) => detail === "constructs a path into dist/lib"), + ).toHaveLength(2); + }); + + it("resolves aliases and constants in their lexical scope", () => { + const fixture = [ + 'const target = "../dist/lib/real.js";', + "require(target);", + "{", + ' const target = "../src/lib/safe.js";', + " require(target);", + "}", + "const load = createRequire(import.meta.url);", + "function useInjectedLoader(load: (value: string) => unknown) {", + ' load("../dist/lib/shadowed.js");', + "}", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("real.js"); + }); + + it("ignores inert text and shadowed built-in helpers", () => { + const fixture = [ + '// require("../dist/lib/comment.js");', + "const generatedExample = 'require(\"../dist/lib/inert.js\");';", + "function useSafeHelpers(require: (value: string) => unknown, path: unknown) {", + ' require("../dist/commands/shadowed.js");', + ' path.resolve("dist", "lib", "shadowed.js");', + "}", + 'require("../src/lib/source.js");', + ].join("\n"); + + expect(findCompiledInternalViolations("test/example.test.ts", fixture)).toEqual([]); + }); + + it("detects CommonJS and TypeScript path aliases", () => { + const fixture = [ + 'const commonJsPath = require("node:path");', + 'commonJsPath.join(root, "dist", "lib", "commonjs.js");', + 'import importEqualsPath = require("node:path");', + 'importEqualsPath.resolve(root, "dist", "commands", "import-equals.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(2); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + "constructs a path into dist/lib", + "constructs a path into dist/commands", + ]), + ); + }); + + it("detects createRequire destructured from CommonJS module imports", () => { + const fixture = [ + 'const { createRequire: makeRequire } = require("node:module");', + "const load = makeRequire(import.meta.url);", + 'load("../dist/lib/commonjs-create-require.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("commonjs-create-require.js"); + }); + + it("detects direct and namespace-qualified createRequire calls", () => { + const fixture = [ + 'import { createRequire } from "node:module";', + 'import * as nodeModule from "node:module";', + 'createRequire(import.meta.url)("../dist/lib/direct-create-require.js");', + 'nodeModule.createRequire(import.meta.url)("../dist/commands/namespace-create-require.js");', + 'const commonJsModule = require("node:module");', + 'commonJsModule.createRequire(import.meta.url)("../dist/lib/commonjs-namespace.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(3); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + expect.stringContaining("direct-create-require.js"), + expect.stringContaining("namespace-create-require.js"), + expect.stringContaining("commonjs-namespace.js"), + ]), + ); + }); + + it("unwraps JavaScript and TypeScript expression wrappers around static loaders", () => { + const fixture = [ + 'require(("../dist/lib/parenthesized.js"));', + 'import(("../dist/commands/dynamic.js"));', + 'require.resolve(("../dist/lib/resolved.js"));', + 'const asserted = "../dist/lib/asserted.js" as const;', + "require(asserted);", + 'const satisfied = "../dist/commands/satisfied.js" satisfies string;', + "require(satisfied);", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(5); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + expect.stringContaining("parenthesized.js"), + expect.stringContaining("dynamic.js"), + expect.stringContaining("resolved.js"), + expect.stringContaining("asserted.js"), + expect.stringContaining("satisfied.js"), + ]), + ); + }); + + it("detects compiled internals in TypeScript import-equals declarations", () => { + const fixture = [ + 'import compiled = require("../dist/lib/import-equals.js");', + 'export import exported = require("../dist/commands/export-import-equals.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(2); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + expect.stringContaining("import-equals.js"), + expect.stringContaining("export-import-equals.js"), + ]), + ); + }); + + it("preserves static String.raw substitutions while scanning generated scripts", () => { + const fixture = [ + "const script = String.raw`", + 'require(${JSON.stringify("../dist/lib/generated-substitution.js")});', + "`;", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("generated-substitution.js"); + }); + + it("detects aliased and inline CommonJS createRequire factories", () => { + const fixture = [ + 'import * as nodeModule from "node:module";', + "const makeRequire = nodeModule.createRequire;", + "const load = makeRequire(import.meta.url);", + 'load("../dist/lib/member-alias.js");', + 'require("node:module").createRequire(import.meta.url)("../dist/commands/inline.js");', + "const { createRequire: destructuredFactory } = nodeModule;", + "const destructuredLoad = destructuredFactory(import.meta.url);", + 'destructuredLoad("../dist/lib/destructured-member.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(3); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + expect.stringContaining("member-alias.js"), + expect.stringContaining("inline.js"), + expect.stringContaining("destructured-member.js"), + ]), + ); + }); + + it("detects named, destructured, and inline CommonJS path builders", () => { + const fixture = [ + 'import { join as namedJoin } from "node:path";', + 'require(namedJoin(repoRoot, "dist", "lib", "named.js"));', + 'const { resolve: destructuredResolve } = require("node:path");', + 'require(destructuredResolve(repoRoot, "dist", "commands", "destructured.js"));', + 'require(require("node:path").join(repoRoot, "dist", "lib", "inline.js"));', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(3); + expect(violations.map(({ detail }) => detail)).toEqual( + expect.arrayContaining([ + "constructs a path into dist/lib", + "constructs a path into dist/commands", + ]), + ); + }); + + it("pre-resolves constants used by earlier closures", () => { + const fixture = [ + "function loadCompiledModule() {", + " require(TARGET);", + "}", + 'const TARGET = "../dist/lib/later.js";', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("later.js"); + }); + + it("keeps switch bindings inside the shared case scope", () => { + const fixture = [ + "switch (mode) {", + " case 0:", + ' require("../dist/lib/shadowed-before-declaration.js");', + " break;", + " case 1:", + " const require = injectedLoader;", + " break;", + "}", + 'require("../dist/lib/outer.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("outer.js"); + }); + + it("evaluates switch discriminants outside the shared case scope", () => { + const fixture = [ + 'switch (require("../dist/lib/discriminant.js")) {', + " case 0:", + " const require = injectedLoader;", + " break;", + "}", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("discriminant.js"); + }); + + it("evaluates computed method names outside the method parameter scope", () => { + const fixture = [ + "const methods = {", + ' [require("../dist/lib/computed-name.js")](require: unknown) {},', + "};", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("computed-name.js"); + }); + + it("evaluates method decorators outside the method parameter scope", () => { + const fixture = [ + "class Decorated {", + ' @register(require("../dist/lib/decorator.js"))', + " run(require: unknown) {}", + "}", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("decorator.js"); + }); + + it("evaluates parameter decorators outside the method parameter scope", () => { + const fixture = [ + "class Decorated {", + ' run(@register(require("../dist/lib/parameter-decorator.js")) value: unknown, require: unknown) {}', + "}", + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toContain("parameter-decorator.js"); + }); + + it("normalizes static path traversal before classifying compiled targets", () => { + const fixture = [ + 'import path from "node:path";', + 'path.join(root, "dist", "lib", "..", "src", "safe.js");', + 'path.resolve(root, "dist", "commands", "..", "src", "safe.js");', + 'path.join(root, "dist", "lib", "nested", "..", "compiled.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toEqual([ + { + file: "test/example.test.ts", + line: 4, + detail: "constructs a path into dist/lib", + }, + ]); + }); + + it("does not hoist namespace or class-static var bindings into the file", () => { + const fixture = [ + "class Example {", + " static { var require = injectedLoader; void require; }", + "}", + "namespace Fixtures {", + " var path = injectedPath;", + "}", + 'require("../dist/lib/outer.js");', + 'path.join(root, "dist", "commands", "outer.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(2); + }); + + it("treats TypeScript namespace names as lexical bindings", () => { + const fixture = [ + "namespace path {", + ' export function resolve(..._parts: string[]) { return "safe"; }', + "}", + 'path.resolve("dist", "lib", "namespace-member.js");', + ].join("\n"); + + expect(findCompiledInternalViolations("test/example.test.ts", fixture)).toEqual([]); + }); + + it("keeps named class-expression bindings inside the class", () => { + const fixture = [ + "const Example = class path {", + ' static resolve(...parts: string[]) { return parts.join("/"); }', + ' static built = path.resolve("dist", "lib", "inner-name.js");', + "};", + 'path.resolve("dist", "commands", "outer.js");', + ].join("\n"); + + const violations = findCompiledInternalViolations("test/example.test.ts", fixture); + + expect(violations).toHaveLength(1); + expect(violations[0]?.detail).toBe("constructs a path into dist/commands"); + }); + it("scans ordinary tests while preserving explicit package, live, and fixture lanes", () => { expect(isScannedTestPath("src/lib/example.test.ts")).toBe(true); expect(isScannedTestPath("test/example.test.ts")).toBe(true); diff --git a/tools/e2e/hermes-dashboard-workflow-boundary.mts b/tools/e2e/hermes-dashboard-workflow-boundary.mts index 82ddb7953dc..1e352bd316f 100644 --- a/tools/e2e/hermes-dashboard-workflow-boundary.mts +++ b/tools/e2e/hermes-dashboard-workflow-boundary.mts @@ -10,6 +10,13 @@ const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); const DEFAULT_WORKFLOW_PATH = join(REPO_ROOT, ".github", "workflows", "e2e.yaml"); const JOB_NAME = "hermes-dashboard"; +// Dashboard recovery has a distinct trust boundary: it alone enables the +// dashboard mode, receives the inference secret at step scope, and must report +// its result before the PR scorecard is published. Keep those invariants in a +// focused validator, matching the repository's other security-posture and +// sandbox-operations workflow-boundary helpers, instead of duplicating them in +// an untyped YAML-shape assertion. + type WorkflowStep = { env?: Record<string, unknown>; name?: string; @@ -50,6 +57,14 @@ export function validateHermesDashboardWorkflow(workflow: HermesDashboardWorkflo const job = workflow.jobs[JOB_NAME] ?? {}; const env = job.env ?? {}; + for (const [jobName, candidate] of Object.entries(workflow.jobs)) { + if (jobName !== JOB_NAME && candidate.env?.NEMOCLAW_E2E_HERMES_DASHBOARD !== undefined) { + errors.push( + `only ${JOB_NAME} may enable Hermes dashboard E2E coverage (found on ${jobName})`, + ); + } + } + requireEqual(errors, job.needs, "generate-matrix", `${JOB_NAME} must depend on generate-matrix`); requireEqual(errors, job["runs-on"], "ubuntu-latest", `${JOB_NAME} must run on ubuntu-latest`); requireEqual(errors, job["timeout-minutes"], 75, `${JOB_NAME} timeout must be 75 minutes`);