diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index dd8fd896ed4..433814e4bb8 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -120,7 +120,11 @@ COPY agents/hermes/mcp-config-transaction.py /usr/local/lib/nemoclaw/hermes-mcp- COPY agents/hermes/cron-restore-control.py /usr/local/lib/nemoclaw/hermes-cron-restore-control.py COPY src/lib/actions/sandbox/openshell-child-visible-credentials.v0.0.101.json /usr/local/lib/nemoclaw/openshell-child-visible-credentials.v0.0.101.json COPY scripts/state-dir-guard.py /usr/local/lib/nemoclaw/state-dir-guard.py +COPY scripts/runtime-state-mutation-control.py /usr/local/lib/nemoclaw/runtime-state-mutation-control.py +COPY scripts/runtime-state-mutation-startup-gate.py /usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py +COPY scripts/runtime_state_mutation_hermes_publisher.py /usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py COPY agents/hermes/state-lock-plan.json /usr/local/share/nemoclaw/state-lock-plan.json +COPY agents/hermes/runtime-state-mutation-publisher-v1.json /usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ FROM scratch AS hermes-wrapper-payload @@ -400,7 +404,10 @@ RUN managed_runtime_assertion_failed() { \ && test -f /usr/local/lib/nemoclaw/managed-bootstrap-trampoline.sh \ && test ! -L /usr/local/lib/nemoclaw/managed-bootstrap-trampoline.sh \ && test "$(stat -c '%u:%g:%a' /usr/local/lib/nemoclaw/managed-bootstrap-trampoline.sh)" = '0:0:444' \ - && install -d -o root -g root -m 0755 /run/nemoclaw + && install -d -o root -g root -m 0755 /run/nemoclaw /var/lib/nemoclaw \ + && install -d -o root -g root -m 0711 \ + /run/nemoclaw/runtime-state-mutation-startup \ + /var/lib/nemoclaw/runtime-state-mutation # Ensure sandbox user can read blueprint files copied as root RUN chmod -R a+rX /opt/nemoclaw-blueprint/ @@ -415,12 +422,14 @@ RUN chmod -R a+rX /opt/nemoclaw-blueprint/ # 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/bin/nemoclaw-managed-startup-hold /usr/local/bin/nemoclaw-managed-bootstrap /usr/local/lib/nemoclaw/sandbox-init.sh /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py /usr/local/lib/nemoclaw/patch-hermes-session-list-preview.py /usr/local/lib/nemoclaw/patch-hermes-sqlite-temp-store.py /usr/local/lib/nemoclaw/patch-hermes-discord-recovery-permissions.py /usr/local/lib/nemoclaw/patch-hermes-profile-policy-defaults.py /usr/local/lib/nemoclaw/seed-hermes-dashboard-config.py /usr/local/lib/nemoclaw/hermes-runtime-config-guard.py /usr/local/lib/nemoclaw/finalize-tirith-marker.py /usr/local/lib/nemoclaw/hermes-mcp-config-transaction.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/share/nemoclaw/state-lock-plan.json /usr/local/lib/nemoclaw/managed-gateway-control.py /usr/local/lib/nemoclaw/build-hermes-mcp-digest.py /usr/local/lib/nemoclaw/hermes-cron-restore-control.py /usr/local/lib/nemoclaw/openshell-child-visible-credentials.v0.0.101.json \ + && 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/runtime-state-mutation-control.py /usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py /usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py /usr/local/share/nemoclaw/state-lock-plan.json /usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json /usr/local/lib/nemoclaw/managed-gateway-control.py /usr/local/lib/nemoclaw/build-hermes-mcp-digest.py /usr/local/lib/nemoclaw/hermes-cron-restore-control.py /usr/local/lib/nemoclaw/openshell-child-visible-credentials.v0.0.101.json \ && chmod 700 /usr/local/bin/nemoclaw-gateway-control /usr/local/lib/nemoclaw/hermes-cron-restore-control.py \ - && chmod 500 /usr/local/lib/nemoclaw/state-dir-guard.py /usr/local/lib/nemoclaw/managed-gateway-control.py \ - && chmod 444 /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /usr/local/share/nemoclaw/state-lock-plan.json /usr/local/lib/nemoclaw/gateway-supervisor.sh /usr/local/lib/nemoclaw/build-hermes-mcp-digest.py /usr/local/lib/nemoclaw/managed_policy.py \ + && chmod 500 /usr/local/lib/nemoclaw/state-dir-guard.py /usr/local/lib/nemoclaw/runtime-state-mutation-control.py /usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py /usr/local/lib/nemoclaw/managed-gateway-control.py \ + && chmod 555 /usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py \ + && chmod 444 /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /usr/local/share/nemoclaw/state-lock-plan.json /usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json /usr/local/lib/nemoclaw/gateway-supervisor.sh /usr/local/lib/nemoclaw/build-hermes-mcp-digest.py /usr/local/lib/nemoclaw/managed_policy.py \ && chmod 444 /usr/local/lib/nemoclaw/patch-hermes-langfuse-credentials.mts \ && chmod 444 /usr/local/lib/nemoclaw/openshell-child-visible-credentials.v0.0.101.json \ + && /opt/hermes/.venv/bin/python3 -I -c 'import runpy, yaml; assert yaml.safe_load("ready: true")["ready"] is True; runpy.run_path("/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", run_name="nemoclaw_runtime_state_mutation_control_probe"); runpy.run_path("/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py", run_name="nemoclaw_runtime_state_mutation_publisher_probe"); runpy.run_path("/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py", run_name="nemoclaw_runtime_state_mutation_gate_probe"); runpy.run_path("/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", run_name="nemoclaw_runtime_config_guard_probe")' \ && 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 {} + \ @@ -1243,6 +1252,12 @@ RUN check_metadata() { \ && check_metadata /usr/local/lib/nemoclaw/managed-bootstrap-trampoline.sh 'root:root 444' \ && check_metadata /usr/local/bin/nemoclaw-gateway-control 'root:root 700' \ && check_metadata /usr/local/share/nemoclaw/state-lock-plan.json 'root:root 444' \ + && check_metadata /usr/local/lib/nemoclaw/runtime-state-mutation-control.py 'root:root 500' \ + && check_metadata /usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py 'root:root 555' \ + && check_metadata /usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py 'root:root 500' \ + && check_metadata /var/lib/nemoclaw/runtime-state-mutation 'root:root 711' \ + && check_metadata /run/nemoclaw/runtime-state-mutation-startup 'root:root 711' \ + && check_metadata /usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json 'root:root 444' \ && check_metadata /usr/local/lib/nemoclaw/hermes-cron-restore-control.py 'root:root 700' \ && check_metadata /usr/local/lib/nemoclaw/preloads/sandbox-safety-net.js 'root:root 444' \ && check_metadata /usr/local/lib/nemoclaw/hermes-wrapper.py 'root:root 755' \ diff --git a/agents/hermes/runtime-state-mutation-publisher-v1.json b/agents/hermes/runtime-state-mutation-publisher-v1.json new file mode 100644 index 00000000000..efdb235d672 --- /dev/null +++ b/agents/hermes/runtime-state-mutation-publisher-v1.json @@ -0,0 +1 @@ +{"schemaVersion":1,"protocol":"nemoclaw-runtime-state-mutation-publisher-v1","agent":"hermes","providerId":"docker","stateRoot":"/sandbox/.hermes","planSchemaVersion":2,"entrypoint":"/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"} diff --git a/agents/hermes/start.sh b/agents/hermes/start.sh index fe40e6c728c..a7c25675a28 100755 --- a/agents/hermes/start.sh +++ b/agents/hermes/start.sh @@ -19,6 +19,105 @@ set -euo pipefail # SECURITY: Lock down PATH before resolving or sourcing root startup helpers. export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +NEMOCLAW_RUNTIME_STATE_MUTATION_RETRY_ARGV=("$@") + +# The provider gate is a fixed root-owned file beneath a search-only directory +# outside /sandbox, so the sandbox identity cannot rename either the gate or +# its parent. Run the immutable validator as this shell's direct child before +# sourcing helpers or reading mutable state; its permit is bound to this exact +# process identity. Invalid or uninspectable gate state is a hold, never an +# availability-to-integrity downgrade. +readonly NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_PYTHON="/opt/hermes/.venv/bin/python3" +readonly NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER="/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py" +readonly NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_SETPRIV="/usr/bin/setpriv" + +if [ ! -x "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_PYTHON" ] \ + || [ ! -f "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER" ] \ + || [ -L "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER" ] \ + || { [ "$EUID" -eq 0 ] && [ ! -x "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_SETPRIV" ]; }; then + printf '%s\n' '[SECURITY] Required runtime state mutation startup gate is unavailable.' >&2 + exit 1 +fi + +nemoclaw_runtime_state_mutation_gate() { + local action="$1" + if [ "$EUID" -eq 0 ]; then + "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_SETPRIV" \ + --reuid=sandbox --regid=sandbox --init-groups -- \ + "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_PYTHON" -I \ + "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER" "$action" >/dev/null + return + fi + "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_PYTHON" -I \ + "$NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER" "$action" >/dev/null +} + +nemoclaw_runtime_state_mutation_retry_exec() { + local status + if nemoclaw_runtime_state_mutation_gate restart; then + status=0 + else + status=$? + fi + if [ "$status" -eq 12 ]; then + exec /usr/local/bin/nemoclaw-start \ + "${NEMOCLAW_RUNTIME_STATE_MUTATION_RETRY_ARGV[@]}" + fi + printf '%s\n' '[SECURITY] Runtime state mutation retry was not authenticated; holding startup.' >&2 + kill -STOP "$$" +} +trap nemoclaw_runtime_state_mutation_retry_exec USR2 + +while :; do + if nemoclaw_runtime_state_mutation_gate admit; then + break + else + _nemoclaw_runtime_state_mutation_gate_status=$? + fi + case "$_nemoclaw_runtime_state_mutation_gate_status" in + 10) break ;; + 75) + printf '%s\n' '[SECURITY] Hermes startup held by an active runtime state mutation.' >&2 + /bin/sleep 1 || true + ;; + *) + printf '%s\n' '[SECURITY] Runtime state mutation startup gate failed.' >&2 + exit 1 + ;; + esac +done +unset _nemoclaw_runtime_state_mutation_gate_status + +# Publish a candidate only after the complete gateway topology is healthy. +# The shell then stops itself until the root controller has independently +# authenticated the candidate, frozen the exact process tree, and published a +# release receipt. Calling this with no active mutation is a cheap no-op. +nemoclaw_runtime_state_mutation_checkpoint() { + local status + if nemoclaw_runtime_state_mutation_gate checkpoint; then + return 0 + else + status=$? + fi + if [ "$status" -ne 11 ]; then + printf '%s\n' '[SECURITY] Runtime state mutation startup checkpoint was refused; holding startup.' >&2 + kill -STOP "$$" + return 1 + fi + kill -STOP "$$" + if nemoclaw_runtime_state_mutation_gate resume; then + return 0 + else + status=$? + fi + if [ "$status" -eq 12 ]; then + exec /usr/local/bin/nemoclaw-start \ + "${NEMOCLAW_RUNTIME_STATE_MUTATION_RETRY_ARGV[@]}" + fi + printf '%s\n' '[SECURITY] Runtime state mutation release receipt was not authenticated; holding startup.' >&2 + kill -STOP "$$" + return 1 +} # managed-entrypoint-env-wrapper begin _NEMOCLAW_ENTRYPOINT_ENV_WRAPPER="/usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh" @@ -127,6 +226,7 @@ exec > >(tee -a "$_START_LOG") 2> >(tee -a "$_START_LOG" >&2) drop_capabilities /usr/local/bin/nemoclaw-start "$@" NEMOCLAW_CMD=("$@") +NEMOCLAW_RUNTIME_STATE_MUTATION_RETRY_ARGV=("${NEMOCLAW_CMD[@]}") _chat_ui_url_port() { [ -n "${CHAT_UI_URL:-}" ] || return 1 @@ -2908,6 +3008,11 @@ handle_hermes_gateway_control_request() { return 1 fi refresh_hermes_supervised_child_pids + nemoclaw_runtime_state_mutation_checkpoint || { + stop_hermes_gateway_fail_closed + gateway_control_fail internal "$old_pid" + return 1 + } gateway_control_complete ok "$old_pid" "$GATEWAY_PID" } @@ -3136,6 +3241,7 @@ recover_hermes_gateway_current_user() { return 1 fi refresh_hermes_supervised_child_pids + nemoclaw_runtime_state_mutation_checkpoint || return 1 return 0 fi echo "[gateway] Hermes auxiliary repair failed; retrying while the exact gateway remains healthy" >&2 @@ -3228,6 +3334,7 @@ bootstrap_hermes_gateway_current_user() { return 1 fi refresh_hermes_supervised_child_pids + nemoclaw_runtime_state_mutation_checkpoint || return 1 return 0 fi @@ -3243,6 +3350,7 @@ bootstrap_hermes_gateway_current_user() { sleep 2 || true recover_hermes_gateway_current_user || return 1 refresh_hermes_supervised_child_pids + nemoclaw_runtime_state_mutation_checkpoint || return 1 } # ── Main ───────────────────────────────────────────────────────── @@ -3371,6 +3479,7 @@ if ! "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" publish-startup-ready echo "[gateway-control] failed to publish Hermes startup readiness" >&2 exit 1 fi +nemoclaw_runtime_state_mutation_checkpoint || exit 1 print_dashboard_urls # PID 1 remains alive even when Hermes stops its gateway. Host recovery uses diff --git a/docs/inference/set-up-llama-cpp.mdx b/docs/inference/set-up-llama-cpp.mdx index 9add8e5e69d..f47315995fe 100644 --- a/docs/inference/set-up-llama-cpp.mdx +++ b/docs/inference/set-up-llama-cpp.mdx @@ -83,6 +83,9 @@ The default recipe serves NVIDIA Nemotron 3 Nano 30B-A3B through the OpenAI Chat This path is an experimental implementation. It does not establish a supported agent, model, and runtime tuple until the protected qualification and activation gates pass. +The protected qualification runner requires Docker Engine `28.3.3` or newer and the trusted daemon's default protected NAT and firewall behavior; it re-queries the live daemon and consumes a fresh single-use authority immediately before each temporary loopback publication. +That requirement supersedes older Docker 27 qualification evidence. +Ordinary managed onboarding does not publish a Docker port: it retains its no-publication container contract and uses the host-owned private bridge, so this runner-specific version floor does not apply to onboarding. Before you start, confirm these prerequisites: @@ -135,7 +138,7 @@ Onboarding performs these actions: - Reuses a verified GGUF from the shared `~/.cache/huggingface/` cache, or acquires the exact file through the existing Hugging Face mechanism when it is absent or invalid. - Verifies the GGUF size and SHA-256 digest before it starts the runtime. - Runs the authenticated container as the current non-root user with one NVIDIA GPU and no CPU fallback. -- Starts a private host bridge on `127.0.0.1:8081` and connects the container to a Docker internal network without publishing a container port. +- Starts a host-owned private bridge on `127.0.0.1:8081` and connects the container to a Docker internal network without a Docker-published port. - Registers `llama-cpp-local` and routes agent traffic through `https://inference.local/v1`. The runtime cannot download a model and has no egress on its internal Docker network. @@ -147,14 +150,17 @@ Selecting either runtime fails before model acquisition or runtime mutation and ## Verify the Managed Runtime -Run the managed runtime and route checks: +Run the managed runtime, route, and host-port checks: ```bash $$nemoclaw my-assistant status $$nemoclaw my-assistant doctor +docker inspect --format '{{json .HostConfig.PortBindings}}' nemoclaw-llama-cpp ``` Accept the result when `status` reports `Managed llama.cpp: running`, the inference route is `reachable`, and `doctor` exits with status `0`. +The Docker inspection output must be `{}`, confirming that the container has no Docker-published port. +The host-owned private bridge still listens on loopback. These checks do not establish agent and model qualification. `status` reports the recipe ID, model digest, image reference, endpoint, and lifecycle state without exposing the API key. diff --git a/docs/manage-sandboxes/runtime-controls.mdx b/docs/manage-sandboxes/runtime-controls.mdx index e13e1417f71..43d3d6f9bfb 100644 --- a/docs/manage-sandboxes/runtime-controls.mdx +++ b/docs/manage-sandboxes/runtime-controls.mdx @@ -93,7 +93,33 @@ NemoClaw binds the write to the SHA-256 digest of the matching read, temporarily `shields up` also publishes fresh config, environment, and compatibility-hash inodes so a descriptor opened before lockdown cannot retain write authority. Shields up keeps `/sandbox/.hermes/profiles/dashboard-home/` sandbox-owned at mode `0700` so the dashboard can update its isolated profile. Other Hermes profiles remain read-only during lockdown. -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. +The root-only mutation lock stays held through every Hermes host-side config write. +On the sealed-plan and compatibility Shields paths, it also stays held through the full `shields up` or `shields down` filesystem transition and verification, and lifecycle recovery that needs to seal those paths. + +Current NemoClaw-managed Hermes images on the Docker driver use the `provider-state-mutation-v2` runtime provider state mutation contract for Shields filesystem transitions. +NemoClaw selects this contract only when all these conditions apply: + +- The registered sandbox is a managed Hermes image. +- The sandbox registry records its lifecycle generation. +- The image exposes the exact root-owned capability installed by NemoClaw. + +An older managed image uses the sealed-plan transition only after NemoClaw proves that the capability is absent. +A custom image, including a legacy Dockerfile workflow, remains on its existing sealed-plan or compatibility contract and cannot opt in by adding a similarly named file. +An invalid capability that is present fails closed and requires a rebuild with a current managed image. + +The Docker provider binds each transition to the registered lifecycle generation, exact container, qualified Docker engine authority, mount namespace, `/sandbox/.hermes` inode, AgentDefinition-derived plan and projection, target posture, rollback posture, and fresh nonce. +Before the provider fence becomes active, NemoClaw drains any earlier privileged sandbox execution lease. +While the fence is active, new direct-container, SSH, and OpenShell command transports are rejected before a sandbox command starts. +The installed root-owned controller and Hermes publisher apply and verify the exact target posture, then the provider starts only the bound Hermes entrypoint and proves the replacement gateway and startup checkpoint before it releases the fence. + +The owner-only ledger under `~/.nemoclaw/state/runtime-provider-lifecycle/` survives a host controller restart and remains authoritative for recovery of the exact target. +The next Shields command, including `shields status`, must recover a retained fence before it can report or change posture. +Hermes startup also checks the image-owned startup gate before it reads mutable state and remains held when the runtime provider state mutation is active or cannot be authenticated. +While recovery is incomplete, do not: + +- Delete the ledger. +- Kill a held entrypoint. +- Use a manual container command to bypass the fence. 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`. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 61b6ffdeb37..ad735730a55 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1354,6 +1354,30 @@ Host-side gateway recovery uses the same per-sandbox serialization. + + +For a current NemoClaw-managed Hermes image on the Docker driver, `shields status` is a recovery and reconciliation command, not only a display command. +It first recovers any retained exact runtime provider state mutation, then applies and verifies the declared recursive posture. +A result exits with status `0` only after the command verifies that posture. +A status check can therefore complete work retained by an interrupted host process. + +If provider recovery restores lockdown while the persisted Shields posture still says mutable, status prints `ERROR (runtime-provider recovery restored lockdown)`, exits with status `2`, and tells you to retry the intended Shields transition. +If live verification of a mutable default or timed Shields down posture fails, status prints `NOT CONFIGURED (DRIFTED...)` or `DOWN (DRIFTED...)`, exits with status `2`, and directs you to run `$$nemoclaw shields up` to reconcile and verify lockdown. +Status does not report `UP`, `DOWN`, or mutable-default with exit status `0` when the provider cannot verify the exact recursive posture. + +While an exact provider fence is active, ordinary direct-container, SSH, and OpenShell command transports are refused before a sandbox process starts. +They report `Runtime provider state mutation owns direct-container execution for sandbox ''; retry after the provider fence is released.` +Recover and retry as follows: + +1. Let the active Shields or recovery command finish. +2. Run `$$nemoclaw shields status`. +3. Retry the original command only after provider verification completes and the command exits with status `0`. + +Older managed Hermes images use the sealed-plan transition only when the current provider capability is proved absent. +Custom images and legacy Dockerfile workflows remain on their existing transition contract and do not use `provider-state-mutation-v2`. + + + Before `shields down` opens a new window, NemoClaw must revoke any stale auto-restore timer authority. If marker cleanup fails, the command reports `Cannot revoke stale auto-restore timer authority` and stops before policy capture, state writes, config unlock, replacement-timer startup, or audit writes. The sandbox retains its existing configuration and policy posture, and the stale timer authority remains. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index 0843fa3397a..98cdd0d9334 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -87,6 +87,7 @@ Run `$$nemoclaw onboard` to register a sandbox again. | Path | Purpose | Safe to delete | |---|---|---| | `~/.nemoclaw/state/` | Operational coordination and history for lifecycle locks, shields transitions, timers, and audit events, local routing, and port-forward helpers. | No. Deleting it can disrupt an active operation and discard security or recovery context. | +| `~/.nemoclaw/state/runtime-provider-lifecycle/` | Owner-only durable transaction records, exact-target claims, recovery state, and release receipts for Docker runtime provider state mutations. The records bind the registered sandbox lifecycle, container and engine authority, mount namespace, state-root inode, normalized plan and projection, target and rollback postures, and transaction nonce. | No. A retained record is the authority that lets a later host process recover the exact transition and prevents another target from mutating the same runtime. Do not remove it manually. | | `~/.nemoclaw/snapshots/` | Copies of host `~/.openclaw` state and configured external roots created by blueprint migration and rollback flows. NemoClaw excludes known authentication-state files and strips recognized credential values from copied JSON, YAML, and `.env` files. | Only after you no longer need the corresponding rollback or restore point. The host CLI does not expose the direct runner's retention actions. | | `~/.nemoclaw/rebuild-backups/` | Host-side snapshots written by `backup-all`, `snapshot create`, and rebuild flows. | Only after you no longer need rollback or restore points. | | `~/.nemoclaw/backups/` | Workspace backups written by legacy backup helpers and some recovery flows. | Only after confirming you no longer need those workspace archives. | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 57d25be7323..358ee5bb137 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1339,6 +1339,34 @@ If a concurrent config or shields command reports `Hermes config mutation is alr 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`. +### A Hermes command reports that runtime provider state mutation owns direct-container execution + +A current managed Hermes image on the Docker driver can report this retryable refusal while an exact Shields provider fence is active: + +```text +Runtime provider state mutation owns direct-container execution for sandbox ''; retry after the provider fence is released. +``` + +The refused command did not start a process inside the sandbox. +Do not bypass the fence with manual `docker exec`, OpenShell, or SSH commands, and do not delete `~/.nemoclaw/state/runtime-provider-lifecycle/`. +Wait for the active Shields or recovery command to finish, then reconcile the retained authority from the host: + +```bash +$$nemoclaw shields status +``` + +Use the status result as follows: + +- If status reports verified `UP`, `DOWN`, or mutable-default posture and exits with status `0`, retry the original command. +- If status reports `runtime-provider recovery restored lockdown`, retry the intended `shields up` or `shields down` transition because provider verification rejected the persisted mutable posture. +- If status reports `DOWN (DRIFTED...)` or `NOT CONFIGURED (DRIFTED...)`, run `$$nemoclaw shields up`. + Open a new shields-down window only after `shields status` reports `UP` and exits with status `0`. + +Hermes can also log `[SECURITY] Hermes startup held by an active runtime state mutation.` before it reads mutable state. +Do not kill or manually restart the held entrypoint. +Run `$$nemoclaw shields status` from the host so NemoClaw can recover the exact retained target and authenticate the startup release. +If recovery still fails, preserve the owner-only lifecycle ledger and the complete error for diagnosis instead of removing a marker or changing in-sandbox permissions. + ### Hermes startup reports `HERMES_CONFIG_MUTATION_ORPHANED` This refusal means a root-owned config or shields transaction stopped without a safely recoverable complete state. diff --git a/docs/security/tcb-boundary.mdx b/docs/security/tcb-boundary.mdx index bb44615f3b1..9728576e6f7 100644 --- a/docs/security/tcb-boundary.mdx +++ b/docs/security/tcb-boundary.mdx @@ -35,6 +35,10 @@ The lifecycle boundary maintains these invariants. - 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 current managed Hermes image on the Docker driver accepts a runtime provider state mutation only through a qualified Docker executable and endpoint authority bound to the registered sandbox lifecycle and exact runtime target. +- The owner-only runtime provider lifecycle ledger survives host process exit, excludes a second target, and remains authoritative until exact recovery and release complete. +- An active provider fence drains an earlier privileged sandbox execution lease and rejects later direct-container, SSH, and OpenShell command transports before command resolution or process spawn. +- Hermes startup cannot read mutable state or admit the gateway while the image-owned startup gate reports an active, malformed, or unauthenticated runtime provider state mutation. - A failed or ambiguous proof stops the operation without reporting recovery or a successful Shields up transition. - The OpenShell-managed topology authenticates the host action but does not create gateway and agent UID isolation. @@ -48,6 +52,13 @@ A successful build does not replace review of privilege, process identity, descr | Component | Execution and privilege | Trusted input | Security responsibility | |---|---|---|---| | `scripts/state-dir-guard.py` | Current OpenClaw and Hermes images install a root-owned, mode `0500` copy at `/usr/local/lib/nemoclaw/state-dir-guard.py` and a generated plan at `/usr/local/share/nemoclaw/state-lock-plan.json`. A historical image that has the helper but no plan uses its co-bundled helper. An agent manifest with `state_lock_plan_in_image: false` selects the trusted host CLI copy over standard input to `python3 -I -` and a manifest-derived plan through authenticated root execution. Historical images that contain neither installed file use the same execution path. | Fixed paths and a bounded action contract. Current and host-injected transitions use a strict versioned path plan derived from the selected agent manifest. A historical co-bundled helper uses its reviewed legacy inventory. | Applies descriptor-rooted state-directory posture changes, rejects link and mount substitution, bounds traversal, and verifies the committed modes and ownership. The host refuses a filesystem transition for an image that contains the generated plan if the installed helper is missing or the plan differs from the current agent manifest. | +| `src/lib/shields/hermes-runtime-state-mutation.ts` | Runs in the host CLI after the Shields coordinator holds the per-sandbox transition authority. | The registered managed Hermes workload, lifecycle generation, exact root-owned image capability, current `AgentDefinition`, and a Docker provider that implements runtime provider state mutation. | Selects `provider-state-mutation-v2`, recovers a retained exact target before acquiring another one, preserves a restrictive fence after same-locked failure, rolls a failed same-mutable transition back to locked posture, and releases only after fresh activation proof. An older managed image falls back only when the capability is proved absent; an invalid present capability fails closed. | +| `src/lib/onboard/runtime-provider/docker-operation-authority.ts` | Runs in the host CLI under the operator account and invokes Docker without a shell from a fixed working directory and sanitized environment. | One qualified absolute Docker executable and its absolute interpreter chain; an absolute-only fixed `PATH`; the effective PATH-selected `docker-credential-*` executables and their interpreter chains; the effective SSH executable for an `ssh://` endpoint; the exact context, host, TLS, and endpoint bindings; and the non-`PATH` execution-environment digest. The complete `PATH` enters authority identity for host-local inference and `ssh://`. A local `sandbox-lifecycle` authority omits helper-free added directories from persisted identity while still binding selected delegated helpers. | Revalidates executable, interpreter, delegated-command, and engine-endpoint metadata before provider actions; rejects authority drift and unverified remote TCP; and prevents ambient Docker configuration or command delegation from redirecting a fenced runtime provider state mutation. | +| `src/lib/onboard/runtime-provider/persisted-engine-lifecycle.ts` and `~/.nemoclaw/state/runtime-provider-lifecycle/` | The host CLI manages an owner-only private directory and durable artifacts under the operator account. | An exact runtime target claim and phase-bound transaction, release receipt, or tombstone whose sandbox lifecycle, engine binding, container, state root, plan, projection, target, rollback, and nonce match. | Preserves recovery authority across host process restart, excludes a second target, advances only the exact transaction through `prepared`, `mutation-authorized`, `fence-established`, and `completed` phases, and releases only the matching claim. | +| `src/lib/sandbox/privileged-exec.ts` and `src/lib/adapters/sandbox/command-transport.ts` | Run in the host CLI and hold a privileged sandbox execution lease through command completion and transport cleanup. | The canonical per-sandbox host transition lock, the durable runtime target claim, and the exact registered container identity. | Drains an earlier execution lease before provider fencing and rejects later direct-container, OpenShell, and SSH execution before argument resolution or process spawn. One OpenShell lease covers its direct Docker fallback so transport selection cannot cross the fence. | +| `scripts/runtime-state-mutation-control.py` | The current managed Hermes image installs a root-owned, mode `0500` copy, invoked as root through the qualified Docker provider authority. | Fixed actions; exact container, engine, mount-namespace, state-root, plan, projection, posture, and nonce bindings; installed controller and publisher identities; and stable process evidence. | Establishes and verifies the in-container fence, stops the bound entrypoint and sandbox processes, invokes only the fixed Hermes publisher, starts only the bound entrypoint, requires a fresh healthy gateway and authenticated startup checkpoint, and retains restrictive state when release is not proved. | +| `scripts/runtime_state_mutation_hermes_publisher.py` | The current managed Hermes image installs a root-owned, mode `0500` copy that only the runtime provider state mutation controller imports. | The root-owned controller marker, nonce-bound canonical plan and projection, installed state-lock plan, exact state-root descriptor, and requested posture. | Applies the normalized Hermes recursive posture, publishes fresh protected inodes where required, maintains its root-only journal, verifies the result, and returns a bounded receipt to the controller. | +| `scripts/runtime-state-mutation-startup-gate.py` and `agents/hermes/start.sh` | The gate is root-owned and mode `0555`; the Hermes entrypoint invokes it before sourcing helpers or reading mutable state. | The exact parent process, root-owned controller handoff, active runtime provider state mutation identity, candidate checkpoint, and authenticated release for the same target. | Holds or refuses startup on active, malformed, uninspectable, or unauthenticated state, publishes a checkpoint only after the complete Hermes topology is healthy, and resumes only the controller-authenticated candidate. | | `scripts/lib/normalize_mutable_config_perms.py` | The installed copy is root-owned and mode `0555`; startup invokes it under the entrypoint identity, and only root can reclaim a root-owned tree. | The fixed OpenClaw config path, the resolved sandbox identity, and an exact `root:root 0700/0600` mutable-drift signature under the expected sandbox-owned parent. | Restores the mutable `2770/660` contract, pins every privileged handoff by descriptor, and rejects ambiguous posture, links, mount substitution, metadata races, and sealed config. | | `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. | @@ -75,6 +86,14 @@ flowchart LR Managed --> Config HostLock --> State[State directory guard] HostLock --> Verify[Shields lock verifier] + HostLock --> Mutation[Hermes runtime provider state mutation] + Mutation --> Ledger[Durable lifecycle ledger] + Mutation --> DockerAuthority[Qualified Docker authority] + DockerAuthority --> ProviderControl[Root runtime provider state mutation controller] + ProviderControl --> Publisher[Hermes state publisher] + ProviderControl --> StartupGate[Hermes startup gate] + Publisher --> Verify + StartupGate --> Gateway Config --> Gateway[Proven gateway process] State --> Verify ``` @@ -89,6 +108,11 @@ Shields mutations acquire the host transition lock before changing network polic The coordinator applies the selected agent's config transition, invokes `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. +For `provider-state-mutation-v2`, the coordinator first recovers any retained exact target, then acquires and repeatedly asserts the durable provider fence around publication and fresh Hermes activation. +An in-flight privileged execution lease drains before the fence becomes active, and later ordinary command transports are rejected before they resolve or spawn a sandbox command. +The fixed publisher applies the exact recursive target, the startup gate authenticates the candidate after the complete topology is healthy, and only then can the provider record release and let ordinary execution resume. +If the host process exits, the durable ledger and in-container fence remain the recovery authority for the next Shields command. + ## Filesystem and Descriptor Proofs Production Python guards bind privileged helpers and parser dependencies to fixed installed paths. @@ -131,6 +155,10 @@ The macOS VM compatibility path accepts a nonroot NemoClaw PID 1 when the VM own 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. +The Docker runtime provider state mutation path applies only to a current NemoClaw-managed Hermes image with the exact installed capability and a registered lifecycle generation. +An older managed image uses the sealed-plan path only after exact capability absence is proved. +Custom images and legacy Dockerfile workflows remain on their existing transition contract, and a present but invalid managed capability fails closed instead of falling back. + ## 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. @@ -142,9 +170,10 @@ The following conditions govern current compatibility code and architecture work - 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. +- Re-review the qualified Docker authority, durable provider ledger, privileged execution lease, provider controller, Hermes publisher, and startup gate together when any exact-target field, phase, mode, process proof, release condition, or retry boundary changes. The agent manifest declaration drives both generated image-plan selection and the derived `AgentDefinition` used by host wiring. Final-image validation must cover the recovery-capable OpenClaw and Hermes 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. +It checks helper owners and modes, the exact Hermes provider capability and publisher descriptor, root and gateway supplementary groups, root execution of the read-only `probe` path, and refusal before helper entry when the sandbox user attempts execution. Deep Agents uses the host-injected helper path instead of an installed recovery artifact. Host wiring tests validate helper selection and plan handoff, while the shared helper tests validate the descriptor-safe behavior; installed-helper metadata checks do not cover Deep Agents. diff --git a/scripts/checks/run-llama-cpp-dgx-spark-qualification.mts b/scripts/checks/run-llama-cpp-dgx-spark-qualification.mts index fbd6ccb04bd..bd00077c528 100644 --- a/scripts/checks/run-llama-cpp-dgx-spark-qualification.mts +++ b/scripts/checks/run-llama-cpp-dgx-spark-qualification.mts @@ -10,6 +10,9 @@ import { fileURLToPath } from "node:url"; import { buildLlamaCppRequestGuardDockerArgv, + consumeDockerLoopbackPublishAuthority, + type DockerLoopbackPublishAuthority, + qualifyDockerLoopbackPublishAuthority, type VerifiedLocalModelArtifact, } from "../../src/lib/inference/llama-cpp/host-local-runtime.ts"; import { @@ -29,7 +32,11 @@ import { runLlamaCppOpenClawAgentQualification } from "./llama-cpp-openclaw-agen import { resolveManagedImageLocalInferenceRoute } from "./managed-image-protected-runtime-contract.ts"; import { runManagedImageOpenShellE2e } from "./run-managed-image-openshell-e2e.ts"; -export { validateChatCompletionResponse, validateModelsResponse }; +export { + qualifyDockerLoopbackPublishAuthority, + validateChatCompletionResponse, + validateModelsResponse, +}; const sha256Pattern = /^sha256:[0-9a-f]{64}$/u; const gitShaPattern = /^[0-9a-f]{40}$/u; @@ -324,6 +331,7 @@ export function insertQualificationLoopbackPublishArgv( containerPort: number; hostPort?: number; imageReference: string; + loopbackPublishAuthority: DockerLoopbackPublishAuthority; }, ): string[] { const imageIndex = argv.indexOf(options.imageReference); @@ -358,6 +366,7 @@ export function insertQualificationLoopbackPublishArgv( options.hostPort === undefined ? "" : String(requiredInteger(options.hostPort, "qualification host port", 1, 65_535)); + consumeDockerLoopbackPublishAuthority(options.loopbackPublishAuthority); return [ ...argv.slice(0, imageIndex), "--publish", @@ -377,6 +386,7 @@ export function buildServerContainerArgv( registryOwner: string; runtimeGid: number; runtimeUid: number; + loopbackPublishAuthority: DockerLoopbackPublishAuthority; hostPort?: number; }, ): string[] { @@ -398,6 +408,7 @@ export function buildServerContainerArgv( containerPort: plan.recipe.serve.port, ...(options.hostPort === undefined ? {} : { hostPort: options.hostPort }), imageReference: options.imageReference, + loopbackPublishAuthority: options.loopbackPublishAuthority, }); } @@ -804,6 +815,7 @@ function startRegistry(names: RuntimeNames): void { if (dockerContainerOwner(names.registryName) !== null) { throw new Error("isolated registry name is already in use"); } + consumeDockerLoopbackPublishAuthority(qualifyLiveDockerLoopbackPublishAuthority()); runCommand( "docker", [ @@ -821,6 +833,12 @@ function startRegistry(names: RuntimeNames): void { ); } +function qualifyLiveDockerLoopbackPublishAuthority(): DockerLoopbackPublishAuthority { + return qualifyDockerLoopbackPublishAuthority( + runCommand("docker", ["version", "--format", "{{.Server.Version}}"]).toString("utf8"), + ); +} + function inspectBuiltImage( plan: QualificationPlan, invocation: QualificationInvocation, @@ -1016,6 +1034,7 @@ async function runQualification( registryOwner: names.registryOwner, runtimeGid, runtimeUid, + loopbackPublishAuthority: qualifyLiveDockerLoopbackPublishAuthority(), ...(plan.qualification.agentQualification.execution === "enabled" ? { hostPort: plan.recipe.serve.port } : {}), diff --git a/scripts/checks/run-managed-image-openshell-e2e.ts b/scripts/checks/run-managed-image-openshell-e2e.ts index a54123d33a8..1810c3bf66c 100644 --- a/scripts/checks/run-managed-image-openshell-e2e.ts +++ b/scripts/checks/run-managed-image-openshell-e2e.ts @@ -35,10 +35,14 @@ import type { RuntimeProviderBundle, } from "../../src/lib/onboard/runtime-provider/contract.ts"; import { createDockerRuntimeProviderBundle } from "../../src/lib/onboard/runtime-provider/docker.ts"; -import { prepareSandboxCreateLaunch } from "../../src/lib/onboard/sandbox-create-launch.ts"; +import { + OPENSHELL_SANDBOX_SUPERVISOR_ARGV, + prepareSandboxCreateLaunch, +} from "../../src/lib/onboard/sandbox-create-launch.ts"; import { resolveDockerStartupCommandPatch, runSandboxGpuCreateFlow, + type SandboxGpuCreateFlowInput, } from "../../src/lib/onboard/sandbox-gpu-create-flow.ts"; import { createDirectSandboxGpuVerifier } from "../../src/lib/onboard/sandbox-gpu-preflight.ts"; import { @@ -71,6 +75,22 @@ const MANAGED_AGENT_BASE_POLICIES: Record, + "expectedSupervisorArgv" +>; + +export function createProtectedManagedImageBootstrapInput( + input: ProtectedManagedImageBootstrapInput, +): NonNullable { + return Object.freeze({ + ...input, + expectedSupervisorArgv: MANAGED_IMAGE_OPENSHELL_SUPERVISOR_ARGV, + }); +} + function compactText(value = ""): string { return String(value).replace(/\s+/gu, " ").trim(); } @@ -877,7 +897,7 @@ async function run/dev/null)" == "$node_path" ]] || export PATH="$node_dir:\$PATH" exec "$cli_path" "\$@" EOF )" @@ -1885,7 +1887,9 @@ fix_npm_permissions() { fi done - export PATH="$HOME/.npm-global/bin:$PATH" + if [[ ":$PATH:" != *":$HOME/.npm-global/bin:"* ]]; then + export PATH="$HOME/.npm-global/bin:$PATH" + fi ok "npm configured for user-local installs (~/.npm-global)" } diff --git a/scripts/runtime-state-mutation-control.py b/scripts/runtime-state-mutation-control.py new file mode 100755 index 00000000000..55e91139bd7 --- /dev/null +++ b/scripts/runtime-state-mutation-control.py @@ -0,0 +1,4014 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Root-only hold for one exact runtime state mutation. + +The host may invoke only the fixed actions exposed by :func:`main`. Acquire +consumes the full bounded runtime and plan binding. Later actions consume one +exact observation plus the provider handle. The durable marker records the +exact OpenShell PID 1, its direct ``nemoclaw-start`` child, and each held +activation process. A controller restart can therefore re-establish or finish +only the original process fence. + +PID 1 remains stopped until release completes. This blocks OpenShell SSH and +exec admission while a root Docker exec can continue the transaction. The +helper also stops ``nemoclaw-start`` and terminates every other process that +uses the ``sandbox`` or ``gateway`` account. Activation resumes only the exact +entrypoint, proves a fresh Hermes gateway, and freezes the resulting process +tree before it returns evidence to the host. + +Posture transitions use the fixed, root-owned Hermes publisher module and +accept only its exact nonce-bound receipt. The host ledger remains +authoritative for publication completion. +""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import http.client +import importlib.util +import json +import os +import pwd +import re +import secrets +import select +import signal +import stat +import sys +import time +from dataclasses import dataclass +from typing import Literal + + +Action = Literal[ + "acquire", "assert", "publish", "rollback", "activate", "release", "recover" +] +Phase = Literal["fenced", "published", "rolled-back", "activation-proven"] + +SCHEMA_VERSION = 1 +PLAN_SCHEMA_VERSION = 2 +SUPPORTED_PROVIDER_ID = "docker" +SUPPORTED_STATE_ROOT = "/sandbox/.hermes" +SUPPORTED_WRITER_ACCOUNTS = ("gateway", "sandbox") + +MAX_ENVELOPE_BYTES = 128 * 1024 +MAX_PLAN_BYTES = 64 * 1024 +MAX_MARKER_BYTES = 160 * 1024 +MAX_PROC_ENTRIES = 32_768 +MAX_PROC_FILE_BYTES = 1024 * 1024 +MAX_CONFIG_GENERATION_BYTES = 64 * 1024 +MAX_ACTIVATION_PROCESSES = 256 +MAX_SELECTORS = 256 +MAX_STRING_BYTES = 4096 +TERM_SECONDS = 3.0 +KILL_SECONDS = 5.0 +PROCESS_STATE_SECONDS = 5.0 +ACTIVATION_SECONDS = 150.0 +HEALTH_SECONDS = 3.0 +STABLE_SCANS = 3 +POLL_SECONDS = 0.05 + +ROOT_UID = 0 +ROOT_GID = 0 +PROC_ROOT = "/proc" +MOUNT_NAMESPACE_PATH = "/proc/1/ns/mnt" +DURABLE_DIRECTORY = "/var/lib/nemoclaw/runtime-state-mutation" +RUNTIME_DIRECTORY = "/run/nemoclaw/runtime-state-mutation" +STARTUP_HANDOFF_DIRECTORY = "/run/nemoclaw/runtime-state-mutation-startup" +DURABLE_PARENT_MODE = 0o755 +DURABLE_DIRECTORY_MODE = 0o711 +RUNTIME_DIRECTORY_MODE = 0o700 +STARTUP_HANDOFF_PARENT_MODE = 0o711 +MARKER_NAME = "active.json" +LOCK_NAME = "control.lock" +SENTINEL_NAME = "hold.json" +ACTIVATION_RECEIPT_NAME = "activation.json" +ACTIVATION_PERMIT_NAME = "activation-permit.json" +ACTIVATION_RELEASE_NAME = "activation-release.json" +ACTIVATION_RETRY_NAME = "activation-retry.json" +ACTIVATION_CLEANUP_NAME = "activation-cleanup.json" +STARTUP_CANDIDATE_NAME = "startup-complete.json" +STARTUP_RETRY_ACK_NAME = "retry-ack.json" +RELEASED_RECEIPT_NAME = "released.json" +PUBLISHER_MODULE_PATH = ( + "/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py" +) +PUBLISHER_PROTOCOL = "nemoclaw-runtime-state-mutation-publisher-v1" +ACTIVATION_PERMIT_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-permit-v1" +ACTIVATION_RELEASE_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-release-v1" +ACTIVATION_RETRY_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-retry-v1" +ACTIVATION_CLEANUP_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-cleanup-v1" +STARTUP_CANDIDATE_PROTOCOL = "nemoclaw-runtime-state-mutation-startup-complete-v1" +STARTUP_RETRY_ACK_PROTOCOL = "nemoclaw-runtime-state-mutation-retry-ack-v1" +OPENSHELL_ARGV0 = b"/opt/openshell/bin/openshell-sandbox" +NEMOCLAW_START_PATH = b"/usr/local/bin/nemoclaw-start" +HERMES_GATEWAY_PATHS = (b"/usr/local/bin/hermes", b"/usr/local/bin/hermes.real") +HERMES_INTERNAL_PORT = 18642 +HERMES_HEALTH_PATH = "/health" +HERMES_CONFIG_GENERATION_PATH = "/sandbox/.hermes/.config-hash" + +HEX_64 = re.compile(r"[0-9a-f]{64}\Z") +SAFE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z") +RUNTIME_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/=+\-]{0,511}\Z") +MOUNT_NAMESPACE = re.compile(r"mnt:\[[1-9][0-9]*\]\Z") +PID_NAMESPACE = re.compile(r"pid:\[[1-9][0-9]*\]\Z") +DECIMAL = re.compile(r"(?:0|[1-9][0-9]*)\Z") +TOP_LEVEL = re.compile(r"[A-Za-z0-9._-]+\Z") +CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f-\x9f]") +PUBLISHER_ERROR_CODE = re.compile(r"[a-z][a-z0-9-]{0,127}\Z") +PHASES = frozenset(("fenced", "published", "rolled-back", "activation-proven")) +ACTIONS = frozenset( + ("acquire", "assert", "publish", "rollback", "activate", "release", "recover") +) + + +class ControlError(RuntimeError): + """A fixed-code, non-sensitive control failure.""" + + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +@dataclass(frozen=True) +class AcquireRequest: + transaction_id: str + provider_id: str + sandbox_name: str + lifecycle_generation: str + engine_binding_sha256: str + runtime_id: str + runtime_pid: int + sandbox_identity_sha256: str + container_mounts_sha256: str + state_root: str + state_root_mounts_sha256: str + plan_sha256: str + projection_sha256: str + nonce: str + plan: dict[str, object] + canonical_plan: str + target: str + rollback: str + + +@dataclass(frozen=True) +class StatusRequest: + action: Action + transaction_id: str + provider_id: str + sandbox_name: str + lifecycle_generation: str + engine_binding_sha256: str + runtime_id: str + runtime_pid: int + sandbox_identity_sha256: str + container_mounts_sha256: str + provider_handle: str | None + activation_provider_handle: str | None + completed_ledger_sha256: str | None + + +Request = AcquireRequest | StatusRequest + + +@dataclass(frozen=True) +class ProcessIdentity: + pid: int + state: str + parent_pid: int + start_identity: str + uids: tuple[int, int, int, int] + command: tuple[bytes, ...] + proc_device: int + proc_inode: int + + def identity_key(self) -> tuple[object, ...]: + return ( + self.pid, + self.parent_pid, + self.start_identity, + self.uids, + self.command, + self.proc_device, + self.proc_inode, + ) + + +@dataclass(frozen=True) +class ProcessReference: + pid: int + start_identity: str + parent_pid: int + uids: tuple[int, int, int, int] + command_sha256: str + proc_device: int + proc_inode: int + + +@dataclass(frozen=True) +class FenceProof: + supervisor: ProcessReference + start: ProcessReference + writer_uids: tuple[int, ...] + + +@dataclass(frozen=True) +class ActivationProof: + service_pid: int + service_start_identity: str + service_uid: int + configuration_generation: str + listener_identity: str + health_sha256: str + startup_checkpoint_sha256: str + persistent_pids: tuple[int, ...] + processes: tuple[ProcessReference, ...] + + +def _fail(code: str) -> None: + raise ControlError(code) + + +def _json_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + _fail("duplicate-json-field") + result[key] = value + return result + + +def _bounded_json_integer(value: str) -> int: + if len(value) > 10: + _fail("json-integer-out-of-range") + parsed = int(value, 10) + if parsed < 0 or parsed > 0x7FFFFFFF: + _fail("json-integer-out-of-range") + return parsed + + +def _reject_json_constant(_value: str) -> None: + _fail("non-finite-json-number") + + +def _reject_json_float(_value: str) -> None: + _fail("json-number-not-integer") + + +def _parse_json(raw: bytes, maximum: int, invalid_code: str) -> object: + if not raw or len(raw) > maximum or b"\x00" in raw: + _fail(invalid_code) + try: + text = raw.decode("utf-8", "strict") + value = json.loads( + text, + object_pairs_hook=_json_pairs, + parse_int=_bounded_json_integer, + parse_float=_reject_json_float, + parse_constant=_reject_json_constant, + ) + except ControlError: + raise + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + _fail(invalid_code) + return value + + +def _read_stdin() -> bytes: + raw = sys.stdin.buffer.read(MAX_ENVELOPE_BYTES + 1) + if len(raw) > MAX_ENVELOPE_BYTES: + _fail("envelope-too-large") + return raw + + +def _exact_keys( + value: object, expected: tuple[str, ...], code: str +) -> dict[str, object]: + if not isinstance(value, dict) or tuple(value.keys()) != expected: + _fail(code) + return value + + +def _bounded_string(value: object, pattern: re.Pattern[str], code: str) -> str: + if ( + not isinstance(value, str) + or not value + or value != value.strip() + or CONTROL_CHARACTERS.search(value) + or len(value.encode("utf-8", "strict")) > MAX_STRING_BYTES + or pattern.fullmatch(value) is None + ): + _fail(code) + return value + + +def _hex_digest(value: object, code: str) -> str: + return _bounded_string(value, HEX_64, code) + + +def _decimal_identity(value: object, code: str) -> str: + return _bounded_string(value, DECIMAL, code) + + +def _canonical_relative_path(value: object, code: str) -> str: + if not isinstance(value, str): + _fail(code) + try: + encoded = value.encode("utf-8", "strict") + except UnicodeEncodeError: + _fail(code) + if ( + not value + or len(encoded) > 512 + or value.startswith("/") + or "\\" in value + or CONTROL_CHARACTERS.search(value) + or os.path.normpath(value) != value + or any(part in ("", ".", "..") for part in value.split("/")) + ): + _fail(code) + return value + + +def _string_array(value: object, code: str, normalize) -> list[str]: + if not isinstance(value, list) or len(value) > MAX_SELECTORS: + _fail(code) + result = [normalize(item, code) for item in value] + if result != sorted(result, key=lambda item: item.encode("utf-8")) or len( + set(result) + ) != len(result): + _fail(code) + return result + + +def _top_level(value: object, code: str) -> str: + return _bounded_string(value, TOP_LEVEL, code) + + +def _writable_subpath(value: object, code: str) -> str: + path = _canonical_relative_path(value, code) + parts = path.split("/") + if ( + len(parts) < 2 + or any("*" in part and part != "*" for part in parts) + or parts[-1] == "*" + ): + _fail(code) + return path + + +def _writable_patterns_overlap(first: str, second: str) -> bool: + left = first.split("/") + right = second.split("/") + return all( + a == "*" or b == "*" or a == b for a, b in zip(left, right, strict=False) + ) + + +def _normalize_state_lock_plan(value: object) -> dict[str, object]: + plan = _exact_keys( + value, + ( + "version", + "readOnlyRoots", + "confidentialRoots", + "readOnlyPrefixes", + "confidentialPrefixes", + "writableSubpaths", + ), + "state-lock-plan-schema", + ) + if type(plan["version"]) is not int or plan["version"] != 1: + _fail("state-lock-plan-version") + read_only_roots = _string_array( + plan["readOnlyRoots"], "state-lock-plan-roots", _top_level + ) + confidential_roots = _string_array( + plan["confidentialRoots"], "state-lock-plan-roots", _top_level + ) + read_only_prefixes = _string_array( + plan["readOnlyPrefixes"], "state-lock-plan-prefixes", _top_level + ) + confidential_prefixes = _string_array( + plan["confidentialPrefixes"], "state-lock-plan-prefixes", _top_level + ) + writable_subpaths = _string_array( + plan["writableSubpaths"], "state-lock-plan-writable", _writable_subpath + ) + roots = read_only_roots + confidential_roots + prefixes = read_only_prefixes + confidential_prefixes + if len(set(roots)) != len(roots) or len(set(prefixes)) != len(prefixes): + _fail("state-lock-plan-policy-overlap") + if any(root.startswith(prefix) for root in roots for prefix in prefixes): + _fail("state-lock-plan-policy-overlap") + for index, prefix in enumerate(prefixes): + if any( + prefix.startswith(other) or other.startswith(prefix) + for other in prefixes[index + 1 :] + ): + _fail("state-lock-plan-policy-overlap") + if any(path.split("/", 1)[0] not in read_only_roots for path in writable_subpaths): + _fail("state-lock-plan-writable") + for index, pattern in enumerate(writable_subpaths): + if any( + _writable_patterns_overlap(pattern, other) + for other in writable_subpaths[index + 1 :] + ): + _fail("state-lock-plan-writable-overlap") + return { + "version": 1, + "readOnlyRoots": read_only_roots, + "confidentialRoots": confidential_roots, + "readOnlyPrefixes": read_only_prefixes, + "confidentialPrefixes": confidential_prefixes, + "writableSubpaths": writable_subpaths, + } + + +def _normalize_plan( + value: object, state_root: str, projection: str +) -> dict[str, object]: + plan = _exact_keys( + value, + ( + "schemaVersion", + "intent", + "target", + "rollback", + "stateLockPlan", + "stateRoot", + "selectors", + "projectionSha256", + ), + "plan-schema", + ) + if ( + type(plan["schemaVersion"]) is not int + or plan["schemaVersion"] != PLAN_SCHEMA_VERSION + ): + _fail("plan-version") + if plan["intent"] != "protection-transition": + _fail("plan-intent") + target = plan["target"] + rollback = plan["rollback"] + if target not in ("locked", "mutable") or rollback not in ("locked", "mutable"): + _fail("plan-posture") + if target == rollback: + _fail("plan-posture") + if plan["stateRoot"] != state_root or plan["projectionSha256"] != projection: + _fail("plan-binding") + state_lock_plan = _normalize_state_lock_plan(plan["stateLockPlan"]) + selectors_value = plan["selectors"] + if ( + not isinstance(selectors_value, list) + or not selectors_value + or len(selectors_value) > MAX_SELECTORS + ): + _fail("plan-selectors") + selectors: list[dict[str, str]] = [] + identities: list[str] = [] + for selector_value in selectors_value: + if not isinstance(selector_value, dict) or selector_value.get("kind") not in ( + "path", + "prefix", + ): + _fail("plan-selector-schema") + if selector_value["kind"] == "path": + selector = _exact_keys( + selector_value, ("kind", "path"), "plan-selector-schema" + ) + path = _canonical_relative_path(selector["path"], "plan-selector-path") + selectors.append({"kind": "path", "path": path}) + identities.append(f"path:{path}") + else: + selector = _exact_keys( + selector_value, ("kind", "prefix"), "plan-selector-schema" + ) + prefix = _top_level(selector["prefix"], "plan-selector-prefix") + selectors.append({"kind": "prefix", "prefix": prefix}) + identities.append(f"prefix:{prefix}") + if identities != sorted(identities, key=lambda item: item.encode("utf-8")) or len( + set(identities) + ) != len(identities): + _fail("plan-selector-order") + required = [ + *(f"path:{item}" for item in state_lock_plan["readOnlyRoots"]), + *(f"path:{item}" for item in state_lock_plan["confidentialRoots"]), + *(f"prefix:{item}" for item in state_lock_plan["readOnlyPrefixes"]), + *(f"prefix:{item}" for item in state_lock_plan["confidentialPrefixes"]), + ] + if any(identity not in identities for identity in required): + _fail("plan-selector-scope") + return { + "schemaVersion": PLAN_SCHEMA_VERSION, + "intent": "protection-transition", + "target": target, + "rollback": rollback, + "stateLockPlan": state_lock_plan, + "stateRoot": state_root, + "selectors": selectors, + "projectionSha256": projection, + } + + +def _json_bytes(value: object) -> bytes: + try: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode( + "utf-8", "strict" + ) + except (TypeError, ValueError, UnicodeEncodeError): + _fail("json-serialization") + + +def _sha256(payload: bytes) -> str: + return hashlib.sha256(payload).hexdigest() + + +ACQUIRE_KEYS = ( + "schemaVersion", + "action", + "transactionId", + "providerId", + "sandboxName", + "lifecycleGeneration", + "engineBindingSha256", + "runtimeId", + "runtimePid", + "sandboxIdentitySha256", + "containerMountsSha256", + "stateRoot", + "stateRootMountsSha256", + "plan", + "planSha256", + "projectionSha256", + "nonce", + "target", + "rollback", +) + +STATUS_KEYS = ( + "schemaVersion", + "action", + "transactionId", + "providerId", + "sandboxName", + "lifecycleGeneration", + "engineBindingSha256", + "runtimeId", + "runtimePid", + "sandboxIdentitySha256", + "containerMountsSha256", +) + +MARKER_KEYS = ( + "schemaVersion", + "phase", + "transactionId", + "providerId", + "sandboxName", + "lifecycleGeneration", + "engineBindingSha256", + "runtimeId", + "runtimePid", + "sandboxIdentitySha256", + "containerMountsSha256", + "stateRoot", + "stateRootMountsSha256", + "mountNamespace", + "stateRootDevice", + "stateRootInode", + "plan", + "planSha256", + "projectionSha256", + "nonce", + "target", + "rollback", + "fence", + "activation", +) + +RELEASED_RECEIPT_KEYS = ( + "schemaVersion", + "releaseState", + "transactionId", + "providerHandle", + "activationProviderHandle", + "completedLedgerSha256", + "marker", +) + +PROVIDER_HANDLE = re.compile( + r"docker-state-mutation-v1:([0-9a-f]{64}):([0-9a-f]{64})\Z" +) +ACTIVATION_PROVIDER_HANDLE = re.compile( + r"docker-state-mutation-activation-v1:([0-9a-f]{64}):([0-9a-f]{64})\Z" +) + + +def _canonical_state_root(value: object) -> str: + if not isinstance(value, str): + _fail("state-root") + try: + encoded = value.encode("utf-8", "strict") + except UnicodeEncodeError: + _fail("state-root") + if ( + not value.startswith("/sandbox/") + or value.endswith("/") + or "\\" in value + or CONTROL_CHARACTERS.search(value) + or len(encoded) > MAX_STRING_BYTES + or os.path.normpath(value) != value + ): + _fail("state-root") + if value != SUPPORTED_STATE_ROOT: + _fail("state-root-unsupported") + return value + + +def _positive_integer(value: object, code: str) -> int: + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + _fail(code) + return value + + +def _runtime_state_sha256(request: AcquireRequest) -> str: + return _sha256( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "providerId": request.provider_id, + "sandboxName": request.sandbox_name, + "lifecycleGeneration": request.lifecycle_generation, + "engineBindingSha256": request.engine_binding_sha256, + "runtimeId": request.runtime_id, + "runtimePid": request.runtime_pid, + "sandboxIdentitySha256": request.sandbox_identity_sha256, + "containerMountsSha256": request.container_mounts_sha256, + "stateRoot": request.state_root, + "stateRootMountsSha256": request.state_root_mounts_sha256, + } + ) + ) + + +def _expected_transaction_id(request: AcquireRequest) -> str: + return _sha256( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "action": "state-mutation", + "runtimeStateSha256": _runtime_state_sha256(request), + "planSha256": request.plan_sha256, + "projectionSha256": request.projection_sha256, + "nonce": request.nonce, + "target": request.target, + "rollback": request.rollback, + } + ) + ) + + +def _parse_request(action: Action, raw: bytes) -> Request: + value = _parse_json(raw, MAX_ENVELOPE_BYTES, "invalid-envelope-json") + expected = ACQUIRE_KEYS if action == "acquire" else STATUS_KEYS + if action not in ("acquire", "recover"): + expected += ("providerHandle",) + if action == "release": + expected += ("activationProviderHandle", "completedLedgerSha256") + envelope = _exact_keys(value, expected, "envelope-schema") + if ( + type(envelope["schemaVersion"]) is not int + or envelope["schemaVersion"] != SCHEMA_VERSION + or envelope["action"] != action + ): + _fail("envelope-version") + transaction_id = _hex_digest(envelope["transactionId"], "transaction-id") + provider_id = _bounded_string(envelope["providerId"], SAFE_NAME, "provider-id") + if provider_id != SUPPORTED_PROVIDER_ID: + _fail("provider-unsupported") + sandbox_name = _bounded_string(envelope["sandboxName"], SAFE_NAME, "sandbox-name") + lifecycle_generation = _bounded_string( + envelope["lifecycleGeneration"], RUNTIME_ID, "lifecycle-generation" + ) + engine_binding_sha256 = _hex_digest( + envelope["engineBindingSha256"], "engine-binding-digest" + ) + runtime_id = _hex_digest(envelope["runtimeId"], "runtime-id") + runtime_pid = _positive_integer(envelope["runtimePid"], "runtime-pid") + sandbox_identity_sha256 = _hex_digest( + envelope["sandboxIdentitySha256"], "sandbox-identity-digest" + ) + container_mounts_sha256 = _hex_digest( + envelope["containerMountsSha256"], "container-mounts-digest" + ) + common: dict[str, object] = { + "schemaVersion": SCHEMA_VERSION, + "action": action, + "transactionId": transaction_id, + "providerId": provider_id, + "sandboxName": sandbox_name, + "lifecycleGeneration": lifecycle_generation, + "engineBindingSha256": engine_binding_sha256, + "runtimeId": runtime_id, + "runtimePid": runtime_pid, + "sandboxIdentitySha256": sandbox_identity_sha256, + "containerMountsSha256": container_mounts_sha256, + } + if action != "acquire": + provider_handle = ( + _bounded_string( + envelope["providerHandle"], PROVIDER_HANDLE, "provider-handle" + ) + if action != "recover" + else None + ) + activation_provider_handle = ( + _bounded_string( + envelope["activationProviderHandle"], + ACTIVATION_PROVIDER_HANDLE, + "activation-provider-handle", + ) + if action == "release" + else None + ) + completed = ( + _hex_digest(envelope["completedLedgerSha256"], "completed-ledger-digest") + if action == "release" + else None + ) + normalized = { + **common, + **( + {"providerHandle": provider_handle} + if provider_handle is not None + else {} + ), + **( + { + "activationProviderHandle": activation_provider_handle, + "completedLedgerSha256": completed, + } + if action == "release" + else {} + ), + } + if raw != _json_bytes(normalized) + b"\n": + _fail("envelope-not-canonical") + return StatusRequest( + action, + transaction_id, + provider_id, + sandbox_name, + lifecycle_generation, + engine_binding_sha256, + runtime_id, + runtime_pid, + sandbox_identity_sha256, + container_mounts_sha256, + provider_handle, + activation_provider_handle, + completed, + ) + + state_root = _canonical_state_root(envelope["stateRoot"]) + state_root_mounts_sha256 = _hex_digest( + envelope["stateRootMountsSha256"], "state-root-mounts-digest" + ) + plan_sha256 = _hex_digest(envelope["planSha256"], "plan-digest") + projection_sha256 = _hex_digest(envelope["projectionSha256"], "projection-digest") + nonce = _hex_digest(envelope["nonce"], "nonce") + if not isinstance(envelope["plan"], str): + _fail("plan-transport") + plan_transport = envelope["plan"].encode("utf-8", "strict") + if not plan_transport or len(plan_transport) > MAX_PLAN_BYTES: + _fail("plan-transport") + plan_value = _parse_json(plan_transport, MAX_PLAN_BYTES, "invalid-plan-json") + plan = _normalize_plan(plan_value, state_root, projection_sha256) + canonical_plan = _json_bytes(plan).decode("utf-8", "strict") + if envelope["plan"] != canonical_plan or _sha256(plan_transport) != plan_sha256: + _fail("plan-digest-mismatch") + target = envelope["target"] + rollback = envelope["rollback"] + if ( + target not in ("locked", "mutable") + or rollback not in ("locked", "mutable") + or target == rollback + or plan["target"] != target + or plan["rollback"] != rollback + ): + _fail("plan-posture") + normalized = { + **common, + "stateRoot": state_root, + "stateRootMountsSha256": state_root_mounts_sha256, + "plan": canonical_plan, + "planSha256": plan_sha256, + "projectionSha256": projection_sha256, + "nonce": nonce, + "target": target, + "rollback": rollback, + } + if raw != _json_bytes(normalized) + b"\n": + _fail("envelope-not-canonical") + request = AcquireRequest( + transaction_id, + provider_id, + sandbox_name, + lifecycle_generation, + engine_binding_sha256, + runtime_id, + runtime_pid, + sandbox_identity_sha256, + container_mounts_sha256, + state_root, + state_root_mounts_sha256, + plan_sha256, + projection_sha256, + nonce, + plan, + canonical_plan, + str(target), + str(rollback), + ) + if not secrets.compare_digest( + request.transaction_id, _expected_transaction_id(request) + ): + _fail("transaction-binding-mismatch") + return request + + +PROCESS_REFERENCE_KEYS = ( + "pid", + "startIdentity", + "parentPid", + "uids", + "commandSha256", + "procDevice", + "procInode", +) + +FENCE_KEYS = ("supervisor", "start", "writerUids") +ACTIVATION_PERMIT_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "markerSha256", + "start", + "candidateDirectory", +) +ACTIVATION_RELEASE_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "checkpointSha256", + "start", + "candidateDirectory", +) +ACTIVATION_RETRY_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "permitSha256", + "checkpointSha256", + "start", + "candidateDirectory", +) +ACTIVATION_CLEANUP_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "start", + "candidateDirectory", +) +STARTUP_CANDIDATE_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "markerSha256", + "start", +) +STARTUP_RETRY_ACK_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "retrySha256", + "start", +) + + +def _process_command_sha256(command: tuple[bytes, ...]) -> str: + framed = b"".join(len(part).to_bytes(4, "big") + part for part in command) + return _sha256(framed) + + +def _process_reference(process: ProcessIdentity) -> ProcessReference: + return ProcessReference( + process.pid, + process.start_identity, + process.parent_pid, + process.uids, + _process_command_sha256(process.command), + process.proc_device, + process.proc_inode, + ) + + +def _process_reference_payload(reference: ProcessReference) -> dict[str, object]: + return { + "pid": reference.pid, + "startIdentity": reference.start_identity, + "parentPid": reference.parent_pid, + "uids": list(reference.uids), + "commandSha256": reference.command_sha256, + "procDevice": str(reference.proc_device), + "procInode": str(reference.proc_inode), + } + + +def _process_reference_from_value(value: object, code: str) -> ProcessReference: + reference = _exact_keys(value, PROCESS_REFERENCE_KEYS, code) + pid = _positive_integer(reference["pid"], code) + parent_pid = reference["parentPid"] + uids = reference["uids"] + if ( + type(parent_pid) is not int + or parent_pid < 0 + or not isinstance(uids, list) + or len(uids) != 4 + or any(type(uid) is not int or uid < 0 for uid in uids) + ): + _fail(code) + start_identity = _decimal_identity(reference["startIdentity"], code) + command_sha256 = _hex_digest(reference["commandSha256"], code) + proc_device = _decimal_identity(reference["procDevice"], code) + proc_inode = _decimal_identity(reference["procInode"], code) + if proc_device == "0" or proc_inode == "0": + _fail(code) + return ProcessReference( + pid, + start_identity, + parent_pid, + tuple(uids), # type: ignore[arg-type] + command_sha256, + int(proc_device, 10), + int(proc_inode, 10), + ) + + +def _fence_payload(fence: FenceProof) -> dict[str, object]: + return { + "supervisor": _process_reference_payload(fence.supervisor), + "start": _process_reference_payload(fence.start), + "writerUids": list(fence.writer_uids), + } + + +def _fence_from_value(value: object, code: str = "fence-marker-invalid") -> FenceProof: + fence = _exact_keys(value, FENCE_KEYS, code) + supervisor = _process_reference_from_value(fence["supervisor"], code) + start = _process_reference_from_value(fence["start"], code) + writer_uids = fence["writerUids"] + if ( + supervisor.pid != 1 + or supervisor.parent_pid != 0 + or supervisor.uids != (ROOT_UID,) * 4 + or start.pid <= 1 + or start.parent_pid != 1 + or not isinstance(writer_uids, list) + or not writer_uids + or len(writer_uids) > len(SUPPORTED_WRITER_ACCOUNTS) + or any(type(uid) is not int or uid <= 0 for uid in writer_uids) + or writer_uids != sorted(set(writer_uids)) + or not any(uid in writer_uids for uid in start.uids) + ): + _fail(code) + return FenceProof(supervisor, start, tuple(writer_uids)) + + +def _startup_candidate_directory(marker: dict[str, object]) -> str: + return os.path.join(STARTUP_HANDOFF_DIRECTORY, str(marker["nonce"])) + + +def _activation_permit_payload( + marker: dict[str, object], fence: FenceProof +) -> dict[str, object]: + marker_binding = { + key: value + for key, value in marker.items() + if key not in ("phase", "activation") + } + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": ACTIVATION_PERMIT_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "markerSha256": _sha256(_json_bytes(marker_binding) + b"\n"), + "start": _process_reference_payload(fence.start), + "candidateDirectory": _startup_candidate_directory(marker), + } + + +def _startup_candidate_payload( + marker: dict[str, object], fence: FenceProof +) -> dict[str, object]: + permit = _activation_permit_payload(marker, fence) + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": STARTUP_CANDIDATE_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "markerSha256": permit["markerSha256"], + "start": permit["start"], + } + + +def _activation_release_payload( + marker: dict[str, object], fence: FenceProof, activation: ActivationProof +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": ACTIVATION_RELEASE_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "checkpointSha256": activation.startup_checkpoint_sha256, + "start": _process_reference_payload(fence.start), + "candidateDirectory": _startup_candidate_directory(marker), + } + + +def _activation_retry_payload( + marker: dict[str, object], + fence: FenceProof, + permit_payload: bytes, + checkpoint_payload: bytes | None, +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": ACTIVATION_RETRY_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "permitSha256": _sha256(permit_payload), + "checkpointSha256": ( + _sha256(checkpoint_payload) if checkpoint_payload is not None else None + ), + "start": _process_reference_payload(fence.start), + "candidateDirectory": _startup_candidate_directory(marker), + } + + +def _activation_cleanup_payload( + marker: dict[str, object], fence: FenceProof +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": ACTIVATION_CLEANUP_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "start": _process_reference_payload(fence.start), + "candidateDirectory": _startup_candidate_directory(marker), + } + + +def _startup_retry_ack_payload( + marker: dict[str, object], fence: FenceProof, retry_payload: bytes +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": STARTUP_RETRY_ACK_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "retrySha256": _sha256(retry_payload), + "start": _process_reference_payload(fence.start), + } + + +def _marker_payload( + request: AcquireRequest, + phase: Phase, + mount_namespace: str, + state_root_device: str, + state_root_inode: str, + fence: dict[str, object], + activation: dict[str, object] | None = None, +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "phase": phase, + "transactionId": request.transaction_id, + "providerId": request.provider_id, + "sandboxName": request.sandbox_name, + "lifecycleGeneration": request.lifecycle_generation, + "engineBindingSha256": request.engine_binding_sha256, + "runtimeId": request.runtime_id, + "runtimePid": request.runtime_pid, + "sandboxIdentitySha256": request.sandbox_identity_sha256, + "containerMountsSha256": request.container_mounts_sha256, + "stateRoot": request.state_root, + "stateRootMountsSha256": request.state_root_mounts_sha256, + "mountNamespace": mount_namespace, + "stateRootDevice": state_root_device, + "stateRootInode": state_root_inode, + "plan": request.canonical_plan, + "planSha256": request.plan_sha256, + "projectionSha256": request.projection_sha256, + "nonce": request.nonce, + "target": request.target, + "rollback": request.rollback, + "fence": fence, + "activation": activation, + } + + +def _validate_marker(value: object) -> dict[str, object]: + marker = _exact_keys(value, MARKER_KEYS, "marker-schema") + if ( + type(marker["schemaVersion"]) is not int + or marker["schemaVersion"] != SCHEMA_VERSION + or marker["phase"] not in PHASES + ): + _fail("marker-schema") + provider_id = _bounded_string(marker["providerId"], SAFE_NAME, "marker-schema") + if provider_id != SUPPORTED_PROVIDER_ID: + _fail("marker-schema") + transaction_id = _hex_digest(marker["transactionId"], "marker-schema") + sandbox_name = _bounded_string(marker["sandboxName"], SAFE_NAME, "marker-schema") + lifecycle_generation = _bounded_string( + marker["lifecycleGeneration"], RUNTIME_ID, "marker-schema" + ) + engine_binding_sha256 = _hex_digest(marker["engineBindingSha256"], "marker-schema") + runtime_id = _hex_digest(marker["runtimeId"], "marker-schema") + runtime_pid = _positive_integer(marker["runtimePid"], "marker-schema") + sandbox_identity_sha256 = _hex_digest( + marker["sandboxIdentitySha256"], "marker-schema" + ) + container_mounts_sha256 = _hex_digest( + marker["containerMountsSha256"], "marker-schema" + ) + state_root = _canonical_state_root(marker["stateRoot"]) + state_root_mounts_sha256 = _hex_digest( + marker["stateRootMountsSha256"], "marker-schema" + ) + mount_namespace = _bounded_string( + marker["mountNamespace"], MOUNT_NAMESPACE, "marker-schema" + ) + state_root_device = _decimal_identity(marker["stateRootDevice"], "marker-schema") + state_root_inode = _decimal_identity(marker["stateRootInode"], "marker-schema") + if state_root_device == "0" or state_root_inode == "0": + _fail("marker-schema") + projection_sha256 = _hex_digest(marker["projectionSha256"], "marker-schema") + plan_sha256 = _hex_digest(marker["planSha256"], "marker-schema") + nonce = _hex_digest(marker["nonce"], "marker-schema") + if not isinstance(marker["plan"], str): + _fail("marker-schema") + plan_transport = marker["plan"].encode("utf-8", "strict") + plan = _normalize_plan( + _parse_json(plan_transport, MAX_PLAN_BYTES, "marker-schema"), + state_root, + projection_sha256, + ) + canonical_plan = _json_bytes(plan).decode("utf-8", "strict") + if canonical_plan != marker["plan"] or _sha256(plan_transport) != plan_sha256: + _fail("marker-schema") + target = marker["target"] + rollback = marker["rollback"] + if target != plan["target"] or rollback != plan["rollback"]: + _fail("marker-schema") + fence = _fence_from_value(marker["fence"], "marker-schema") + request = AcquireRequest( + transaction_id, + provider_id, + sandbox_name, + lifecycle_generation, + engine_binding_sha256, + runtime_id, + runtime_pid, + sandbox_identity_sha256, + container_mounts_sha256, + state_root, + state_root_mounts_sha256, + plan_sha256, + projection_sha256, + nonce, + plan, + canonical_plan, + str(target), + str(rollback), + ) + if not secrets.compare_digest(transaction_id, _expected_transaction_id(request)): + _fail("marker-schema") + activation = marker["activation"] + if marker["phase"] == "activation-proven": + if activation is None: + _fail("marker-schema") + activation = _activation_payload(_activation_from_marker(marker)) # type: ignore[arg-type] + elif marker["phase"] == "rolled-back" and activation is not None: + activation = _activation_payload(_activation_from_marker(marker)) # type: ignore[arg-type] + elif activation is not None: + _fail("marker-schema") + return _marker_payload( + request, + marker["phase"], # type: ignore[arg-type] + mount_namespace, + state_root_device, + state_root_inode, + _fence_payload(fence), + activation, # type: ignore[arg-type] + ) + + +def _base_receipt( + marker: dict[str, object], phase: Phase | None = None +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "phase": marker["phase"] if phase is None else phase, + "transactionId": marker["transactionId"], + "providerId": marker["providerId"], + "sandboxName": marker["sandboxName"], + "lifecycleGeneration": marker["lifecycleGeneration"], + "engineBindingSha256": marker["engineBindingSha256"], + "runtimeId": marker["runtimeId"], + "runtimePid": marker["runtimePid"], + "sandboxIdentitySha256": marker["sandboxIdentitySha256"], + "containerMountsSha256": marker["containerMountsSha256"], + "stateRoot": marker["stateRoot"], + "stateRootMountsSha256": marker["stateRootMountsSha256"], + "mountNamespace": marker["mountNamespace"], + "stateRootDevice": marker["stateRootDevice"], + "stateRootInode": marker["stateRootInode"], + "planSha256": marker["planSha256"], + "projectionSha256": marker["projectionSha256"], + "nonce": marker["nonce"], + "target": marker["target"], + "rollback": marker["rollback"], + } + + +def _provider_handle(marker: dict[str, object]) -> str: + return ( + f"docker-state-mutation-v1:{marker['transactionId']}:" + f"{_sha256(_json_bytes(_base_receipt(marker, 'fenced')))}" + ) + + +def _activation_provider_handle(marker: dict[str, object]) -> str: + activation = marker["activation"] + if not isinstance(activation, dict): + _fail("activation-marker-invalid") + payload = { + "schemaVersion": SCHEMA_VERSION, + "providerId": marker["providerId"], + "sandboxName": marker["sandboxName"], + "lifecycleGeneration": marker["lifecycleGeneration"], + "runtimeId": marker["runtimeId"], + "nonce": marker["nonce"], + "configurationGeneration": activation["configurationGeneration"], + "listenerIdentity": activation["listenerIdentity"], + "healthSha256": activation["healthSha256"], + "fenceProviderHandle": _provider_handle(marker), + } + return ( + f"docker-state-mutation-activation-v1:{marker['transactionId']}:" + f"{_sha256(_json_bytes(payload))}" + ) + + +def _receipt_payload(marker: dict[str, object]) -> dict[str, object]: + receipt = _base_receipt(marker) + if marker["phase"] == "activation-proven": + activation = marker["activation"] + if not isinstance(activation, dict): + _fail("activation-marker-invalid") + receipt.update( + { + "configurationGeneration": activation["configurationGeneration"], + "listenerIdentity": activation["listenerIdentity"], + "healthSha256": activation["healthSha256"], + "activationProviderHandle": _activation_provider_handle(marker), + } + ) + return receipt + + +def _released_receipt_payload( + marker: dict[str, object], completed_ledger_sha256: str, release_state: str +) -> dict[str, object]: + if release_state not in ("intent", "complete"): + _fail("released-receipt-invalid") + return { + "schemaVersion": SCHEMA_VERSION, + "releaseState": release_state, + "transactionId": marker["transactionId"], + "providerHandle": _provider_handle(marker), + "activationProviderHandle": _activation_provider_handle(marker), + "completedLedgerSha256": completed_ledger_sha256, + "marker": marker, + } + + +def _validate_released_receipt(value: object) -> dict[str, object]: + receipt = _exact_keys(value, RELEASED_RECEIPT_KEYS, "released-receipt-invalid") + if ( + type(receipt["schemaVersion"]) is not int + or receipt["schemaVersion"] != SCHEMA_VERSION + or receipt["releaseState"] not in ("intent", "complete") + ): + _fail("released-receipt-invalid") + marker = _validate_marker(receipt["marker"]) + if marker["phase"] != "activation-proven": + _fail("released-receipt-invalid") + completed = _hex_digest( + receipt["completedLedgerSha256"], "released-receipt-invalid" + ) + expected = _released_receipt_payload( + marker, completed, str(receipt["releaseState"]) + ) + if not secrets.compare_digest(_json_bytes(receipt), _json_bytes(expected)): + _fail("released-receipt-invalid") + return expected + + +def _marker_matches_acquire(marker: dict[str, object], request: AcquireRequest) -> bool: + expected = _marker_payload( + request, + marker["phase"], # type: ignore[arg-type] + str(marker["mountNamespace"]), + str(marker["stateRootDevice"]), + str(marker["stateRootInode"]), + marker["fence"], # type: ignore[arg-type] + marker["activation"] if isinstance(marker["activation"], dict) else None, + ) + return secrets.compare_digest(_json_bytes(marker), _json_bytes(expected)) + + +def _marker_matches_status(marker: dict[str, object], request: StatusRequest) -> bool: + matches = ( + marker["transactionId"] == request.transaction_id + and marker["providerId"] == request.provider_id + and marker["sandboxName"] == request.sandbox_name + and marker["lifecycleGeneration"] == request.lifecycle_generation + and marker["engineBindingSha256"] == request.engine_binding_sha256 + and marker["runtimeId"] == request.runtime_id + and marker["runtimePid"] == request.runtime_pid + and marker["sandboxIdentitySha256"] == request.sandbox_identity_sha256 + and marker["containerMountsSha256"] == request.container_mounts_sha256 + ) + if not matches: + return False + return request.provider_handle is None or secrets.compare_digest( + request.provider_handle, _provider_handle(marker) + ) + + +def _directory_flags() -> int: + return os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + + +def _open_absolute_directory(path: str) -> int: + if not path.startswith("/") or os.path.normpath(path) != path: + _fail("unsafe-directory") + current = os.open("/", _directory_flags()) + try: + for component in path.split("/")[1:]: + next_fd = os.open(component, _directory_flags(), dir_fd=current) + os.close(current) + current = next_fd + return current + except OSError: + os.close(current) + _fail("unsafe-directory") + + +def _open_or_create_directory(path: str, mode: int) -> int: + parent, name = os.path.split(path) + parent_fd = _open_absolute_directory(parent) + try: + try: + os.mkdir(name, mode, dir_fd=parent_fd) + os.fsync(parent_fd) + except FileExistsError: + pass + directory_fd = os.open(name, _directory_flags(), dir_fd=parent_fd) + finally: + os.close(parent_fd) + metadata = os.fstat(directory_fd) + if ( + not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) != mode + ): + os.close(directory_fd) + _fail("unsafe-control-directory") + return directory_fd + + +def _open_or_create_private_directory(path: str) -> int: + return _open_or_create_directory(path, 0o700) + + +def _verify_control_parent(directory_fd: int, *, searchable: bool = False) -> None: + metadata = os.fstat(directory_fd) + if ( + not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) & 0o022 + or (searchable and not stat.S_IMODE(metadata.st_mode) & 0o001) + ): + _fail("unsafe-control-parent") + + +def _open_control_directories() -> tuple[int, int]: + # The stable parents are image/OS owned. Only the controller leaves are + # created here, and each leaf is descriptor-opened without following links. + durable_parent = os.path.dirname(DURABLE_DIRECTORY) + runtime_parent = os.path.dirname(RUNTIME_DIRECTORY) + for parent, created_mode, searchable in ( + (durable_parent, DURABLE_PARENT_MODE, True), + (runtime_parent, 0o755, False), + ): + try: + parent_fd = _open_absolute_directory(parent) + except ControlError: + # Create only the fixed NemoClaw parent, never an arbitrary path. + grandparent, leaf = os.path.split(parent) + grandparent_fd = _open_absolute_directory(grandparent) + try: + try: + os.mkdir(leaf, created_mode, dir_fd=grandparent_fd) + os.fsync(grandparent_fd) + except FileExistsError: + pass + finally: + os.close(grandparent_fd) + else: + _verify_control_parent(parent_fd, searchable=searchable) + os.close(parent_fd) + continue + parent_fd = _open_absolute_directory(parent) + try: + _verify_control_parent(parent_fd, searchable=searchable) + finally: + os.close(parent_fd) + return ( + _open_or_create_directory(DURABLE_DIRECTORY, DURABLE_DIRECTORY_MODE), + _open_or_create_directory(RUNTIME_DIRECTORY, RUNTIME_DIRECTORY_MODE), + ) + + +def _open_lock(directory_fd: int) -> int: + fd = os.open( + LOCK_NAME, + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or stat.S_IMODE(metadata.st_mode) != 0o600 + or metadata.st_nlink != 1 + ): + os.close(fd) + _fail("unsafe-control-lock") + fcntl.flock(fd, fcntl.LOCK_EX) + return fd + + +def _read_control_file( + directory_fd: int, name: str, maximum: int, *, mode: int +) -> bytes | None: + try: + fd = os.open( + name, + os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, + dir_fd=directory_fd, + ) + except FileNotFoundError: + return None + except OSError: + _fail("unsafe-control-file") + try: + before = os.fstat(fd) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_uid != ROOT_UID + or before.st_gid != ROOT_GID + or stat.S_IMODE(before.st_mode) != mode + or before.st_nlink != 1 + or before.st_size <= 0 + or before.st_size > maximum + ): + _fail("unsafe-control-file") + data = b"" + while len(data) <= maximum: + chunk = os.read(fd, min(65_536, maximum + 1 - len(data))) + if not chunk: + break + data += chunk + after = os.fstat(fd) + if len(data) > maximum or _stable_stat(before) != _stable_stat(after): + _fail("raced-control-file") + return data + finally: + os.close(fd) + + +def _read_private_file(directory_fd: int, name: str, maximum: int) -> bytes | None: + return _read_control_file(directory_fd, name, maximum, mode=0o600) + + +def _stable_stat(value: os.stat_result) -> tuple[object, ...]: + return ( + value.st_dev, + value.st_ino, + value.st_mode, + value.st_nlink, + value.st_uid, + value.st_gid, + value.st_size, + value.st_mtime_ns, + value.st_ctime_ns, + ) + + +def _atomic_write( + directory_fd: int, name: str, payload: bytes, *, mode: int = 0o600 +) -> None: + temporary = f".{name}.tmp.{secrets.token_hex(12)}" + fd = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + try: + offset = 0 + while offset < len(payload): + offset += os.write(fd, payload[offset:]) + os.fchown(fd, ROOT_UID, ROOT_GID) + os.fchmod(fd, mode) + os.fsync(fd) + except Exception: + try: + os.unlink(temporary, dir_fd=directory_fd) + except OSError: + pass + raise + finally: + os.close(fd) + os.replace(temporary, name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd) + os.fsync(directory_fd) + + +def _unlink_control_file(directory_fd: int, name: str, *, mode: int) -> None: + existing = _read_control_file(directory_fd, name, MAX_MARKER_BYTES, mode=mode) + if existing is None: + return + os.unlink(name, dir_fd=directory_fd) + os.fsync(directory_fd) + + +def _unlink_private(directory_fd: int, name: str) -> None: + _unlink_control_file(directory_fd, name, mode=0o600) + + +def _load_marker(durable_fd: int) -> dict[str, object] | None: + raw = _read_private_file(durable_fd, MARKER_NAME, MAX_MARKER_BYTES) + if raw is None: + return None + value = _parse_json(raw, MAX_MARKER_BYTES, "invalid-marker-json") + marker = _validate_marker(value) + if raw != _json_bytes(marker) + b"\n": + _fail("marker-not-canonical") + return marker + + +def _write_marker(durable_fd: int, marker: dict[str, object]) -> bytes: + payload = _json_bytes(marker) + b"\n" + if len(payload) > MAX_MARKER_BYTES: + _fail("marker-too-large") + _atomic_write(durable_fd, MARKER_NAME, payload) + return payload + + +def _sandbox_account() -> tuple[int, int]: + try: + account = pwd.getpwnam("sandbox") + except KeyError: + _fail("writer-account-unavailable") + if account.pw_uid == ROOT_UID or account.pw_gid == ROOT_GID: + _fail("writer-account-is-root") + return account.pw_uid, account.pw_gid + + +def _open_startup_handoff_root() -> int: + parent = os.path.dirname(STARTUP_HANDOFF_DIRECTORY) + parent_fd = _open_absolute_directory(parent) + try: + _verify_control_parent(parent_fd, searchable=True) + finally: + os.close(parent_fd) + return _open_or_create_directory( + STARTUP_HANDOFF_DIRECTORY, STARTUP_HANDOFF_PARENT_MODE + ) + + +def _open_startup_candidate_directory( + marker: dict[str, object], *, create: bool +) -> tuple[int, int] | None: + root_fd = _open_startup_handoff_root() + name = str(marker["nonce"]) + sandbox_uid, sandbox_gid = _sandbox_account() + try: + if create: + created = False + try: + os.mkdir(name, 0o700, dir_fd=root_fd) + created = True + except FileExistsError: + pass + try: + directory_fd = os.open(name, _directory_flags(), dir_fd=root_fd) + except OSError: + _fail("activation-candidate-directory-invalid") + if created: + os.fchown(directory_fd, sandbox_uid, sandbox_gid) + os.fchmod(directory_fd, 0o700) + os.fsync(directory_fd) + os.fsync(root_fd) + else: + try: + directory_fd = os.open(name, _directory_flags(), dir_fd=root_fd) + except FileNotFoundError: + os.close(root_fd) + return None + except OSError: + _fail("activation-candidate-directory-invalid") + metadata = os.fstat(directory_fd) + if ( + not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != sandbox_uid + or metadata.st_gid != sandbox_gid + or stat.S_IMODE(metadata.st_mode) != 0o700 + ): + os.close(directory_fd) + _fail("activation-candidate-directory-invalid") + return root_fd, directory_fd + except BaseException: + try: + os.close(root_fd) + except OSError: + pass + raise + + +def _read_startup_candidate( + marker: dict[str, object], fence: FenceProof, *, required: bool +) -> tuple[dict[str, object], bytes] | None: + opened = _open_startup_candidate_directory(marker, create=False) + if opened is None: + if required: + _fail("activation-checkpoint-missing") + return None + root_fd, directory_fd = opened + sandbox_uid, sandbox_gid = _sandbox_account() + try: + # The candidate is intentionally sandbox-owned inside the one + # controller-created handoff directory; re-open it with that exact + # ownership instead of the root-only control-file helper. + try: + fd = os.open( + STARTUP_CANDIDATE_NAME, + os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, + dir_fd=directory_fd, + ) + except FileNotFoundError: + if required: + _fail("activation-checkpoint-missing") + return None + except OSError: + _fail("activation-checkpoint-invalid") + try: + before = os.fstat(fd) + payload = os.read(fd, MAX_MARKER_BYTES + 1) + after = os.fstat(fd) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_uid != sandbox_uid + or before.st_gid != sandbox_gid + or stat.S_IMODE(before.st_mode) != 0o600 + or before.st_nlink != 1 + or len(payload) > MAX_MARKER_BYTES + or os.read(fd, 1) + or _stable_stat(before) != _stable_stat(after) + ): + _fail("activation-checkpoint-invalid") + finally: + os.close(fd) + candidate = _exact_keys( + _parse_json(payload, MAX_MARKER_BYTES, "activation-checkpoint-invalid"), + STARTUP_CANDIDATE_KEYS, + "activation-checkpoint-invalid", + ) + marker_sha256 = _hex_digest( + candidate["markerSha256"], "activation-checkpoint-invalid" + ) + expected = { + "schemaVersion": SCHEMA_VERSION, + "protocol": STARTUP_CANDIDATE_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "markerSha256": marker_sha256, + "start": _process_reference_payload(fence.start), + } + if ( + payload != _json_bytes(expected) + b"\n" + or not secrets.compare_digest(_json_bytes(candidate), _json_bytes(expected)) + or not secrets.compare_digest( + marker_sha256, + str(_startup_candidate_payload(marker, fence)["markerSha256"]), + ) + ): + _fail("activation-checkpoint-invalid") + return expected, payload + finally: + os.close(directory_fd) + os.close(root_fd) + + +def _read_public_protocol_file( + durable_fd: int, + name: str, + keys: tuple[str, ...], + protocol: str, + code: str, +) -> dict[str, object] | None: + raw = _read_control_file(durable_fd, name, MAX_MARKER_BYTES, mode=0o444) + if raw is None: + return None + value = _exact_keys(_parse_json(raw, MAX_MARKER_BYTES, code), keys, code) + if ( + value["schemaVersion"] != SCHEMA_VERSION + or value["protocol"] != protocol + or raw != _json_bytes(value) + b"\n" + ): + _fail(code) + return value + + +def _canonical_protocol_payload(value: dict[str, object]) -> bytes: + return _json_bytes(value) + b"\n" + + +def _read_activation_permit( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> dict[str, object] | None: + permit = _read_public_protocol_file( + durable_fd, + ACTIVATION_PERMIT_NAME, + ACTIVATION_PERMIT_KEYS, + ACTIVATION_PERMIT_PROTOCOL, + "activation-permit-invalid", + ) + if permit is not None and not secrets.compare_digest( + _json_bytes(permit), _json_bytes(_activation_permit_payload(marker, fence)) + ): + _fail("activation-permit-conflict") + return permit + + +def _read_activation_retry( + durable_fd: int, +) -> dict[str, object] | None: + retry = _read_public_protocol_file( + durable_fd, + ACTIVATION_RETRY_NAME, + ACTIVATION_RETRY_KEYS, + ACTIVATION_RETRY_PROTOCOL, + "activation-retry-invalid", + ) + if retry is not None: + _hex_digest(retry["permitSha256"], "activation-retry-invalid") + checkpoint = retry["checkpointSha256"] + if checkpoint is not None: + _hex_digest(checkpoint, "activation-retry-invalid") + return retry + + +def _read_activation_cleanup( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> dict[str, object] | None: + raw = _read_private_file(durable_fd, ACTIVATION_CLEANUP_NAME, MAX_MARKER_BYTES) + if raw is None: + return None + cleanup = _exact_keys( + _parse_json(raw, MAX_MARKER_BYTES, "activation-cleanup-invalid"), + ACTIVATION_CLEANUP_KEYS, + "activation-cleanup-invalid", + ) + expected = _activation_cleanup_payload(marker, fence) + if ( + cleanup["schemaVersion"] != SCHEMA_VERSION + or cleanup["protocol"] != ACTIVATION_CLEANUP_PROTOCOL + or raw != _canonical_protocol_payload(expected) + or not secrets.compare_digest(_json_bytes(cleanup), _json_bytes(expected)) + ): + _fail("activation-cleanup-invalid") + return cleanup + + +def _activation_attempt_pending( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> bool: + if _read_activation_cleanup(durable_fd, marker, fence) is not None: + # The exact shell has already authenticated and acknowledged its exec + # restart. Finish the durable, idempotent cleanup before issuing a fresh + # permit; every process is still covered by the activation guardian. + _cleanup_activation_protocol(durable_fd, marker) + return False + permit = _read_activation_permit(durable_fd, marker, fence) + retry = _read_activation_retry(durable_fd) + opened = _open_startup_candidate_directory(marker, create=False) + candidate_entries: list[str] | None = None + if opened is not None: + root_fd, directory_fd = opened + candidate_entries = os.listdir(directory_fd) + os.close(directory_fd) + os.close(root_fd) + if permit is None: + if retry is not None or candidate_entries: + _fail("activation-attempt-orphaned") + if opened is not None: + _cleanup_startup_candidate_directory(marker) + return False + return True + + +def _publish_activation_permit( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> None: + opened = _open_startup_candidate_directory(marker, create=True) + assert opened is not None + root_fd, directory_fd = opened + os.close(directory_fd) + os.close(root_fd) + if ( + _read_public_protocol_file( + durable_fd, + ACTIVATION_RELEASE_NAME, + ACTIVATION_RELEASE_KEYS, + ACTIVATION_RELEASE_PROTOCOL, + "activation-release-invalid", + ) + is not None + ): + _fail("activation-release-conflict") + if _read_activation_retry(durable_fd) is not None: + _fail("activation-retry-conflict") + expected = _activation_permit_payload(marker, fence) + existing = _read_activation_permit(durable_fd, marker, fence) + if existing is not None: + if not secrets.compare_digest(_json_bytes(existing), _json_bytes(expected)): + _fail("activation-permit-conflict") + return + _atomic_write( + durable_fd, + ACTIVATION_PERMIT_NAME, + _json_bytes(expected) + b"\n", + mode=0o444, + ) + + +def _publish_activation_release( + durable_fd: int, + marker: dict[str, object], + fence: FenceProof, + activation: ActivationProof, +) -> None: + expected = _activation_release_payload(marker, fence, activation) + existing = _read_public_protocol_file( + durable_fd, + ACTIVATION_RELEASE_NAME, + ACTIVATION_RELEASE_KEYS, + ACTIVATION_RELEASE_PROTOCOL, + "activation-release-invalid", + ) + if existing is not None: + if not secrets.compare_digest(_json_bytes(existing), _json_bytes(expected)): + _fail("activation-release-conflict") + return + _atomic_write( + durable_fd, + ACTIVATION_RELEASE_NAME, + _json_bytes(expected) + b"\n", + mode=0o444, + ) + + +def _publish_activation_retry( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> bytes: + permit = _read_activation_permit(durable_fd, marker, fence) + if permit is None: + _fail("activation-permit-missing") + selected = _read_startup_candidate(marker, fence, required=False) + checkpoint_payload = selected[1] if selected is not None else None + permit_payload = _canonical_protocol_payload(permit) + expected = _activation_retry_payload( + marker, fence, permit_payload, checkpoint_payload + ) + existing = _read_activation_retry(durable_fd) + if existing is not None: + if not secrets.compare_digest(_json_bytes(existing), _json_bytes(expected)): + _fail("activation-retry-conflict") + return _canonical_protocol_payload(existing) + payload = _canonical_protocol_payload(expected) + _atomic_write(durable_fd, ACTIVATION_RETRY_NAME, payload, mode=0o444) + return payload + + +def _read_startup_retry_ack( + marker: dict[str, object], fence: FenceProof, retry_payload: bytes +) -> dict[str, object] | None: + opened = _open_startup_candidate_directory(marker, create=False) + if opened is None: + return None + root_fd, directory_fd = opened + sandbox_uid, sandbox_gid = _sandbox_account() + try: + try: + fd = os.open( + STARTUP_RETRY_ACK_NAME, + os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, + dir_fd=directory_fd, + ) + except FileNotFoundError: + return None + except OSError: + _fail("activation-retry-ack-invalid") + try: + before = os.fstat(fd) + payload = os.read(fd, MAX_MARKER_BYTES + 1) + after = os.fstat(fd) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_uid != sandbox_uid + or before.st_gid != sandbox_gid + or stat.S_IMODE(before.st_mode) != 0o600 + or before.st_nlink != 1 + or len(payload) > MAX_MARKER_BYTES + or os.read(fd, 1) + or _stable_stat(before) != _stable_stat(after) + ): + _fail("activation-retry-ack-invalid") + finally: + os.close(fd) + ack = _exact_keys( + _parse_json(payload, MAX_MARKER_BYTES, "activation-retry-ack-invalid"), + STARTUP_RETRY_ACK_KEYS, + "activation-retry-ack-invalid", + ) + expected = _startup_retry_ack_payload(marker, fence, retry_payload) + if ( + ack["schemaVersion"] != SCHEMA_VERSION + or ack["protocol"] != STARTUP_RETRY_ACK_PROTOCOL + or payload != _json_bytes(expected) + b"\n" + or not secrets.compare_digest(_json_bytes(ack), _json_bytes(expected)) + ): + _fail("activation-retry-ack-invalid") + return expected + finally: + os.close(directory_fd) + os.close(root_fd) + + +def _wait_for_startup_retry_ack( + marker: dict[str, object], fence: FenceProof, retry_payload: bytes +) -> None: + deadline = time.monotonic() + PROCESS_STATE_SECONDS + while True: + if _read_startup_retry_ack(marker, fence, retry_payload) is not None: + _recapture_reference(fence.start, "activation-retry-identity-drift") + return + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("activation-retry-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + + +def _verify_activation_checkpoint( + marker: dict[str, object], fence: FenceProof, activation: ActivationProof +) -> None: + selected = _read_startup_candidate(marker, fence, required=True) + assert selected is not None + _candidate, payload = selected + if not secrets.compare_digest( + _sha256(payload), activation.startup_checkpoint_sha256 + ): + _fail("activation-checkpoint-drift") + + +def _cleanup_startup_candidate_directory(marker: dict[str, object]) -> None: + opened = _open_startup_candidate_directory(marker, create=False) + if opened is None: + return + root_fd, directory_fd = opened + sandbox_uid, sandbox_gid = _sandbox_account() + try: + for name in os.listdir(directory_fd): + if ( + name not in (STARTUP_CANDIDATE_NAME, STARTUP_RETRY_ACK_NAME) + and not name.startswith(f".{STARTUP_CANDIDATE_NAME}.") + and not name.startswith(f".{STARTUP_RETRY_ACK_NAME}.") + ): + _fail("activation-candidate-directory-invalid") + try: + metadata = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + except OSError: + _fail("activation-candidate-directory-invalid") + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != sandbox_uid + or metadata.st_gid != sandbox_gid + or stat.S_IMODE(metadata.st_mode) != 0o600 + or metadata.st_nlink != 1 + ): + _fail("activation-candidate-directory-invalid") + os.unlink(name, dir_fd=directory_fd) + os.fsync(directory_fd) + os.close(directory_fd) + directory_fd = -1 + os.rmdir(str(marker["nonce"]), dir_fd=root_fd) + os.fsync(root_fd) + finally: + if directory_fd >= 0: + os.close(directory_fd) + os.close(root_fd) + + +def _cleanup_activation_protocol(durable_fd: int, marker: dict[str, object]) -> None: + fence = _fence_from_value(marker["fence"]) + cleanup = _read_activation_cleanup(durable_fd, marker, fence) + if cleanup is None: + cleanup = _activation_cleanup_payload(marker, fence) + _atomic_write( + durable_fd, + ACTIVATION_CLEANUP_NAME, + _canonical_protocol_payload(cleanup), + ) + for name, keys, protocol, code in ( + ( + ACTIVATION_PERMIT_NAME, + ACTIVATION_PERMIT_KEYS, + ACTIVATION_PERMIT_PROTOCOL, + "activation-permit-invalid", + ), + ( + ACTIVATION_RELEASE_NAME, + ACTIVATION_RELEASE_KEYS, + ACTIVATION_RELEASE_PROTOCOL, + "activation-release-invalid", + ), + ( + ACTIVATION_RETRY_NAME, + ACTIVATION_RETRY_KEYS, + ACTIVATION_RETRY_PROTOCOL, + "activation-retry-invalid", + ), + ): + value = _read_public_protocol_file(durable_fd, name, keys, protocol, code) + if value is None: + continue + if ( + value["transactionId"] != marker["transactionId"] + or value["nonce"] != marker["nonce"] + or value["start"] != _process_reference_payload(fence.start) + or value["candidateDirectory"] != _startup_candidate_directory(marker) + ): + _fail(code) + _unlink_control_file(durable_fd, name, mode=0o444) + _cleanup_startup_candidate_directory(marker) + # This durable progress record is removed last. Its presence makes every + # preceding unlink boundary recognizable and safely resumable. + _unlink_private(durable_fd, ACTIVATION_CLEANUP_NAME) + + +def _load_released_receipt(durable_fd: int) -> dict[str, object] | None: + raw = _read_private_file(durable_fd, RELEASED_RECEIPT_NAME, MAX_MARKER_BYTES) + if raw is None: + return None + value = _parse_json(raw, MAX_MARKER_BYTES, "released-receipt-invalid") + receipt = _validate_released_receipt(value) + if raw != _json_bytes(receipt) + b"\n": + _fail("released-receipt-invalid") + return receipt + + +def _write_released_receipt( + durable_fd: int, + marker: dict[str, object], + completed_ledger_sha256: str, + release_state: str, +) -> dict[str, object]: + receipt = _released_receipt_payload(marker, completed_ledger_sha256, release_state) + payload = _json_bytes(receipt) + b"\n" + if len(payload) > MAX_MARKER_BYTES: + _fail("released-receipt-too-large") + _atomic_write(durable_fd, RELEASED_RECEIPT_NAME, payload) + return receipt + + +def _released_receipt_matches_status( + receipt: dict[str, object], request: StatusRequest +) -> bool: + marker = receipt["marker"] + if not isinstance(marker, dict) or not _marker_matches_status(marker, request): + return False + if request.action != "release": + return True + return ( + request.activation_provider_handle is not None + and request.completed_ledger_sha256 is not None + and secrets.compare_digest( + request.activation_provider_handle, + str(receipt["activationProviderHandle"]), + ) + and secrets.compare_digest( + request.completed_ledger_sha256, + str(receipt["completedLedgerSha256"]), + ) + ) + + +def _finish_released_cleanup( + durable_fd: int, runtime_fd: int, released_marker: dict[str, object] +) -> None: + active = _load_marker(durable_fd) + if active is not None and not secrets.compare_digest( + _json_bytes(active), _json_bytes(released_marker) + ): + return + _cleanup_activation_protocol(durable_fd, released_marker) + _unlink_private(runtime_fd, SENTINEL_NAME) + _unlink_private(runtime_fd, ACTIVATION_RECEIPT_NAME) + # ``active.json`` is the durable non-root startup gate. Remove it last so a + # replacement entrypoint cannot pass the gate before release cleanup is + # itself complete and durable. + _unlink_private(durable_fd, MARKER_NAME) + + +def _publish_sentinel(runtime_fd: int, marker_payload: bytes, nonce: str) -> None: + sentinel = { + "schemaVersion": SCHEMA_VERSION, + "nonce": nonce, + "markerSha256": _sha256(marker_payload), + } + _atomic_write(runtime_fd, SENTINEL_NAME, _json_bytes(sentinel) + b"\n") + + +def _verify_sentinel(runtime_fd: int, marker_payload: bytes, nonce: str) -> None: + raw = _read_private_file(runtime_fd, SENTINEL_NAME, MAX_MARKER_BYTES) + expected = ( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "nonce": nonce, + "markerSha256": _sha256(marker_payload), + } + ) + + b"\n" + ) + if raw is None or not secrets.compare_digest(raw, expected): + _fail("sentinel-mismatch") + + +def _capture_runtime_binding(state_root: str) -> tuple[str, str, str]: + root_fd = _open_absolute_directory(state_root) + try: + metadata = os.fstat(root_fd) + finally: + os.close(root_fd) + try: + mount_namespace = os.readlink(MOUNT_NAMESPACE_PATH) + except OSError: + _fail("mount-namespace-unavailable") + if MOUNT_NAMESPACE.fullmatch(mount_namespace) is None: + _fail("mount-namespace-unavailable") + return mount_namespace, str(metadata.st_dev), str(metadata.st_ino) + + +def _assert_runtime_binding(marker: dict[str, object]) -> None: + mount_namespace, state_root_device, state_root_inode = _capture_runtime_binding( + str(marker["stateRoot"]) + ) + if mount_namespace != marker["mountNamespace"]: + _fail("mount-namespace-drift") + if ( + state_root_device != marker["stateRootDevice"] + or state_root_inode != marker["stateRootInode"] + ): + _fail("state-root-drift") + + +def _read_proc_file(path: str, maximum: int = MAX_PROC_FILE_BYTES) -> bytes: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK) + try: + metadata = os.fstat(fd) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > maximum: + _fail("unreadable-writer-process") + data = b"" + while len(data) <= maximum: + chunk = os.read(fd, min(65_536, maximum + 1 - len(data))) + if not chunk: + break + data += chunk + if len(data) > maximum: + _fail("unreadable-writer-process") + return data + finally: + os.close(fd) + + +def _parse_proc_stat(pid: int, raw: bytes) -> tuple[str, int, str]: + try: + text = raw.decode("ascii", "strict") + suffix = text[text.rindex(") ") + 2 :].split() + state = suffix[0] + parent = int(suffix[1], 10) + start = suffix[19] + except (UnicodeDecodeError, ValueError, IndexError): + _fail("unreadable-writer-process") + if len(state) != 1 or DECIMAL.fullmatch(start) is None or parent < 0: + _fail("unreadable-writer-process") + return state, parent, start + + +def _parse_proc_uids(raw: bytes) -> tuple[int, int, int, int]: + try: + text = raw.decode("ascii", "strict") + except UnicodeDecodeError: + _fail("unreadable-writer-process") + for line in text.splitlines(): + if line.startswith("Uid:"): + fields = line.split()[1:] + if len(fields) != 4 or any( + DECIMAL.fullmatch(item) is None for item in fields + ): + break + return tuple(int(item, 10) for item in fields) # type: ignore[return-value] + _fail("unreadable-writer-process") + + +def _same_filesystem_object(first: os.stat_result, second: os.stat_result) -> bool: + return first.st_dev == second.st_dev and first.st_ino == second.st_ino + + +def _assert_private_procfs() -> None: + try: + proc_metadata = os.lstat(PROC_ROOT) + proc_root = os.stat(PROC_ROOT) + container_root = os.stat("/") + pid_one_root = os.stat(os.path.join(PROC_ROOT, "1", "root")) + self_root = os.stat(os.path.join(PROC_ROOT, "self", "root")) + pid_one_namespace = os.readlink(os.path.join(PROC_ROOT, "1", "ns", "pid")) + self_namespace = os.readlink(os.path.join(PROC_ROOT, "self", "ns", "pid")) + except OSError: + _fail("unsafe-proc-namespace") + if ( + not stat.S_ISDIR(proc_metadata.st_mode) + or stat.S_ISLNK(proc_metadata.st_mode) + or proc_root.st_dev == container_root.st_dev + or PID_NAMESPACE.fullmatch(pid_one_namespace) is None + or pid_one_namespace != self_namespace + or not _same_filesystem_object(pid_one_root, container_root) + or not _same_filesystem_object(self_root, container_root) + ): + _fail("unsafe-proc-namespace") + + +def _capture_process(pid: int) -> ProcessIdentity | None: + process_path = os.path.join(PROC_ROOT, str(pid)) + try: + before = os.stat(process_path, follow_symlinks=False) + first_stat = _read_proc_file(os.path.join(process_path, "stat")) + status = _read_proc_file(os.path.join(process_path, "status")) + command_raw = _read_proc_file(os.path.join(process_path, "cmdline")) + second_stat = _read_proc_file(os.path.join(process_path, "stat")) + after = os.stat(process_path, follow_symlinks=False) + except FileNotFoundError: + return None + except PermissionError: + _fail("unreadable-writer-process") + _first_state, parent, start = _parse_proc_stat(pid, first_stat) + second_state, second_parent, second_start = _parse_proc_stat(pid, second_stat) + if ( + not stat.S_ISDIR(before.st_mode) + or _stable_stat(before) != _stable_stat(after) + or (parent, start) != (second_parent, second_start) + ): + _fail("raced-writer-process") + return ProcessIdentity( + pid, + second_state, + parent, + start, + _parse_proc_uids(status), + tuple(part for part in command_raw.split(b"\0") if part), + before.st_dev, + before.st_ino, + ) + + +def _supported_writer_uids() -> tuple[int, ...]: + values: list[int] = [] + try: + for account in SUPPORTED_WRITER_ACCOUNTS: + uid = pwd.getpwnam(account).pw_uid + if uid == ROOT_UID: + _fail("writer-account-is-root") + values.append(uid) + except KeyError: + _fail("writer-account-unavailable") + return tuple(sorted(set(values))) + + +def _sandbox_uid() -> int: + try: + uid = pwd.getpwnam("sandbox").pw_uid + except KeyError: + _fail("writer-account-unavailable") + if uid == ROOT_UID: + _fail("writer-account-is-root") + return uid + + +def _capture_writer_processes( + writer_uids: tuple[int, ...], +) -> tuple[ProcessIdentity, ...]: + _assert_private_procfs() + try: + entries = os.listdir(PROC_ROOT) + except OSError: + _fail("proc-unavailable") + numeric = sorted(int(name) for name in entries if name.isascii() and name.isdigit()) + if len(numeric) > MAX_PROC_ENTRIES: + _fail("proc-entry-limit") + result: list[ProcessIdentity] = [] + for pid in numeric: + process = _capture_process(pid) + if ( + process is not None + and process.state != "Z" + and any(uid in writer_uids for uid in process.uids) + ): + result.append(process) + return tuple(result) + + +def _is_openshell_supervisor(process: ProcessIdentity) -> bool: + return bool( + process.pid == 1 + and process.parent_pid == 0 + and process.state != "Z" + and process.uids == (ROOT_UID,) * 4 + and process.command + and process.command[0] == OPENSHELL_ARGV0 + ) + + +def _is_nemoclaw_start(process: ProcessIdentity, sandbox_uid: int) -> bool: + direct = process.command == (NEMOCLAW_START_PATH,) + interpreted = bool( + len(process.command) == 2 + and process.command[0].rsplit(b"/", 1)[-1] == b"bash" + and process.command[1] == NEMOCLAW_START_PATH + ) + return bool( + process.pid > 1 + and process.parent_pid == 1 + and process.state != "Z" + and process.uids == (sandbox_uid,) * 4 + and (direct or interpreted) + ) + + +def _process_matches_reference( + process: ProcessIdentity, reference: ProcessReference +) -> bool: + return bool( + _process_has_reference_identity(process, reference) and process.state != "Z" + ) + + +def _process_has_reference_identity( + process: ProcessIdentity, reference: ProcessReference +) -> bool: + return bool( + process.pid == reference.pid + and process.start_identity == reference.start_identity + and process.parent_pid == reference.parent_pid + and process.uids == reference.uids + and _process_command_sha256(process.command) == reference.command_sha256 + and process.proc_device == reference.proc_device + and process.proc_inode == reference.proc_inode + ) + + +def _recapture_reference( + reference: ProcessReference, code: str = "fenced-process-drift" +) -> ProcessIdentity: + process = _capture_process(reference.pid) + if process is None or not _process_matches_reference(process, reference): + _fail(code) + return process + + +def _discover_fence(expected_mount_namespace: str) -> FenceProof: + _assert_private_procfs() + try: + mount_namespace = os.readlink(MOUNT_NAMESPACE_PATH) + except OSError: + _fail("supervisor-unavailable") + if mount_namespace != expected_mount_namespace: + _fail("supervisor-unavailable") + writer_uids = _supported_writer_uids() + sandbox_uid = _sandbox_uid() + supervisor = _capture_process(1) + if supervisor is None or not _is_openshell_supervisor(supervisor): + _fail("supervisor-unavailable") + writers = _capture_writer_processes(writer_uids) + starts = [ + process for process in writers if _is_nemoclaw_start(process, sandbox_uid) + ] + if len(starts) != 1: + _fail("supervisor-unavailable") + start = starts[0] + supervisor_reference = _process_reference(supervisor) + start_reference = _process_reference(start) + second_supervisor = _recapture_reference( + supervisor_reference, "supervisor-identity-drift" + ) + second_writers = _capture_writer_processes(writer_uids) + second_starts = [ + process + for process in second_writers + if _is_nemoclaw_start(process, sandbox_uid) + ] + if ( + len(second_starts) != 1 + or not _process_matches_reference(second_starts[0], start_reference) + or not _is_openshell_supervisor(second_supervisor) + ): + _fail("supervisor-identity-drift") + return FenceProof(supervisor_reference, start_reference, writer_uids) + + +def _signal_exact_process(process: ProcessIdentity, requested_signal: int) -> None: + _assert_private_procfs() + if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"): + _fail("pidfd-unavailable") + try: + pidfd = os.pidfd_open(process.pid, 0) + except ProcessLookupError: + return + except OSError: + _fail("pidfd-unavailable") + try: + current = _capture_process(process.pid) + if current is None: + return + if current.identity_key() != process.identity_key(): + _fail("writer-pid-reused") + try: + signal.pidfd_send_signal(pidfd, requested_signal) + except ProcessLookupError: + return + except OSError: + _fail("writer-signal-failed") + finally: + os.close(pidfd) + + +def _signal_reference(reference: ProcessReference, requested_signal: int) -> None: + process = _recapture_reference(reference) + _signal_exact_process(process, requested_signal) + + +def _wait_for_reference_state( + reference: ProcessReference, expected: tuple[str, ...] +) -> ProcessIdentity: + deadline = time.monotonic() + PROCESS_STATE_SECONDS + while True: + process = _recapture_reference(reference) + if process.state in expected: + return process + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("process-state-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + + +def _stop_reference(reference: ProcessReference) -> None: + process = _recapture_reference(reference) + if process.state not in ("T", "t"): + _signal_exact_process(process, signal.SIGSTOP) + _wait_for_reference_state(reference, ("T", "t")) + + +def _allowed_writer_map( + allowed: tuple[ProcessReference, ...], +) -> dict[int, ProcessReference]: + result: dict[int, ProcessReference] = {} + for reference in allowed: + if reference.pid in result: + _fail("fenced-process-drift") + result[reference.pid] = reference + return result + + +def _writers_match_allowed( + writers: tuple[ProcessIdentity, ...], allowed: tuple[ProcessReference, ...] +) -> bool: + references = _allowed_writer_map(allowed) + if len(writers) != len(references): + return False + return all( + writer.pid in references + and _process_matches_reference(writer, references[writer.pid]) + and writer.state in ("T", "t") + for writer in writers + ) + + +def _exclude_writers( + writer_uids: tuple[int, ...], allowed: tuple[ProcessReference, ...] +) -> None: + term_deadline = time.monotonic() + TERM_SECONDS + kill_deadline = term_deadline + KILL_SECONDS + stable = 0 + signalled: set[tuple[int, str, int]] = set() + allowed_by_pid = _allowed_writer_map(allowed) + while True: + writers = _capture_writer_processes(writer_uids) + unexpected: list[ProcessIdentity] = [] + for writer in writers: + reference = allowed_by_pid.get(writer.pid) + if reference is None: + unexpected.append(writer) + continue + if not _process_matches_reference(writer, reference): + _fail("fenced-process-drift") + if writer.state not in ("T", "t"): + _fail("allowed-writer-running") + if not unexpected and _writers_match_allowed(writers, allowed): + stable += 1 + if stable >= STABLE_SCANS: + return + time.sleep(POLL_SECONDS) + continue + stable = 0 + now = time.monotonic() + if now >= kill_deadline: + _fail("writer-exclusion-timeout") + requested = signal.SIGTERM if now < term_deadline else signal.SIGKILL + for writer in unexpected: + identity = (writer.pid, writer.start_identity, requested) + if identity not in signalled: + _signal_exact_process(writer, requested) + signalled.add(identity) + time.sleep(POLL_SECONDS) + + +def _assert_writer_exclusion( + writer_uids: tuple[int, ...], allowed: tuple[ProcessReference, ...] +) -> None: + stable = 0 + while stable < STABLE_SCANS: + writers = _capture_writer_processes(writer_uids) + if not _writers_match_allowed(writers, allowed): + _fail("writer-fence-breached") + stable += 1 + time.sleep(POLL_SECONDS) + + +def _prove_fence_shape( + fence: FenceProof, expected_mount_namespace: str +) -> tuple[ProcessIdentity, ProcessIdentity]: + _assert_private_procfs() + try: + mount_namespace = os.readlink(MOUNT_NAMESPACE_PATH) + except OSError: + _fail("supervisor-identity-drift") + if ( + mount_namespace != expected_mount_namespace + or fence.writer_uids != _supported_writer_uids() + ): + _fail("supervisor-identity-drift") + supervisor = _recapture_reference(fence.supervisor, "supervisor-identity-drift") + start = _recapture_reference(fence.start, "supervisor-identity-drift") + if not _is_openshell_supervisor(supervisor) or not _is_nemoclaw_start( + start, _sandbox_uid() + ): + _fail("supervisor-identity-drift") + return supervisor, start + + +def _held_writer_references( + fence: FenceProof, activation: ActivationProof | None +) -> tuple[ProcessReference, ...]: + if activation is None: + return (fence.start,) + retained: list[ProcessReference] = [] + persistent = set(activation.persistent_pids) + for reference in activation.processes: + if _reference_is_terminated(reference): + if reference.pid in persistent: + _fail("activation-process-drift") + continue + retained.append(reference) + return (fence.start, *retained) + + +def _hold_exact_processes( + fence: FenceProof, + expected_mount_namespace: str, + activation: ActivationProof | None, +) -> None: + _prove_fence_shape(fence, expected_mount_namespace) + _stop_reference(fence.supervisor) + _stop_reference(fence.start) + if activation is not None: + persistent = set(activation.persistent_pids) + for reference in activation.processes: + if _reference_is_terminated(reference): + if reference.pid in persistent: + _fail("activation-process-drift") + continue + _stop_reference(reference) + allowed = _held_writer_references(fence, activation) + _exclude_writers(fence.writer_uids, allowed) + _assert_writer_exclusion(fence.writer_uids, allowed) + + +def _assert_exact_process_fence( + fence: FenceProof, + expected_mount_namespace: str, + activation: ActivationProof | None, +) -> None: + supervisor, start = _prove_fence_shape(fence, expected_mount_namespace) + if supervisor.state not in ("T", "t") or start.state not in ("T", "t"): + _fail("process-fence-breached") + _assert_writer_exclusion( + fence.writer_uids, _held_writer_references(fence, activation) + ) + + +def _read_activation_guard_byte(fd: int, code: str) -> bytes: + ready, _writable, _exceptional = select.select([fd], [], [], PROCESS_STATE_SECONDS) + if not ready: + _fail(code) + try: + value = os.read(fd, 1) + except OSError: + _fail(code) + if len(value) != 1: + _fail(code) + return value + + +def _wait_activation_guard_child(pid: int, code: str) -> None: + deadline = time.monotonic() + PROCESS_STATE_SECONDS + while True: + try: + selected, status = os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + _fail(code) + if selected == pid: + if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0: + _fail(code) + return + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail(code) + time.sleep(min(POLL_SECONDS, remaining)) + + +def _close_activation_guard_inherited_fds(keep: tuple[int, ...]) -> None: + entries: list[str] | None = None + for directory in (os.path.join(PROC_ROOT, "self", "fd"), "/dev/fd"): + try: + entries = os.listdir(directory) + break + except OSError: + continue + if entries is None: + retained = set(keep) + for fd in range(3, 1024): + if fd in retained: + continue + try: + os.close(fd) + except OSError: + pass + return + retained = set(keep) + for entry in entries: + if not entry.isascii() or not entry.isdigit(): + continue + fd = int(entry, 10) + if fd <= 2 or fd in retained: + continue + try: + os.close(fd) + except OSError: + pass + + +def _pid_namespace_process_ids() -> tuple[int, ...]: + try: + entries = os.listdir(PROC_ROOT) + except BaseException: + return () + return tuple( + sorted( + int(entry, 10) for entry in entries if entry.isascii() and entry.isdigit() + ) + ) + + +def _open_activation_guard_pidfd(reference: ProcessReference) -> int: + if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"): + _fail("activation-guard-unavailable") + _recapture_reference(reference, "activation-guard-unavailable") + try: + pidfd = os.pidfd_open(reference.pid, 0) + except OSError: + _fail("activation-guard-unavailable") + try: + os.set_inheritable(pidfd, False) + _recapture_reference(reference, "activation-guard-unavailable") + except BaseException: + os.close(pidfd) + raise + return pidfd + + +def _stop_activation_guard_pidfd(pidfd: int) -> None: + try: + signal.pidfd_send_signal(pidfd, signal.SIGSTOP, None, 0) + except BaseException: + pass + + +def _kernel_pid_namespace_stop() -> None: + # Linux excludes both PID 1 and the sender from kill(-1, signal). The + # guardian handles PID 1 through its pre-opened pidfd; excluding the sender + # is what lets it keep the transaction lock and repeat this broadcast. + os.kill(-1, signal.SIGSTOP) + + +def _park_pid_namespace_fail_closed(pidfds: tuple[int, ...]) -> None: + # Both identity-aware hold attempts failed. There is no safe protocol + # response left: retain the inherited transaction lock and repeatedly stop + # every other process in the already-proven private PID namespace. Only + # sandbox/container destruction may terminate this last-resort guardian. + for ignored in ( + signal.SIGHUP, + signal.SIGINT, + signal.SIGQUIT, + signal.SIGTERM, + signal.SIGUSR1, + signal.SIGUSR2, + ): + try: + signal.signal(ignored, signal.SIG_IGN) + except BaseException: + pass + own_pid = os.getpid() + while True: + for pidfd in pidfds: + _stop_activation_guard_pidfd(pidfd) + try: + # The child inherited the already-proven private PID namespace, + # and Linux never moves an existing process into another PID + # namespace. This broadcast therefore cannot reach host processes + # and cannot stop the guardian itself. + _kernel_pid_namespace_stop() + except BaseException: + pass + # Enumeration is defense in depth only. The kernel broadcast above is + # the fail-closed primitive when procfs is missing or unreadable. + try: + pids = _pid_namespace_process_ids() + except BaseException: + pids = () + for pid in pids: + if pid == own_pid: + continue + try: + os.kill(pid, signal.SIGSTOP) + except BaseException: + pass + try: + time.sleep(max(POLL_SECONDS, 0.01)) + except BaseException: + pass + + +def _activation_guard_child( + command_fd: int, + acknowledgement_fd: int, + fence: FenceProof, + mount_namespace: str, + lock_fd: int | None, + supervisor_pidfd: int, + start_pidfd: int, +) -> None: + retained = [ + command_fd, + acknowledgement_fd, + supervisor_pidfd, + start_pidfd, + ] + if lock_fd is not None: + retained.append(lock_fd) + _close_activation_guard_inherited_fds(tuple(retained)) + try: + null_fd = os.open("/dev/null", os.O_RDWR | os.O_CLOEXEC) + try: + for target in (0, 1, 2): + os.dup2(null_fd, target) + finally: + if null_fd > 2: + os.close(null_fd) + os.write(acknowledgement_fd, b"R") + command = os.read(command_fd, 1) + if command == b"D": + os.write(acknowledgement_fd, b"D") + os._exit(0) + # EOF is the kernel-backed controller-death signal. Any malformed + # command is treated identically: restore the original exact hold and + # exclude every other writer before this orphan exits. + _hold_exact_processes(fence, mount_namespace, None) + try: + os.write(acknowledgement_fd, b"H") + except OSError: + pass + os._exit(0) + except BaseException: + try: + _hold_exact_processes(fence, mount_namespace, None) + except BaseException: + _park_pid_namespace_fail_closed((supervisor_pidfd, start_pidfd)) + os._exit(70) + + +@dataclass +class ActivationGuard: + pid: int + command_fd: int + acknowledgement_fd: int + fence: FenceProof + mount_namespace: str + active: bool = True + + def disarm(self) -> None: + if not self.active: + return + try: + os.write(self.command_fd, b"D") + if ( + _read_activation_guard_byte( + self.acknowledgement_fd, "activation-guard-disarm-failed" + ) + != b"D" + ): + _fail("activation-guard-disarm-failed") + _wait_activation_guard_child(self.pid, "activation-guard-disarm-failed") + finally: + os.close(self.command_fd) + os.close(self.acknowledgement_fd) + self.active = False + + def fail_closed(self) -> None: + if not self.active: + return + child_held = False + try: + os.close(self.command_fd) + self.command_fd = -1 + child_held = ( + _read_activation_guard_byte( + self.acknowledgement_fd, "activation-guard-hold-failed" + ) + == b"H" + ) + _wait_activation_guard_child(self.pid, "activation-guard-hold-failed") + except ControlError: + child_held = False + finally: + if self.command_fd >= 0: + os.close(self.command_fd) + os.close(self.acknowledgement_fd) + self.active = False + if not child_held: + _hold_exact_processes(self.fence, self.mount_namespace, None) + + +def _start_activation_guard( + fence: FenceProof, mount_namespace: str, lock_fd: int | None = None +) -> ActivationGuard: + # The last-resort child may broadcast SIGSTOP through the whole namespace, + # so establish this safety property before forking it. + _assert_private_procfs() + descriptors: list[int] = [] + try: + supervisor_pidfd = _open_activation_guard_pidfd(fence.supervisor) + descriptors.append(supervisor_pidfd) + start_pidfd = _open_activation_guard_pidfd(fence.start) + descriptors.append(start_pidfd) + command_read, command_write = os.pipe() + descriptors.extend((command_read, command_write)) + acknowledgement_read, acknowledgement_write = os.pipe() + descriptors.extend((acknowledgement_read, acknowledgement_write)) + for fd in ( + command_read, + command_write, + acknowledgement_read, + acknowledgement_write, + ): + os.set_inheritable(fd, False) + pid = os.fork() + except (OSError, ControlError): + for fd in descriptors: + try: + os.close(fd) + except OSError: + pass + _hold_exact_processes(fence, mount_namespace, None) + _fail("activation-guard-unavailable") + if pid == 0: + os.close(command_write) + os.close(acknowledgement_read) + _activation_guard_child( + command_read, + acknowledgement_write, + fence, + mount_namespace, + lock_fd, + supervisor_pidfd, + start_pidfd, + ) + os._exit(70) + os.close(supervisor_pidfd) + os.close(start_pidfd) + os.close(command_read) + os.close(acknowledgement_write) + guard = ActivationGuard( + pid, + command_write, + acknowledgement_read, + fence, + mount_namespace, + ) + if ( + _read_activation_guard_byte( + acknowledgement_read, "activation-guard-unavailable" + ) + != b"R" + ): + guard.fail_closed() + _fail("activation-guard-unavailable") + return guard + + +def _load_publisher_module() -> object: + parent_fd = _open_absolute_directory(os.path.dirname(PUBLISHER_MODULE_PATH)) + try: + parent = os.fstat(parent_fd) + finally: + os.close(parent_fd) + if ( + parent.st_uid != ROOT_UID + or parent.st_gid != ROOT_GID + or stat.S_IMODE(parent.st_mode) & 0o022 + ): + _fail("publisher-protocol-unavailable") + try: + fd = os.open( + PUBLISHER_MODULE_PATH, + os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC, + ) + except OSError: + _fail("publisher-protocol-unavailable") + try: + metadata = os.fstat(fd) + finally: + os.close(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) & 0o022 + or metadata.st_nlink != 1 + ): + _fail("publisher-protocol-unavailable") + module_name = "_nemoclaw_runtime_state_mutation_publisher" + spec = importlib.util.spec_from_file_location(module_name, PUBLISHER_MODULE_PATH) + if spec is None or spec.loader is None: + _fail("publisher-protocol-unavailable") + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + try: + spec.loader.exec_module(module) + except Exception: + sys.modules.pop(module_name, None) + _fail("publisher-protocol-unavailable") + return module + + +def _apply_plan_posture(marker: dict[str, object], posture: str) -> None: + module = _load_publisher_module() + apply = getattr(module, "apply_plan_posture", None) + publisher_error = getattr(module, "PublisherError", None) + if not callable(apply) or not isinstance(publisher_error, type): + _fail("publisher-protocol-unavailable") + try: + value = apply(marker, posture) + except publisher_error as error: # type: ignore[misc] + code = getattr(error, "code", None) + if not isinstance(code, str) or PUBLISHER_ERROR_CODE.fullmatch(code) is None: + _fail("publisher-failed") + _fail(code) + except Exception: + _fail("publisher-failed") + receipt = _exact_keys( + value, + ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "planSha256", + "projectionSha256", + "posture", + "verificationSha256", + ), + "publisher-receipt-invalid", + ) + if ( + type(receipt["schemaVersion"]) is not int + or receipt["schemaVersion"] != SCHEMA_VERSION + or receipt["protocol"] != PUBLISHER_PROTOCOL + or receipt["transactionId"] != marker["transactionId"] + or receipt["nonce"] != marker["nonce"] + or receipt["planSha256"] != marker["planSha256"] + or receipt["projectionSha256"] != marker["projectionSha256"] + or receipt["posture"] != posture + ): + _fail("publisher-receipt-invalid") + _hex_digest(receipt["verificationSha256"], "publisher-receipt-invalid") + + +def _activation_from_marker(marker: dict[str, object]) -> ActivationProof | None: + value = marker["activation"] + if value is None: + return None + activation = _exact_keys( + value, + ( + "servicePid", + "serviceStartIdentity", + "serviceUid", + "configurationGeneration", + "listenerIdentity", + "healthSha256", + "startupCheckpointSha256", + "persistentPids", + "processes", + ), + "activation-marker-invalid", + ) + pid = activation["servicePid"] + uid = activation["serviceUid"] + if type(pid) is not int or pid <= 1 or type(uid) is not int or uid < 0: + _fail("activation-marker-invalid") + process_values = activation["processes"] + persistent_values = activation["persistentPids"] + if ( + not isinstance(process_values, list) + or not process_values + or len(process_values) > MAX_ACTIVATION_PROCESSES + or not isinstance(persistent_values, list) + or not persistent_values + or persistent_values != sorted(set(persistent_values)) + or any(type(pid) is not int or pid <= 1 for pid in persistent_values) + ): + _fail("activation-marker-invalid") + processes = tuple( + _process_reference_from_value(item, "activation-marker-invalid") + for item in process_values + ) + if len({process.pid for process in processes}) != len(processes): + _fail("activation-marker-invalid") + proof = ActivationProof( + pid, + _decimal_identity( + activation["serviceStartIdentity"], "activation-marker-invalid" + ), + uid, + _bounded_string( + activation["configurationGeneration"], + RUNTIME_ID, + "activation-marker-invalid", + ), + _bounded_string( + activation["listenerIdentity"], RUNTIME_ID, "activation-marker-invalid" + ), + _hex_digest(activation["healthSha256"], "activation-marker-invalid"), + _hex_digest(activation["startupCheckpointSha256"], "activation-marker-invalid"), + tuple(persistent_values), + processes, + ) + services = [ + process + for process in processes + if process.pid == proof.service_pid + and process.start_identity == proof.service_start_identity + and process.uids == (proof.service_uid,) * 4 + ] + if ( + len(services) != 1 + or proof.service_pid not in proof.persistent_pids + or any( + pid not in {process.pid for process in processes} + for pid in proof.persistent_pids + ) + ): + _fail("activation-marker-invalid") + return proof + + +def _process_matches_activation( + process: ProcessIdentity, proof: ActivationProof, fence: FenceProof +) -> bool: + references = [ + reference for reference in proof.processes if reference.pid == proof.service_pid + ] + return bool( + len(references) == 1 + and _process_matches_reference(process, references[0]) + and process.pid == proof.service_pid + and process.start_identity == proof.service_start_identity + and process.parent_pid == fence.start.pid + and process.uids == (proof.service_uid,) * 4 + and _is_hermes_gateway(process, fence) + ) + + +def _is_hermes_gateway(process: ProcessIdentity, fence: FenceProof) -> bool: + command = process.command + direct = bool( + len(command) == 3 + and command[0] in HERMES_GATEWAY_PATHS + and command[1:] == (b"gateway", b"run") + ) + interpreted = bool( + len(command) == 4 + and command[0].rsplit(b"/", 1)[-1] in (b"python", b"python3") + and command[1] in HERMES_GATEWAY_PATHS + and command[2:] == (b"gateway", b"run") + ) + return bool( + process.pid > 1 + and process.parent_pid == fence.start.pid + and process.state != "Z" + and len(set(process.uids)) == 1 + and process.uids[0] in fence.writer_uids + and (direct or interpreted) + ) + + +def _read_stable_regular(path: str, maximum: int) -> bytes: + flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK + try: + fd = os.open(path, flags) + except OSError: + _fail("activation-config-unavailable") + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1: + _fail("activation-config-unavailable") + chunks: list[bytes] = [] + total = 0 + while total <= maximum: + chunk = os.read(fd, min(65_536, maximum + 1 - total)) + if not chunk: + break + chunks.append(chunk) + total += len(chunk) + after = os.fstat(fd) + if total > maximum or _stable_stat(before) != _stable_stat(after): + _fail("activation-config-unavailable") + return b"".join(chunks) + finally: + os.close(fd) + + +def _configuration_generation() -> str: + payload = _read_stable_regular( + HERMES_CONFIG_GENERATION_PATH, MAX_CONFIG_GENERATION_BYTES + ) + if not payload: + _fail("activation-config-unavailable") + return f"sha256:{_sha256(payload)}" + + +def _tcp_listener_inodes(process: ProcessIdentity, port: int) -> set[str]: + expected_port = f"{port:04X}" + listeners: set[str] = set() + for table in ("tcp", "tcp6"): + raw = _read_proc_file(os.path.join(PROC_ROOT, str(process.pid), "net", table)) + try: + lines = raw.decode("ascii", "strict").splitlines()[1:] + for line in lines: + fields = line.split() + if ( + len(fields) >= 10 + and fields[1].rsplit(":", 1)[-1].upper() == expected_port + and fields[3] == "0A" + and DECIMAL.fullmatch(fields[9]) is not None + and fields[9] != "0" + ): + listeners.add(fields[9]) + except (UnicodeDecodeError, IndexError): + _fail("activation-listener-unavailable") + fd_path = os.path.join(PROC_ROOT, str(process.pid), "fd") + try: + entries = os.listdir(fd_path) + except OSError: + _fail("activation-listener-unavailable") + if len(entries) > MAX_PROC_ENTRIES: + _fail("proc-entry-limit") + owned: set[str] = set() + for entry in entries: + if not entry.isascii() or not entry.isdigit(): + continue + try: + target = os.readlink(os.path.join(fd_path, entry)) + except FileNotFoundError: + continue + except OSError: + _fail("activation-listener-unavailable") + match = re.fullmatch(r"socket:\[([1-9][0-9]*)\]", target) + if match is not None: + owned.add(match.group(1)) + return listeners & owned + + +def _listener_identity(process: ProcessIdentity) -> str: + before = _process_reference(process) + listeners = _tcp_listener_inodes(process, HERMES_INTERNAL_PORT) + after = _recapture_reference(before, "activation-service-drift") + if len(listeners) != 1 or after.state in ("Z", "X", "x"): + _fail("activation-listener-unavailable") + return f"tcp:{HERMES_INTERNAL_PORT}:{next(iter(listeners))}" + + +def _health_status() -> int: + connection = http.client.HTTPConnection( + "127.0.0.1", HERMES_INTERNAL_PORT, timeout=HEALTH_SECONDS + ) + response: http.client.HTTPResponse | None = None + try: + connection.request("GET", HERMES_HEALTH_PATH) + response = connection.getresponse() + response.read(4096) + if response.status not in (200, 401): + _fail("activation-health-unavailable") + return response.status + except (OSError, http.client.HTTPException): + _fail("activation-health-unavailable") + finally: + if response is not None: + response.close() + connection.close() + + +def _prove_live_activation( + marker: dict[str, object], + fence: FenceProof, + gateway: ProcessIdentity, + expected: ActivationProof | None = None, + checkpoint_sha256: str | None = None, +) -> ActivationProof: + if not _is_hermes_gateway(gateway, fence): + _fail("activation-service-unproven") + reference = _process_reference(gateway) + generation = _configuration_generation() + listener = _listener_identity(gateway) + status = _health_status() + current = _recapture_reference(reference, "activation-service-drift") + if current.state in ("T", "t"): + _fail("activation-health-unavailable") + if generation != _configuration_generation() or listener != _listener_identity( + current + ): + _fail("activation-proof-drift") + health = _sha256( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "nonce": marker["nonce"], + "serviceStartIdentity": gateway.start_identity, + "configurationGeneration": generation, + "listenerIdentity": listener, + "status": status, + } + ) + ) + checkpoint = ( + expected.startup_checkpoint_sha256 + if expected is not None + else checkpoint_sha256 + ) + if checkpoint is None or HEX_64.fullmatch(checkpoint) is None: + _fail("activation-checkpoint-invalid") + proof = ActivationProof( + gateway.pid, + gateway.start_identity, + gateway.uids[0], + generation, + listener, + health, + checkpoint, + (gateway.pid,), + (reference,), + ) + if expected is not None and ( + proof.service_pid != expected.service_pid + or proof.service_start_identity != expected.service_start_identity + or proof.service_uid != expected.service_uid + or proof.configuration_generation != expected.configuration_generation + or proof.listener_identity != expected.listener_identity + or proof.health_sha256 != expected.health_sha256 + or proof.startup_checkpoint_sha256 != expected.startup_checkpoint_sha256 + ): + _fail("activation-proof-drift") + return proof + + +def _activation_tree( + fence: FenceProof, +) -> tuple[ProcessIdentity | None, tuple[ProcessIdentity, ...]]: + writers = _capture_writer_processes(fence.writer_uids) + if len(writers) > MAX_ACTIVATION_PROCESSES + 1: + _fail("activation-process-limit") + by_pid = {process.pid: process for process in writers} + start = by_pid.get(fence.start.pid) + if start is None or not _process_matches_reference(start, fence.start): + _fail("supervisor-identity-drift") + tree: list[ProcessIdentity] = [] + for process in writers: + if process.pid == fence.start.pid: + continue + ancestor = process + seen: set[int] = set() + while ancestor.parent_pid != fence.start.pid: + if ancestor.pid in seen or ancestor.parent_pid not in by_pid: + _fail("activation-writer-drift") + seen.add(ancestor.pid) + ancestor = by_pid[ancestor.parent_pid] + tree.append(process) + gateways = [process for process in tree if _is_hermes_gateway(process, fence)] + if len(gateways) > 1: + _fail("activation-service-ambiguous") + return (gateways[0] if gateways else None), tuple( + sorted(tree, key=lambda process: process.pid) + ) + + +def _wait_for_activation( + marker: dict[str, object], fence: FenceProof, checkpoint_sha256: str +) -> ActivationProof: + deadline = time.monotonic() + ACTIVATION_SECONDS + while True: + _recapture_reference(fence.supervisor, "supervisor-identity-drift") + gateway, _tree = _activation_tree(fence) + if gateway is not None: + try: + return _prove_live_activation( + marker, + fence, + gateway, + checkpoint_sha256=checkpoint_sha256, + ) + except ControlError as error: + if error.code not in ( + "activation-health-unavailable", + "activation-listener-unavailable", + ): + raise + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("activation-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + + +def _freeze_activation( + marker: dict[str, object], fence: FenceProof, live: ActivationProof +) -> ActivationProof: + _stop_reference(fence.start) + gateway, tree = _activation_tree(fence) + if gateway is None: + _fail("activation-service-drift") + live_reference = live.processes[0] + if not _process_matches_reference(gateway, live_reference): + _fail("activation-service-drift") + references = tuple(_process_reference(process) for process in tree) + for reference in references: + _stop_reference(reference) + frozen = ActivationProof( + live.service_pid, + live.service_start_identity, + live.service_uid, + live.configuration_generation, + live.listener_identity, + live.health_sha256, + live.startup_checkpoint_sha256, + live.persistent_pids, + references, + ) + _assert_writer_exclusion(fence.writer_uids, _held_writer_references(fence, frozen)) + service = _recapture_reference(live_reference, "activation-service-drift") + if ( + not _process_matches_activation(service, frozen, fence) + or service.state not in ("T", "t") + or _configuration_generation() != frozen.configuration_generation + or _listener_identity(service) != frozen.listener_identity + ): + _fail("activation-proof-drift") + return frozen + + +def _wait_for_startup_checkpoint(marker: dict[str, object], fence: FenceProof) -> str: + deadline = time.monotonic() + ACTIVATION_SECONDS + while True: + supervisor = _recapture_reference(fence.supervisor, "supervisor-identity-drift") + start = _recapture_reference(fence.start, "supervisor-identity-drift") + selected = _read_startup_candidate(marker, fence, required=False) + if selected is not None and start.state in ("T", "t"): + if supervisor.state not in ("T", "t"): + _fail("process-fence-breached") + _candidate, payload = selected + return _sha256(payload) + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("activation-checkpoint-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + + +def _reset_activation_attempt( + durable_fd: int, marker: dict[str, object], fence: FenceProof +) -> None: + retry_payload = _publish_activation_retry(durable_fd, marker, fence) + if _read_startup_retry_ack(marker, fence, retry_payload) is None: + # The retry receipt is root-owned and bound to the current permit and + # optional checkpoint. Queue the signal while the exact shell is held; + # its immutable trap validates that receipt before execing the fixed + # entrypoint path with the same PID/starttime/parent identity. + _signal_reference(fence.start, signal.SIGUSR2) + _signal_reference(fence.start, signal.SIGCONT) + _wait_for_startup_retry_ack(marker, fence, retry_payload) + else: + _recapture_reference(fence.start, "activation-retry-identity-drift") + _cleanup_activation_protocol(durable_fd, marker) + + +def _activate_exact( + durable_fd: int, + marker: dict[str, object], + fence: FenceProof, + lock_fd: int | None = None, +) -> ActivationProof: + mount_namespace = str(marker["mountNamespace"]) + pending = _activation_attempt_pending(durable_fd, marker, fence) + if lock_fd is None: + guard = _start_activation_guard(fence, mount_namespace) + else: + guard = _start_activation_guard(fence, mount_namespace, lock_fd) + try: + if pending: + _hold_exact_processes(fence, mount_namespace, None) + _reset_activation_attempt(durable_fd, marker, fence) + else: + _assert_exact_process_fence(fence, mount_namespace, None) + _publish_activation_permit(durable_fd, marker, fence) + _signal_reference(fence.start, signal.SIGCONT) + checkpoint_sha256 = _wait_for_startup_checkpoint(marker, fence) + live = _wait_for_activation(marker, fence, checkpoint_sha256) + frozen = _freeze_activation(marker, fence, live) + _verify_activation_checkpoint(marker, fence, frozen) + # From this point to durable marker publication no process is resumed. + # Waiting for guardian disarm therefore cannot open a runnable-writer + # crash window, while every earlier controller death is pipe EOF and + # forces the guardian to restore the exact original hold. + guard.disarm() + return frozen + except BaseException: + guard.fail_closed() + raise + + +def _activation_payload(proof: ActivationProof) -> dict[str, object]: + return { + "servicePid": proof.service_pid, + "serviceStartIdentity": proof.service_start_identity, + "serviceUid": proof.service_uid, + "configurationGeneration": proof.configuration_generation, + "listenerIdentity": proof.listener_identity, + "healthSha256": proof.health_sha256, + "startupCheckpointSha256": proof.startup_checkpoint_sha256, + "persistentPids": list(proof.persistent_pids), + "processes": [ + _process_reference_payload(process) for process in proof.processes + ], + } + + +def _activation_receipt_payload(marker: dict[str, object]) -> dict[str, object]: + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + if marker["phase"] != "activation-proven" or activation is None: + _fail("activation-marker-invalid") + marker_payload = _json_bytes(marker) + b"\n" + return { + "schemaVersion": SCHEMA_VERSION, + "nonce": marker["nonce"], + "markerSha256": _sha256(marker_payload), + "supervisorStartIdentity": fence.supervisor.start_identity, + "startPid": fence.start.pid, + "startStartIdentity": fence.start.start_identity, + "activation": _activation_payload(activation), + } + + +def _publish_activation_receipt(runtime_fd: int, marker: dict[str, object]) -> None: + receipt = _activation_receipt_payload(marker) + _atomic_write( + runtime_fd, + ACTIVATION_RECEIPT_NAME, + _json_bytes(receipt) + b"\n", + ) + + +def _verify_activation_receipt(runtime_fd: int, marker: dict[str, object]) -> None: + raw = _read_private_file(runtime_fd, ACTIVATION_RECEIPT_NAME, MAX_MARKER_BYTES) + expected = _json_bytes(_activation_receipt_payload(marker)) + b"\n" + if raw is None or not secrets.compare_digest(raw, expected): + _fail("activation-receipt-mismatch") + + +def _write_phase( + durable_fd: int, + runtime_fd: int, + marker: dict[str, object], + phase: Phase, + activation: dict[str, object] | None = None, +) -> dict[str, object]: + updated = {**marker, "phase": phase, "activation": activation} + payload = _write_marker(durable_fd, updated) + _publish_sentinel(runtime_fd, payload, str(updated["nonce"])) + return updated + + +def _load_exact_active( + durable_fd: int, runtime_fd: int, request: StatusRequest +) -> tuple[dict[str, object], bytes]: + marker = _load_marker(durable_fd) + if marker is None: + _fail("no-active-fence") + if not _marker_matches_status(marker, request): + _fail("active-fence-binding-mismatch") + payload = _json_bytes(marker) + b"\n" + _verify_sentinel(runtime_fd, payload, str(marker["nonce"])) + return marker, payload + + +def _assert_active_state(marker: dict[str, object], runtime_fd: int) -> None: + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + _assert_exact_process_fence(fence, str(marker["mountNamespace"]), activation) + if activation is None: + return + _verify_activation_checkpoint(marker, fence, activation) + service = _recapture_reference( + next( + process + for process in activation.processes + if process.pid == activation.service_pid + ), + "activation-service-drift", + ) + if ( + service.state not in ("T", "t") + or not _process_matches_activation(service, activation, fence) + or _configuration_generation() != activation.configuration_generation + or _listener_identity(service) != activation.listener_identity + ): + _fail("activation-proof-drift") + if marker["phase"] == "activation-proven": + _verify_activation_receipt(runtime_fd, marker) + + +def _reference_is_terminated(reference: ProcessReference) -> bool: + process = _capture_process(reference.pid) + if process is None: + return True + if process.state == "Z" and ( + process.pid == reference.pid + and process.start_identity == reference.start_identity + and process.parent_pid == reference.parent_pid + and process.proc_device == reference.proc_device + and process.proc_inode == reference.proc_inode + ): + return True + if not _process_matches_reference(process, reference): + _fail("activation-process-drift") + return False + + +def _retire_activation_tree( + marker: dict[str, object], runtime_fd: int, activation: ActivationProof +) -> None: + fence = _fence_from_value(marker["fence"]) + _prove_fence_shape(fence, str(marker["mountNamespace"])) + _stop_reference(fence.supervisor) + _stop_reference(fence.start) + for reference in activation.processes: + if not _reference_is_terminated(reference): + _signal_reference(reference, signal.SIGKILL) + deadline = time.monotonic() + KILL_SECONDS + while not all( + _reference_is_terminated(reference) for reference in activation.processes + ): + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("activation-retirement-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + _exclude_writers(fence.writer_uids, (fence.start,)) + _assert_writer_exclusion(fence.writer_uids, (fence.start,)) + _unlink_private(runtime_fd, ACTIVATION_RECEIPT_NAME) + + +def _acquire( + durable_fd: int, runtime_fd: int, request: AcquireRequest +) -> dict[str, object]: + mount_namespace, state_root_device, state_root_inode = _capture_runtime_binding( + request.state_root + ) + marker = _load_marker(durable_fd) + if marker is not None: + if not _marker_matches_acquire(marker, request): + _fail("active-fence-binding-mismatch") + _assert_runtime_binding(marker) + payload = _json_bytes(marker) + b"\n" + _publish_sentinel(runtime_fd, payload, request.nonce) + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + _hold_exact_processes(fence, mount_namespace, activation) + if marker["phase"] == "activation-proven": + _publish_activation_receipt(runtime_fd, marker) + _assert_active_state(marker, runtime_fd) + return marker + released = _load_released_receipt(durable_fd) + if released is not None and released["transactionId"] == request.transaction_id: + _fail( + "transaction-release-pending" + if released["releaseState"] == "intent" + else "transaction-already-released" + ) + fence = _discover_fence(mount_namespace) + _unlink_private(runtime_fd, ACTIVATION_RECEIPT_NAME) + marker = _marker_payload( + request, + "fenced", + mount_namespace, + state_root_device, + state_root_inode, + _fence_payload(fence), + ) + marker_payload = _write_marker(durable_fd, marker) + _publish_sentinel(runtime_fd, marker_payload, request.nonce) + _hold_exact_processes(fence, mount_namespace, None) + _assert_runtime_binding(marker) + _assert_active_state(marker, runtime_fd) + if released is not None: + _unlink_private(durable_fd, RELEASED_RECEIPT_NAME) + return marker + + +def _recover( + durable_fd: int, runtime_fd: int, request: StatusRequest +) -> dict[str, object]: + marker = _load_marker(durable_fd) + sentinel = _read_private_file(runtime_fd, SENTINEL_NAME, MAX_MARKER_BYTES) + if marker is None: + if sentinel is not None: + _fail("orphan-sentinel") + _fail("no-active-fence") + if not _marker_matches_status(marker, request): + _fail("active-fence-binding-mismatch") + _assert_runtime_binding(marker) + payload = _json_bytes(marker) + b"\n" + _publish_sentinel(runtime_fd, payload, str(marker["nonce"])) + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + if marker["phase"] == "rolled-back" and activation is not None: + _retire_activation_tree(marker, runtime_fd, activation) + marker = _write_phase(durable_fd, runtime_fd, marker, "rolled-back", None) + activation = None + else: + _hold_exact_processes(fence, str(marker["mountNamespace"]), activation) + if marker["phase"] == "activation-proven": + _publish_activation_receipt(runtime_fd, marker) + else: + _unlink_private(runtime_fd, ACTIVATION_RECEIPT_NAME) + _assert_active_state(marker, runtime_fd) + return marker + + +def _wait_for_reference_running(reference: ProcessReference) -> ProcessIdentity: + deadline = time.monotonic() + PROCESS_STATE_SECONDS + while True: + process = _recapture_reference(reference) + if process.state not in ("T", "t"): + return process + remaining = deadline - time.monotonic() + if remaining <= 0: + _fail("process-state-timeout") + time.sleep(min(POLL_SECONDS, remaining)) + + +def _resume_reference(reference: ProcessReference) -> ProcessIdentity: + process = _recapture_reference(reference) + if process.state in ("T", "t"): + _signal_exact_process(process, signal.SIGCONT) + return _wait_for_reference_running(reference) + + +def _prove_released_activation( + marker: dict[str, object], fence: FenceProof, activation: ActivationProof +) -> None: + persistent = set(activation.persistent_pids) + for reference in activation.processes: + if reference.pid not in persistent: + continue + process = _recapture_reference(reference, "activation-process-drift") + if process.state in ("T", "t"): + _fail("activation-process-stopped") + start = _recapture_reference(fence.start, "supervisor-identity-drift") + if start.state in ("T", "t"): + _fail("start-process-stopped") + service_reference = next( + process + for process in activation.processes + if process.pid == activation.service_pid + ) + service = _recapture_reference(service_reference, "activation-service-drift") + _prove_live_activation(marker, fence, service, activation) + + +def _release_activation_hold(durable_fd: int, marker: dict[str, object]) -> None: + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + if activation is None: + _fail("activation-marker-invalid") + _verify_activation_checkpoint(marker, fence, activation) + _publish_activation_release(durable_fd, marker, fence, activation) + supervisor, _start = _prove_fence_shape(fence, str(marker["mountNamespace"])) + if supervisor.state in ("T", "t"): + persistent = set(activation.persistent_pids) + for reference in activation.processes: + if _reference_is_terminated(reference): + if reference.pid in persistent: + _fail("activation-process-drift") + continue + _resume_reference(reference) + _resume_reference(fence.start) + _prove_released_activation(marker, fence, activation) + supervisor = _recapture_reference(fence.supervisor, "supervisor-identity-drift") + if supervisor.state not in ("T", "t"): + _fail("release-order-ambiguous") + _signal_exact_process(supervisor, signal.SIGCONT) + _wait_for_reference_running(fence.supervisor) + return + _prove_released_activation(marker, fence, activation) + + +def _complete_released_receipt( + durable_fd: int, + runtime_fd: int, + receipt: dict[str, object], +) -> dict[str, object]: + marker = receipt["marker"] + if not isinstance(marker, dict): + _fail("released-receipt-invalid") + if receipt["releaseState"] == "intent": + _assert_runtime_binding(marker) + _release_activation_hold(durable_fd, marker) + receipt = _write_released_receipt( + durable_fd, + marker, + str(receipt["completedLedgerSha256"]), + "complete", + ) + _finish_released_cleanup(durable_fd, runtime_fd, marker) + return marker + + +def _run_locked( + action: Action, + request: Request, + durable_fd: int, + runtime_fd: int, + lock_fd: int | None = None, +) -> dict[str, object]: + if action == "acquire": + if not isinstance(request, AcquireRequest): + _fail("envelope-schema") + return _acquire(durable_fd, runtime_fd, request) + if not isinstance(request, StatusRequest): + _fail("envelope-schema") + released = _load_released_receipt(durable_fd) + if released is not None and _released_receipt_matches_status(released, request): + if action not in ("recover", "release"): + _fail("fence-already-released") + return _complete_released_receipt(durable_fd, runtime_fd, released) + if action == "recover": + return _recover(durable_fd, runtime_fd, request) + + marker, _marker_payload = _load_exact_active(durable_fd, runtime_fd, request) + _assert_runtime_binding(marker) + fence = _fence_from_value(marker["fence"]) + activation = _activation_from_marker(marker) + phase = marker["phase"] + if action == "assert": + if phase == "rolled-back" and activation is not None: + _fail("activation-retirement-pending") + _assert_active_state(marker, runtime_fd) + return marker + if action == "publish": + if phase == "published": + _assert_active_state(marker, runtime_fd) + return marker + if phase != "fenced": + _fail("publish-phase-invalid") + _assert_active_state(marker, runtime_fd) + _apply_plan_posture(marker, str(marker["target"])) + _assert_runtime_binding(marker) + _assert_active_state(marker, runtime_fd) + return _write_phase(durable_fd, runtime_fd, marker, "published") + if action == "rollback": + if phase == "rolled-back" and activation is None: + _assert_active_state(marker, runtime_fd) + return marker + if phase == "rolled-back" and activation is not None: + _retire_activation_tree(marker, runtime_fd, activation) + return _write_phase(durable_fd, runtime_fd, marker, "rolled-back", None) + if phase not in ("fenced", "published", "activation-proven"): + _fail("rollback-phase-invalid") + _assert_active_state(marker, runtime_fd) + _apply_plan_posture(marker, str(marker["rollback"])) + _assert_runtime_binding(marker) + _assert_active_state(marker, runtime_fd) + if activation is None: + return _write_phase(durable_fd, runtime_fd, marker, "rolled-back") + pending = _write_phase( + durable_fd, + runtime_fd, + marker, + "rolled-back", + _activation_payload(activation), + ) + _retire_activation_tree(pending, runtime_fd, activation) + return _write_phase(durable_fd, runtime_fd, pending, "rolled-back", None) + if action == "activate": + if phase == "activation-proven": + _assert_active_state(marker, runtime_fd) + return marker + if phase not in ("published", "rolled-back"): + _fail("activation-phase-invalid") + if activation is not None: + _retire_activation_tree(marker, runtime_fd, activation) + marker = _write_phase(durable_fd, runtime_fd, marker, "rolled-back", None) + if lock_fd is None: + proof = _activate_exact(durable_fd, marker, fence) + else: + proof = _activate_exact(durable_fd, marker, fence, lock_fd) + _assert_runtime_binding(marker) + activated = _write_phase( + durable_fd, + runtime_fd, + marker, + "activation-proven", + _activation_payload(proof), + ) + _publish_activation_receipt(runtime_fd, activated) + _assert_active_state(activated, runtime_fd) + return activated + if action == "release": + if phase != "activation-proven" or request.completed_ledger_sha256 is None: + _fail("release-phase-invalid") + if activation is None: + _fail("activation-marker-invalid") + if request.activation_provider_handle is None or not secrets.compare_digest( + request.activation_provider_handle, _activation_provider_handle(marker) + ): + _fail("activation-provider-handle-mismatch") + _assert_active_state(marker, runtime_fd) + _assert_runtime_binding(marker) + released = _write_released_receipt( + durable_fd, + marker, + request.completed_ledger_sha256, + "intent", + ) + return _complete_released_receipt(durable_fd, runtime_fd, released) + raise AssertionError(action) + + +def _parse_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Control one exact runtime state mutation", + allow_abbrev=False, + ) + parser.add_argument("action", choices=tuple(sorted(ACTIONS))) + 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) + action: Action = args.action + try: + if os.geteuid() != ROOT_UID: + _fail("root-required") + request = _parse_request(action, _read_stdin()) + durable_fd, runtime_fd = _open_control_directories() + lock_fd = -1 + try: + lock_fd = _open_lock(durable_fd) + receipt = _run_locked(action, request, durable_fd, runtime_fd, lock_fd) + finally: + if lock_fd >= 0: + fcntl.flock(lock_fd, fcntl.LOCK_UN) + os.close(lock_fd) + os.close(runtime_fd) + os.close(durable_fd) + print(_json_bytes(_receipt_payload(receipt)).decode("utf-8")) + return 0 + except ControlError as error: + print( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "action": action, + "status": "failed", + "code": error.code, + } + ).decode("utf-8"), + file=sys.stderr, + ) + return 1 + except (OSError, ValueError): + print( + _json_bytes( + { + "schemaVersion": SCHEMA_VERSION, + "action": action, + "status": "failed", + "code": "control-io-failed", + } + ).decode("utf-8"), + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/runtime-state-mutation-startup-gate.py b/scripts/runtime-state-mutation-startup-gate.py new file mode 100755 index 00000000000..f7df08f9715 --- /dev/null +++ b/scripts/runtime-state-mutation-startup-gate.py @@ -0,0 +1,676 @@ +#!/opt/hermes/.venv/bin/python3 -I +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Validate the exact non-root startup admitted by a root state-mutation permit. + +The helper has no caller-selected path or command surface. It is installed +root-owned and read-only in the Hermes image, reads only the fixed root-owned +permit/receipt names, binds them to its exact ``nemoclaw-start`` parent, and +publishes one canonical startup-complete candidate into the controller-created +nonce directory. The root controller independently verifies that candidate +and the live process tree before promoting it to activation evidence. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import secrets +import stat +import sys +from typing import NoReturn + + +SCHEMA_VERSION = 1 +ROOT_UID = 0 +ROOT_GID = 0 +DURABLE_DIRECTORY = "/var/lib/nemoclaw/runtime-state-mutation" +ACTIVE_NAME = "active.json" +PERMIT_NAME = "activation-permit.json" +RELEASE_NAME = "activation-release.json" +RETRY_NAME = "activation-retry.json" +HANDOFF_ROOT = "/run/nemoclaw/runtime-state-mutation-startup" +CANDIDATE_NAME = "startup-complete.json" +RETRY_ACK_NAME = "retry-ack.json" +PERMIT_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-permit-v1" +RELEASE_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-release-v1" +RETRY_PROTOCOL = "nemoclaw-runtime-state-mutation-activation-retry-v1" +CANDIDATE_PROTOCOL = "nemoclaw-runtime-state-mutation-startup-complete-v1" +RETRY_ACK_PROTOCOL = "nemoclaw-runtime-state-mutation-retry-ack-v1" +MAX_FILE_BYTES = 32 * 1024 +HEX_64 = re.compile(r"[0-9a-f]{64}\Z") +DECIMAL = re.compile(r"(?:0|[1-9][0-9]*)\Z") +PROCESS_REFERENCE_KEYS = ( + "pid", + "startIdentity", + "parentPid", + "uids", + "commandSha256", + "procDevice", + "procInode", +) +PERMIT_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "markerSha256", + "start", + "candidateDirectory", +) +RELEASE_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "checkpointSha256", + "start", + "candidateDirectory", +) +RETRY_KEYS = ( + "schemaVersion", + "protocol", + "transactionId", + "nonce", + "permitSha256", + "checkpointSha256", + "start", + "candidateDirectory", +) + + +class GateError(RuntimeError): + """A fixed, non-sensitive startup-gate refusal.""" + + +def _fail(code: str) -> NoReturn: + raise GateError(code) + + +def _pairs(values: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in values: + if key in result: + _fail("duplicate-json-field") + result[key] = value + return result + + +def _canonical(value: object) -> bytes: + try: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode( + "utf-8", "strict" + ) + except (TypeError, ValueError, UnicodeEncodeError): + return _fail("invalid-json") + + +def _parse(raw: bytes, code: str) -> object: + if not raw or len(raw) > MAX_FILE_BYTES: + _fail(code) + try: + value = json.loads( + raw.decode("utf-8", "strict"), + object_pairs_hook=_pairs, + parse_constant=lambda _value: _fail(code), + parse_float=lambda _value: _fail(code), + ) + except (UnicodeDecodeError, json.JSONDecodeError, GateError): + _fail(code) + if raw != _canonical(value) + b"\n": + _fail(code) + return value + + +def _directory_flags(*, readable: bool = False) -> int: + # Linux O_PATH preserves search-only 0711 traversal without granting the + # sandbox identity directory-enumeration access. Writers reopen only the + # sandbox-owned final directory readably so its fsync remains valid. + directory_access = os.O_RDONLY if readable else getattr(os, "O_PATH", os.O_RDONLY) + return directory_access | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + + +def _open_absolute_directory(path: str, *, readable_final: bool = False) -> int: + if not path.startswith("/") or os.path.normpath(path) != path: + _fail("unsafe-directory") + components = path.split("/")[1:] + current = os.open("/", _directory_flags(readable=readable_final and not components)) + try: + for index, component in enumerate(components): + next_fd = os.open( + component, + _directory_flags( + readable=readable_final and index == len(components) - 1 + ), + dir_fd=current, + ) + os.close(current) + current = next_fd + return current + except OSError: + os.close(current) + return _fail("unsafe-directory") + + +def _stable_stat(value: os.stat_result) -> tuple[object, ...]: + return ( + value.st_dev, + value.st_ino, + value.st_mode, + value.st_nlink, + value.st_uid, + value.st_gid, + value.st_size, + value.st_mtime_ns, + value.st_ctime_ns, + ) + + +def _read_at( + directory_fd: int, + name: str, + *, + uid: int, + gid: int, + mode: int, + missing: bool = False, +) -> bytes | None: + try: + fd = os.open( + name, + os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, + dir_fd=directory_fd, + ) + except FileNotFoundError: + if missing: + return None + _fail("gate-file-missing") + except OSError: + _fail("gate-file-invalid") + try: + before = os.fstat(fd) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_uid != uid + or before.st_gid != gid + or stat.S_IMODE(before.st_mode) != mode + or before.st_nlink != 1 + ): + _fail("gate-file-invalid") + payload = os.read(fd, MAX_FILE_BYTES + 1) + after = os.fstat(fd) + if ( + len(payload) > MAX_FILE_BYTES + or os.read(fd, 1) + or _stable_stat(before) != _stable_stat(after) + ): + _fail("gate-file-invalid") + return payload + finally: + os.close(fd) + + +def _active_directory() -> int | None: + try: + before = os.stat(DURABLE_DIRECTORY, follow_symlinks=False) + except FileNotFoundError: + return None + except OSError: + _fail("gate-directory-invalid") + directory_fd = _open_absolute_directory(DURABLE_DIRECTORY) + metadata = os.fstat(directory_fd) + if ( + _stable_stat(before) != _stable_stat(metadata) + or not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) != 0o711 + ): + os.close(directory_fd) + _fail("gate-directory-invalid") + return directory_fd + + +def _active_exists(directory_fd: int | None) -> bool: + if directory_fd is None: + return False + try: + metadata = os.stat(ACTIVE_NAME, dir_fd=directory_fd, follow_symlinks=False) + except FileNotFoundError: + return False + except OSError: + _fail("active-gate-invalid") + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) != 0o600 + or metadata.st_nlink != 1 + ): + _fail("active-gate-invalid") + return True + + +def _hex(value: object, code: str) -> str: + if not isinstance(value, str) or HEX_64.fullmatch(value) is None: + _fail(code) + return value + + +def _decimal(value: object, code: str) -> str: + if not isinstance(value, str) or DECIMAL.fullmatch(value) is None: + _fail(code) + return value + + +def _command_sha256(command: tuple[bytes, ...]) -> str: + framed = b"".join(len(part).to_bytes(4, "big") + part for part in command) + return hashlib.sha256(framed).hexdigest() + + +def _read_proc_file(path: str) -> bytes: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK) + except OSError: + _fail("start-process-unavailable") + try: + payload = os.read(fd, MAX_FILE_BYTES + 1) + if len(payload) > MAX_FILE_BYTES or os.read(fd, 1): + _fail("start-process-unavailable") + return payload + finally: + os.close(fd) + + +def _parse_proc_stat(raw: bytes) -> tuple[int, str]: + try: + text = raw.decode("ascii", "strict") + suffix = text[text.rindex(") ") + 2 :].split() + parent = int(suffix[1], 10) + start = suffix[19] + except (UnicodeDecodeError, ValueError, IndexError): + _fail("start-process-unavailable") + if parent < 0 or DECIMAL.fullmatch(start) is None: + _fail("start-process-unavailable") + return parent, start + + +def _parse_uids(raw: bytes) -> tuple[int, int, int, int]: + try: + lines = raw.decode("ascii", "strict").splitlines() + except UnicodeDecodeError: + _fail("start-process-unavailable") + for line in lines: + if not line.startswith("Uid:"): + continue + fields = line.split()[1:] + if len(fields) == 4 and all(DECIMAL.fullmatch(field) for field in fields): + return tuple(int(field, 10) for field in fields) # type: ignore[return-value] + return _fail("start-process-unavailable") + + +def _capture_parent() -> dict[str, object]: + pid = os.getppid() + process_path = f"/proc/{pid}" + try: + before = os.stat(process_path, follow_symlinks=False) + first = _read_proc_file(f"{process_path}/stat") + status = _read_proc_file(f"{process_path}/status") + command_raw = _read_proc_file(f"{process_path}/cmdline") + second = _read_proc_file(f"{process_path}/stat") + after = os.stat(process_path, follow_symlinks=False) + except OSError: + _fail("start-process-unavailable") + first_parent, first_start = _parse_proc_stat(first) + second_parent, second_start = _parse_proc_stat(second) + if ( + not stat.S_ISDIR(before.st_mode) + or _stable_stat(before) != _stable_stat(after) + or (first_parent, first_start) != (second_parent, second_start) + ): + _fail("start-process-unavailable") + command = tuple(part for part in command_raw.split(b"\0") if part) + return { + "pid": pid, + "startIdentity": second_start, + "parentPid": second_parent, + "uids": list(_parse_uids(status)), + "commandSha256": _command_sha256(command), + "procDevice": str(before.st_dev), + "procInode": str(before.st_ino), + } + + +def _process_reference(value: object, code: str) -> dict[str, object]: + if not isinstance(value, dict) or set(value) != set(PROCESS_REFERENCE_KEYS): + _fail(code) + if ( + type(value["pid"]) is not int + or value["pid"] <= 1 + or type(value["parentPid"]) is not int + or value["parentPid"] < 0 + or not isinstance(value["uids"], list) + or len(value["uids"]) != 4 + or any(type(uid) is not int or uid < 0 for uid in value["uids"]) + ): + _fail(code) + return { + "pid": value["pid"], + "startIdentity": _decimal(value["startIdentity"], code), + "parentPid": value["parentPid"], + "uids": value["uids"], + "commandSha256": _hex(value["commandSha256"], code), + "procDevice": _decimal(value["procDevice"], code), + "procInode": _decimal(value["procInode"], code), + } + + +def _binding(raw: bytes, protocol: str, keys: tuple[str, ...]) -> dict[str, object]: + value = _parse(raw, "gate-receipt-invalid") + if not isinstance(value, dict) or set(value) != set(keys): + _fail("gate-receipt-invalid") + if value["schemaVersion"] != SCHEMA_VERSION or value["protocol"] != protocol: + _fail("gate-receipt-invalid") + transaction_id = _hex(value["transactionId"], "gate-receipt-invalid") + nonce = _hex(value["nonce"], "gate-receipt-invalid") + expected_directory = f"{HANDOFF_ROOT}/{nonce}" + if value["candidateDirectory"] != expected_directory: + _fail("gate-receipt-invalid") + start = _process_reference(value["start"], "gate-receipt-invalid") + if _canonical(start) != _canonical(_capture_parent()): + _fail("gate-start-mismatch") + if protocol == PERMIT_PROTOCOL: + protocol_binding: dict[str, object] = { + "markerSha256": _hex(value["markerSha256"], "gate-receipt-invalid") + } + elif protocol == RELEASE_PROTOCOL: + protocol_binding = { + "checkpointSha256": _hex(value["checkpointSha256"], "gate-receipt-invalid") + } + else: + checkpoint = value["checkpointSha256"] + protocol_binding = { + "permitSha256": _hex(value["permitSha256"], "gate-receipt-invalid"), + "checkpointSha256": ( + None if checkpoint is None else _hex(checkpoint, "gate-receipt-invalid") + ), + } + normalized = { + "schemaVersion": SCHEMA_VERSION, + "protocol": protocol, + "transactionId": transaction_id, + "nonce": nonce, + **protocol_binding, + "start": start, + "candidateDirectory": expected_directory, + } + if raw != _canonical(normalized) + b"\n": + _fail("gate-receipt-invalid") + return normalized + + +def _read_binding( + directory_fd: int, name: str, protocol: str, keys: tuple[str, ...] +) -> dict[str, object] | None: + raw = _read_at( + directory_fd, + name, + uid=ROOT_UID, + gid=ROOT_GID, + mode=0o444, + missing=True, + ) + return None if raw is None else _binding(raw, protocol, keys) + + +def _candidate(binding: dict[str, object]) -> tuple[dict[str, object], bytes]: + candidate = { + "schemaVersion": SCHEMA_VERSION, + "protocol": CANDIDATE_PROTOCOL, + "transactionId": binding["transactionId"], + "nonce": binding["nonce"], + "markerSha256": binding["markerSha256"], + "start": binding["start"], + } + return candidate, _canonical(candidate) + b"\n" + + +def _publish_candidate(binding: dict[str, object]) -> None: + directory = str(binding["candidateDirectory"]) + directory_fd = _open_absolute_directory(directory, readable_final=True) + try: + metadata = os.fstat(directory_fd) + if ( + metadata.st_uid != os.geteuid() + or metadata.st_gid != os.getegid() + or stat.S_IMODE(metadata.st_mode) != 0o700 + ): + _fail("candidate-directory-invalid") + _value, payload = _candidate(binding) + existing = _read_at( + directory_fd, + CANDIDATE_NAME, + uid=os.geteuid(), + gid=os.getegid(), + mode=0o600, + missing=True, + ) + if existing is not None: + if existing != payload: + _fail("candidate-conflict") + return + temporary = f".{CANDIDATE_NAME}.{os.getpid()}.{secrets.token_hex(8)}" + fd = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + try: + view = memoryview(payload) + while view: + written = os.write(fd, view) + if written <= 0: + _fail("candidate-write-failed") + view = view[written:] + os.fchmod(fd, 0o600) + os.fsync(fd) + finally: + os.close(fd) + os.replace( + temporary, + CANDIDATE_NAME, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + ) + os.fsync(directory_fd) + except OSError: + _fail("candidate-write-failed") + finally: + os.close(directory_fd) + + +def _verify_release_candidate(binding: dict[str, object]) -> None: + directory_fd = _open_absolute_directory(str(binding["candidateDirectory"])) + try: + raw = _read_at( + directory_fd, + CANDIDATE_NAME, + uid=os.geteuid(), + gid=os.getegid(), + mode=0o600, + ) + finally: + os.close(directory_fd) + if raw is None or hashlib.sha256(raw).hexdigest() != binding["checkpointSha256"]: + _fail("release-candidate-mismatch") + + +def _verify_retry_binding(directory_fd: int, binding: dict[str, object]) -> bytes: + permit_raw = _read_at( + directory_fd, + PERMIT_NAME, + uid=ROOT_UID, + gid=ROOT_GID, + mode=0o444, + ) + if ( + permit_raw is None + or hashlib.sha256(permit_raw).hexdigest() != binding["permitSha256"] + ): + _fail("retry-permit-mismatch") + permit = _binding(permit_raw, PERMIT_PROTOCOL, PERMIT_KEYS) + if ( + binding["transactionId"] != permit["transactionId"] + or binding["nonce"] != permit["nonce"] + or binding["start"] != permit["start"] + or binding["candidateDirectory"] != permit["candidateDirectory"] + ): + _fail("retry-permit-mismatch") + checkpoint = binding["checkpointSha256"] + if checkpoint is not None: + candidate_fd = _open_absolute_directory(str(binding["candidateDirectory"])) + try: + candidate_raw = _read_at( + candidate_fd, + CANDIDATE_NAME, + uid=os.geteuid(), + gid=os.getegid(), + mode=0o600, + ) + finally: + os.close(candidate_fd) + if ( + candidate_raw is None + or hashlib.sha256(candidate_raw).hexdigest() != checkpoint + ): + _fail("retry-candidate-mismatch") + return _canonical(binding) + b"\n" + + +def _publish_retry_ack(binding: dict[str, object], retry_payload: bytes) -> None: + directory_fd = _open_absolute_directory( + str(binding["candidateDirectory"]), readable_final=True + ) + try: + metadata = os.fstat(directory_fd) + if ( + metadata.st_uid != os.geteuid() + or metadata.st_gid != os.getegid() + or stat.S_IMODE(metadata.st_mode) != 0o700 + ): + _fail("candidate-directory-invalid") + ack = { + "schemaVersion": SCHEMA_VERSION, + "protocol": RETRY_ACK_PROTOCOL, + "transactionId": binding["transactionId"], + "nonce": binding["nonce"], + "retrySha256": hashlib.sha256(retry_payload).hexdigest(), + "start": binding["start"], + } + payload = _canonical(ack) + b"\n" + existing = _read_at( + directory_fd, + RETRY_ACK_NAME, + uid=os.geteuid(), + gid=os.getegid(), + mode=0o600, + missing=True, + ) + if existing is not None: + if existing != payload: + _fail("retry-ack-conflict") + return + temporary = f".{RETRY_ACK_NAME}.{os.getpid()}.{secrets.token_hex(8)}" + fd = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + try: + view = memoryview(payload) + while view: + written = os.write(fd, view) + if written <= 0: + _fail("retry-ack-write-failed") + view = view[written:] + os.fchmod(fd, 0o600) + os.fsync(fd) + finally: + os.close(fd) + os.replace( + temporary, + RETRY_ACK_NAME, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + ) + os.fsync(directory_fd) + except OSError: + _fail("retry-ack-write-failed") + finally: + os.close(directory_fd) + + +def _run(action: str) -> str: + directory_fd = _active_directory() + if not _active_exists(directory_fd): + if directory_fd is not None: + os.close(directory_fd) + return "inactive" + assert directory_fd is not None + try: + released = _read_binding( + directory_fd, RELEASE_NAME, RELEASE_PROTOCOL, RELEASE_KEYS + ) + if released is not None: + _verify_release_candidate(released) + return "released" + retry = _read_binding(directory_fd, RETRY_NAME, RETRY_PROTOCOL, RETRY_KEYS) + if retry is not None: + retry_payload = _verify_retry_binding(directory_fd, retry) + if action == "admit": + _publish_retry_ack(retry, retry_payload) + return "retry-wait" + if action in ("restart", "resume"): + return "retry" + _fail("activation-retry-pending") + permit = _read_binding(directory_fd, PERMIT_NAME, PERMIT_PROTOCOL, PERMIT_KEYS) + if permit is None: + _fail("activation-not-permitted") + if action == "checkpoint": + _publish_candidate(permit) + return "activation-ready" + if action in ("restart", "resume"): + _fail("activation-not-released") + return "permitted" + finally: + os.close(directory_fd) + + +def main(argv: list[str] | None = None) -> int: + arguments = sys.argv[1:] if argv is None else argv + if arguments not in (["admit"], ["checkpoint"], ["restart"], ["resume"]): + print("runtime-state-mutation-startup-gate: invalid action", file=sys.stderr) + return 64 + try: + state = _run(arguments[0]) + print(state) + return { + "inactive": 0, + "released": 0, + "permitted": 10, + "activation-ready": 11, + "retry": 12, + "retry-wait": 75, + }[state] + except (GateError, OSError): + print("runtime-state-mutation-startup-gate: held", file=sys.stderr) + return 75 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/runtime_state_mutation_hermes_publisher.py b/scripts/runtime_state_mutation_hermes_publisher.py new file mode 100755 index 00000000000..1bf45514d40 --- /dev/null +++ b/scripts/runtime_state_mutation_hermes_publisher.py @@ -0,0 +1,1148 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Nonce-bound Hermes publisher for one normalized state-mutation plan. + +The runtime-state-mutation controller imports :func:`apply_plan_posture` only +after it has authenticated and normalized the durable marker. This module has +no caller-selected command, path, or callback surface: it accepts that marker +and either its exact target or rollback posture, then drives the fixed Hermes +shields transaction already shipped in the image. + +The publisher keeps a root-only journal beside the controller marker. The +journal binds the provider nonce and complete canonical plan before the Hermes +guard begins, so a lost Docker exec response can resume only the same +transaction. A successful retry independently verifies the top-level +config/hash projection and every selector in the installed state-lock plan. +""" + +from __future__ import annotations + +import fcntl +import hashlib +import importlib.util +import json +import os +import pwd +import grp +import re +import secrets +import stat +import subprocess +import sys +import time +from types import ModuleType +from typing import NoReturn + + +SCHEMA_VERSION = 1 +PLAN_SCHEMA_VERSION = 2 +ROOT_UID = 0 +ROOT_GID = 0 +HERMES_DIR = "/sandbox/.hermes" +HERMES_HASH_FILE = "/etc/nemoclaw/hermes.config-hash" +DURABLE_DIRECTORY = "/var/lib/nemoclaw/runtime-state-mutation" +JOURNAL_NAME = "hermes-publisher.json" +LOCK_NAME = "hermes-publisher.lock" +GUARD_STATE_NAME = "hermes-publisher-guard-state.json" +RUNTIME_GUARD_PATH = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py" +STATE_DIR_GUARD_PATH = "/usr/local/lib/nemoclaw/state-dir-guard.py" +STATE_LOCK_PLAN_PATH = "/usr/local/share/nemoclaw/state-lock-plan.json" +PYTHON_PATH = "/opt/hermes/.venv/bin/python3" +MAX_PLAN_BYTES = 64 * 1024 +MAX_JOURNAL_BYTES = 256 * 1024 +MAX_GUARD_STATE_BYTES = 4 * 1024 * 1024 +MAX_GUARD_OUTPUT_BYTES = 16 * 1024 +GUARD_TIMEOUT_SECONDS = 13 * 60 +HEX_64 = re.compile(r"[0-9a-f]{64}\Z") +BEGIN_OUTPUT = re.compile(r"lock_token=([0-9a-f]{64}) original_locked=([01])\n?\Z") +PHASES = frozenset( + { + "intent", + "begun", + "state-applied", + "top-applied", + "abort-requested", + "abort-prepared", + "abort-state-applied", + } +) +TOP_SELECTORS = (".config-hash", ".env", "config.yaml") + + +class PublisherError(RuntimeError): + """A fixed, non-sensitive publisher failure.""" + + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +def _fail(code: str) -> NoReturn: + raise PublisherError(code) + + +def _canonical(value: object) -> bytes: + try: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode( + "utf-8", "strict" + ) + except (TypeError, ValueError, UnicodeEncodeError): + return _fail("publisher-json-invalid") + + +def _pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + _fail("publisher-json-invalid") + result[key] = value + return result + + +def _parse_json(raw: bytes, maximum: int, code: str) -> object: + if not raw or len(raw) > maximum: + _fail(code) + try: + return json.loads( + raw.decode("utf-8", "strict"), + object_pairs_hook=_pairs, + parse_constant=lambda _value: _fail(code), + parse_float=lambda _value: _fail(code), + ) + except (UnicodeDecodeError, json.JSONDecodeError, PublisherError): + return _fail(code) + + +def _exact_record(value: object, keys: tuple[str, ...], code: str) -> dict[str, object]: + if not isinstance(value, dict) or set(value) != set(keys): + _fail(code) + return value + + +def _hex(value: object, code: str) -> str: + if not isinstance(value, str) or HEX_64.fullmatch(value) is None: + _fail(code) + return value + + +def _safe_component(value: object, code: str) -> str: + if ( + not isinstance(value, str) + or value in {"", ".", ".."} + or "/" in value + or "\\" in value + or re.fullmatch(r"[A-Za-z0-9._-]+", value) is None + ): + _fail(code) + return value + + +def _safe_relative(value: object, code: str) -> str: + if not isinstance(value, str) or value.startswith("/") or "\\" in value: + _fail(code) + pieces = value.split("/") + if any(piece in {"", ".", ".."} for piece in pieces): + _fail(code) + for piece in pieces: + if "*" in piece and piece != "*": + _fail(code) + if pieces[-1] == "*": + _fail(code) + return value + + +def _string_list(value: object, code: str, validator) -> list[str]: + if not isinstance(value, list) or len(value) > 256: + _fail(code) + result = [validator(item, code) for item in value] + if len(result) != len(set(result)): + _fail(code) + return result + + +def _normalize_state_lock_plan(value: object, *, installed: bool) -> dict[str, object]: + if not isinstance(value, dict): + _fail("publisher-state-lock-plan-invalid") + allowed = { + "version", + "readOnlyRoots", + "confidentialRoots", + "readOnlyPrefixes", + "confidentialPrefixes", + "writableSubpaths", + } + if installed: + allowed.add("$comment") + if set(value) - allowed or allowed - {"$comment"} - set(value): + _fail("publisher-state-lock-plan-invalid") + if "$comment" in value and not isinstance(value["$comment"], str): + _fail("publisher-state-lock-plan-invalid") + if type(value.get("version")) is not int or value["version"] != 1: + _fail("publisher-state-lock-plan-invalid") + read_only_roots = _string_list( + value["readOnlyRoots"], "publisher-state-lock-plan-invalid", _safe_component + ) + confidential_roots = _string_list( + value["confidentialRoots"], + "publisher-state-lock-plan-invalid", + _safe_component, + ) + read_only_prefixes = _string_list( + value["readOnlyPrefixes"], + "publisher-state-lock-plan-invalid", + _safe_component, + ) + confidential_prefixes = _string_list( + value["confidentialPrefixes"], + "publisher-state-lock-plan-invalid", + _safe_component, + ) + writable_subpaths = _string_list( + value["writableSubpaths"], + "publisher-state-lock-plan-invalid", + _safe_relative, + ) + roots = read_only_roots + confidential_roots + prefixes = read_only_prefixes + confidential_prefixes + if len(roots) != len(set(roots)) or len(prefixes) != len(set(prefixes)): + _fail("publisher-state-lock-plan-invalid") + if any(root.startswith(prefix) for root in roots for prefix in prefixes): + _fail("publisher-state-lock-plan-invalid") + for index, prefix in enumerate(prefixes): + if any( + prefix.startswith(other) or other.startswith(prefix) + for other in prefixes[index + 1 :] + ): + _fail("publisher-state-lock-plan-invalid") + if any(path.split("/", 1)[0] not in read_only_roots for path in writable_subpaths): + _fail("publisher-state-lock-plan-invalid") + return { + "version": 1, + "readOnlyRoots": read_only_roots, + "confidentialRoots": confidential_roots, + "readOnlyPrefixes": read_only_prefixes, + "confidentialPrefixes": confidential_prefixes, + "writableSubpaths": writable_subpaths, + } + + +def _read_regular( + path: str, maximum: int, code: str, *, exact_mode: int | None = None +) -> bytes: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + except OSError: + _fail(code) + try: + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or metadata.st_nlink != 1 + or (exact_mode is not None and stat.S_IMODE(metadata.st_mode) != exact_mode) + or (exact_mode is None and stat.S_IMODE(metadata.st_mode) & 0o022) + ): + _fail(code) + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(64 * 1024, maximum + 1 - total)) + if not chunk: + return b"".join(chunks) + chunks.append(chunk) + total += len(chunk) + if total > maximum: + _fail(code) + finally: + os.close(fd) + + +def _installed_state_lock_plan() -> tuple[dict[str, object], str]: + raw = _read_regular( + STATE_LOCK_PLAN_PATH, + MAX_PLAN_BYTES, + "publisher-installed-plan-invalid", + exact_mode=0o444, + ) + normalized = _normalize_state_lock_plan( + _parse_json(raw, MAX_PLAN_BYTES, "publisher-installed-plan-invalid"), + installed=True, + ) + return normalized, _canonical(normalized).decode("utf-8", "strict") + + +def _normalize_marker(marker: object, posture: str) -> dict[str, object]: + if os.geteuid() != ROOT_UID: + _fail("publisher-root-required") + if not isinstance(marker, dict): + _fail("publisher-marker-invalid") + transaction_id = _hex(marker.get("transactionId"), "publisher-marker-invalid") + nonce = _hex(marker.get("nonce"), "publisher-marker-invalid") + plan_sha256 = _hex(marker.get("planSha256"), "publisher-marker-invalid") + projection_sha256 = _hex(marker.get("projectionSha256"), "publisher-marker-invalid") + if marker.get("providerId") != "docker" or marker.get("stateRoot") != HERMES_DIR: + _fail("publisher-marker-invalid") + target = marker.get("target") + rollback = marker.get("rollback") + if ( + target not in ("locked", "mutable") + or rollback not in ("locked", "mutable") + or target == rollback + or posture not in (target, rollback) + ): + _fail("publisher-posture-invalid") + plan_text = marker.get("plan") + if not isinstance(plan_text, str): + _fail("publisher-marker-invalid") + try: + plan_raw = plan_text.encode("utf-8", "strict") + except UnicodeEncodeError: + _fail("publisher-marker-invalid") + if ( + len(plan_raw) > MAX_PLAN_BYTES + or hashlib.sha256(plan_raw).hexdigest() != plan_sha256 + ): + _fail("publisher-plan-binding-mismatch") + plan = _exact_record( + _parse_json(plan_raw, MAX_PLAN_BYTES, "publisher-plan-invalid"), + ( + "schemaVersion", + "intent", + "target", + "rollback", + "stateLockPlan", + "stateRoot", + "selectors", + "projectionSha256", + ), + "publisher-plan-invalid", + ) + if _canonical(plan) != plan_raw: + _fail("publisher-plan-noncanonical") + if ( + type(plan["schemaVersion"]) is not int + or plan["schemaVersion"] != PLAN_SCHEMA_VERSION + or plan["intent"] != "protection-transition" + or plan["target"] != target + or plan["rollback"] != rollback + or plan["stateRoot"] != HERMES_DIR + or plan["projectionSha256"] != projection_sha256 + ): + _fail("publisher-plan-binding-mismatch") + state_plan = _normalize_state_lock_plan(plan["stateLockPlan"], installed=False) + installed_plan, installed_plan_json = _installed_state_lock_plan() + if not secrets.compare_digest(_canonical(state_plan), _canonical(installed_plan)): + _fail("publisher-installed-plan-mismatch") + expected_selectors = [ + *(f"path:{name}" for name in TOP_SELECTORS), + *(f"path:{name}" for name in state_plan["readOnlyRoots"]), # type: ignore[index] + *(f"path:{name}" for name in state_plan["confidentialRoots"]), # type: ignore[index] + *(f"prefix:{name}" for name in state_plan["readOnlyPrefixes"]), # type: ignore[index] + *(f"prefix:{name}" for name in state_plan["confidentialPrefixes"]), # type: ignore[index] + ] + expected_selectors.sort(key=lambda item: item.encode("utf-8")) + selectors = plan["selectors"] + if not isinstance(selectors, list): + _fail("publisher-plan-selector-mismatch") + observed_selectors: list[str] = [] + for selector in selectors: + if not isinstance(selector, dict) or selector.get("kind") not in ( + "path", + "prefix", + ): + _fail("publisher-plan-selector-mismatch") + if selector["kind"] == "path": + exact = _exact_record( + selector, ("kind", "path"), "publisher-plan-selector-mismatch" + ) + observed_selectors.append( + "path:" + + _safe_relative(exact["path"], "publisher-plan-selector-mismatch") + ) + else: + exact = _exact_record( + selector, ("kind", "prefix"), "publisher-plan-selector-mismatch" + ) + observed_selectors.append( + "prefix:" + + _safe_component(exact["prefix"], "publisher-plan-selector-mismatch") + ) + if observed_selectors != expected_selectors: + _fail("publisher-plan-selector-mismatch") + binding = { + "schemaVersion": SCHEMA_VERSION, + "transactionId": transaction_id, + "nonce": nonce, + "planSha256": plan_sha256, + "projectionSha256": projection_sha256, + "target": target, + "rollback": rollback, + "plan": plan_text, + } + return { + "binding": binding, + "bindingSha256": hashlib.sha256(_canonical(binding)).hexdigest(), + "transactionId": transaction_id, + "nonce": nonce, + "planSha256": plan_sha256, + "projectionSha256": projection_sha256, + "target": target, + "rollback": rollback, + "posture": posture, + "stateLockPlan": state_plan, + "stateLockPlanJson": installed_plan_json, + } + + +def _open_durable_directory() -> int: + try: + fd = os.open( + DURABLE_DIRECTORY, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + ) + except OSError: + _fail("publisher-durable-directory-invalid") + metadata = os.fstat(fd) + if ( + metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or stat.S_IMODE(metadata.st_mode) != 0o711 + ): + os.close(fd) + _fail("publisher-durable-directory-invalid") + return fd + + +def _read_at(directory_fd: int, name: str, maximum: int, code: str) -> bytes | None: + try: + fd = os.open( + name, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=directory_fd + ) + except FileNotFoundError: + return None + except OSError: + _fail(code) + try: + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or metadata.st_nlink != 1 + or stat.S_IMODE(metadata.st_mode) != 0o600 + ): + _fail(code) + payload = os.read(fd, maximum + 1) + if len(payload) > maximum or os.read(fd, 1): + _fail(code) + return payload + finally: + os.close(fd) + + +def _atomic_write(directory_fd: int, name: str, value: object) -> None: + payload = _canonical(value) + b"\n" + if len(payload) > MAX_JOURNAL_BYTES: + _fail("publisher-journal-invalid") + temporary = f".{name}.{os.getpid()}.{secrets.token_hex(8)}" + fd = -1 + try: + fd = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + os.fchmod(fd, 0o600) + view = memoryview(payload) + while view: + written = os.write(fd, view) + if written <= 0: + _fail("publisher-journal-write-failed") + view = view[written:] + os.fsync(fd) + os.close(fd) + fd = -1 + os.replace(temporary, name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd) + os.fsync(directory_fd) + except OSError: + _fail("publisher-journal-write-failed") + finally: + if fd >= 0: + os.close(fd) + try: + os.unlink(temporary, dir_fd=directory_fd) + except FileNotFoundError: + # A successful replace consumes the temporary name; cleanup is best-effort. + pass + + +def _operation(posture: str, rollback_posture: str) -> dict[str, object]: + return { + "posture": posture, + "rollbackPosture": rollback_posture, + "phase": "intent", + "guardToken": None, + } + + +def _new_journal(normalized: dict[str, object]) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "bindingSha256": normalized["bindingSha256"], + "transactionId": normalized["transactionId"], + "nonce": normalized["nonce"], + "planSha256": normalized["planSha256"], + "projectionSha256": normalized["projectionSha256"], + "target": normalized["target"], + "rollback": normalized["rollback"], + "finalPosture": None, + "operation": None, + } + + +def _validate_operation(value: object) -> dict[str, object] | None: + if value is None: + return None + operation = _exact_record( + value, + ("posture", "rollbackPosture", "phase", "guardToken"), + "publisher-journal-invalid", + ) + if ( + operation["posture"] not in ("locked", "mutable") + or operation["rollbackPosture"] not in ("locked", "mutable") + or operation["posture"] == operation["rollbackPosture"] + or operation["phase"] not in PHASES + or ( + operation["guardToken"] is not None + and HEX_64.fullmatch(str(operation["guardToken"])) is None + ) + ): + _fail("publisher-journal-invalid") + return operation + + +def _load_journal( + directory_fd: int, normalized: dict[str, object] +) -> dict[str, object]: + raw = _read_at( + directory_fd, JOURNAL_NAME, MAX_JOURNAL_BYTES, "publisher-journal-invalid" + ) + if raw is None: + journal = _new_journal(normalized) + _atomic_write(directory_fd, JOURNAL_NAME, journal) + return journal + journal = _exact_record( + _parse_json(raw, MAX_JOURNAL_BYTES, "publisher-journal-invalid"), + ( + "schemaVersion", + "bindingSha256", + "transactionId", + "nonce", + "planSha256", + "projectionSha256", + "target", + "rollback", + "finalPosture", + "operation", + ), + "publisher-journal-invalid", + ) + if type(journal["schemaVersion"]) is not int or journal["schemaVersion"] != 1: + _fail("publisher-journal-invalid") + operation = _validate_operation(journal["operation"]) + final_posture = journal["finalPosture"] + if final_posture not in (None, "locked", "mutable"): + _fail("publisher-journal-invalid") + if journal["bindingSha256"] != normalized["bindingSha256"]: + if operation is not None: + _fail("publisher-binding-mismatch") + journal = _new_journal(normalized) + _atomic_write(directory_fd, JOURNAL_NAME, journal) + return journal + expected = { + "transactionId": normalized["transactionId"], + "nonce": normalized["nonce"], + "planSha256": normalized["planSha256"], + "projectionSha256": normalized["projectionSha256"], + "target": normalized["target"], + "rollback": normalized["rollback"], + } + if any(journal[key] != value for key, value in expected.items()): + _fail("publisher-binding-mismatch") + return journal + + +def _write_journal(directory_fd: int, journal: dict[str, object]) -> None: + _atomic_write(directory_fd, JOURNAL_NAME, journal) + + +def _acquire_lock(directory_fd: int) -> int: + try: + fd = os.open( + LOCK_NAME, + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=directory_fd, + ) + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or metadata.st_nlink != 1 + or stat.S_IMODE(metadata.st_mode) != 0o600 + ): + os.close(fd) + _fail("publisher-lock-invalid") + fcntl.flock(fd, fcntl.LOCK_EX) + return fd + except OSError: + return _fail("publisher-lock-invalid") + + +def _trusted_executable(path: str) -> None: + try: + metadata = os.stat(path, follow_symlinks=False) + except OSError: + _fail("publisher-guard-untrusted") + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_uid != ROOT_UID + or metadata.st_gid != ROOT_GID + or metadata.st_nlink != 1 + or stat.S_IMODE(metadata.st_mode) & 0o022 + ): + _fail("publisher-guard-untrusted") + + +def _run_guard(action: str, arguments: list[str]) -> str: + _trusted_executable(RUNTIME_GUARD_PATH) + command = [ + PYTHON_PATH, + "-I", + RUNTIME_GUARD_PATH, + action, + "--hermes-dir", + HERMES_DIR, + *arguments, + ] + try: + result = subprocess.run( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + timeout=GUARD_TIMEOUT_SECONDS, + env={ + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "LANG": "C", + "LC_ALL": "C", + }, + ) + except (OSError, subprocess.TimeoutExpired): + _fail("publisher-guard-failed") + if ( + result.returncode != 0 + or len(result.stdout) > MAX_GUARD_OUTPUT_BYTES + or len(result.stderr) > MAX_GUARD_OUTPUT_BYTES + ): + _fail("publisher-guard-failed") + try: + return result.stdout.decode("ascii", "strict") + except UnicodeDecodeError: + return _fail("publisher-guard-failed") + + +def _guard_state_path() -> str: + return os.path.join(DURABLE_DIRECTORY, GUARD_STATE_NAME) + + +def _guard_arguments(*values: str) -> list[str]: + return list(values) + + +def _begin_guard(posture: str, rollback_posture: str) -> str: + output = _run_guard( + "begin-shields-transition", + _guard_arguments( + "--hash-file", + HERMES_HASH_FILE, + "--state-file", + _guard_state_path(), + "--shields-mode", + posture, + "--rollback-shields-mode", + rollback_posture, + ), + ) + matched = BEGIN_OUTPUT.fullmatch(output) + if matched is None: + _fail("publisher-guard-failed") + return matched.group(1) + + +def _state_guard(token: str, posture: str, plan_json: str) -> None: + _run_guard( + "run-state-dir-transition", + _guard_arguments( + "--state-file", + _guard_state_path(), + "--lock-token", + token, + "--state-action", + "lock" if posture == "locked" else "unlock", + "--state-lock-plan-json", + plan_json, + ), + ) + + +def _apply_guard(token: str) -> None: + _run_guard( + "apply-shields-transition", + _guard_arguments("--state-file", _guard_state_path(), "--lock-token", token), + ) + + +def _finish_guard(token: str) -> None: + _run_guard( + "finish-shields-transition", + _guard_arguments( + "--hash-file", + HERMES_HASH_FILE, + "--state-file", + _guard_state_path(), + "--lock-token", + token, + ), + ) + + +def _prepare_abort_guard(token: str) -> None: + _run_guard( + "prepare-shields-abort", + _guard_arguments("--state-file", _guard_state_path(), "--lock-token", token), + ) + + +def _abort_guard(token: str) -> None: + _run_guard( + "abort-shields-transition", + _guard_arguments("--state-file", _guard_state_path(), "--lock-token", token), + ) + + +def _load_guard_state(directory_fd: int) -> dict[str, object] | None: + raw = _read_at( + directory_fd, + GUARD_STATE_NAME, + MAX_GUARD_STATE_BYTES, + "publisher-guard-state-invalid", + ) + if raw is None: + return None + value = _parse_json(raw, MAX_GUARD_STATE_BYTES, "publisher-guard-state-invalid") + if not isinstance(value, dict): + _fail("publisher-guard-state-invalid") + return value + + +def _matching_guard_token( + directory_fd: int, posture: str, rollback_posture: str +) -> tuple[str, str] | None: + state = _load_guard_state(directory_fd) + if state is None: + return None + transition = state.get("shields_transition") + token = state.get("mutation_lock_token") + phase = state.get("phase") + if ( + not isinstance(transition, dict) + or HEX_64.fullmatch(str(token)) is None + or state.get("hermes_dir") != HERMES_DIR + or state.get("hash_file") != HERMES_HASH_FILE + or transition.get("mode") != posture + or transition.get("rollback_mode") != rollback_posture + or not isinstance(phase, str) + ): + _fail("publisher-guard-state-invalid") + return str(token), phase + + +def _load_module(path: str, name: str) -> ModuleType: + _trusted_executable(path) + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail("publisher-verifier-unavailable") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except Exception: + sys.modules.pop(name, None) + _fail("publisher-verifier-unavailable") + return module + + +def _verify_top_posture(posture: str) -> None: + runtime = _load_module( + RUNTIME_GUARD_PATH, "_nemoclaw_runtime_state_mutation_hermes_guard" + ) + try: + runtime._verify_strict_hash(HERMES_DIR, HERMES_HASH_FILE) + runtime._verify_compat_hash( + HERMES_HASH_FILE, os.path.join(HERMES_DIR, ".config-hash") + ) + sandbox_uid = pwd.getpwnam("sandbox").pw_uid + sandbox_gid = grp.getgrnam("sandbox").gr_gid + except Exception: + _fail("publisher-top-posture-invalid") + parent = os.stat(os.path.dirname(HERMES_DIR), follow_symlinks=False) + root = os.stat(HERMES_DIR, follow_symlinks=False) + if not stat.S_ISDIR(parent.st_mode) or not stat.S_ISDIR(root.st_mode): + _fail("publisher-top-posture-invalid") + if posture == "locked": + expected_parent = (ROOT_UID, sandbox_gid, 0o1775) + expected_root_owners = (ROOT_UID, sandbox_gid) + expected_root_modes = (0o3770,) + expected_file = (ROOT_UID, ROOT_GID, 0o444) + else: + expected_parent = (sandbox_uid, sandbox_gid, 0o755) + expected_root_owners = (sandbox_uid, sandbox_gid) + expected_root_modes = (0o700, 0o3770) + expected_file = (sandbox_uid, sandbox_gid, 0o640) + if (parent.st_uid, parent.st_gid, stat.S_IMODE(parent.st_mode)) != expected_parent: + _fail("publisher-top-posture-invalid") + if (root.st_uid, root.st_gid) != expected_root_owners or stat.S_IMODE( + root.st_mode + ) not in expected_root_modes: + _fail("publisher-top-posture-invalid") + for name in TOP_SELECTORS: + path = os.path.join(HERMES_DIR, name) + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + except OSError: + _fail("publisher-top-posture-invalid") + try: + metadata = os.fstat(fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or (metadata.st_uid, metadata.st_gid, stat.S_IMODE(metadata.st_mode)) + != expected_file + ): + _fail("publisher-top-posture-invalid") + finally: + os.close(fd) + + +def _verify_state_posture(posture: str, plan_json: str) -> None: + guard = _load_module( + STATE_DIR_GUARD_PATH, "_nemoclaw_runtime_state_mutation_state_dir_guard" + ) + try: + plan = guard.parse_agent_state_lock_plan(plan_json) + identity = guard._production_identity() + config_fd = guard._open_absolute_dir_nofollow(HERMES_DIR) + config_st = os.fstat(config_fd) + deadline = time.monotonic() + guard.MAX_GUARD_SECONDS + roots, issues = guard._preflight( + config_fd, + HERMES_DIR, + config_st.st_dev, + deadline, + "lock" if posture == "locked" else "unlock", + plan, + ) + if issues: + _fail("publisher-state-posture-invalid") + expected_roots = {(root.name, root.dev, root.ino) for root in roots} + context = guard.TraversalContext( + config_fd, + HERMES_DIR, + config_st.st_dev, + tuple(root.name for root in roots), + guard.WorkBudget(deadline), + plan.writable_subpaths, + ) + verification_issues: list[object] = [] + for root in roots: + root_st = os.stat(root.name, dir_fd=config_fd, follow_symlinks=False) + root_fd = guard._open_child_dir(config_fd, root.name, root_st) + try: + guard._verify_dir( + context, + root_fd, + root.name, + root.policy, + "lock" if posture == "locked" else "unlock", + identity, + {}, + verification_issues, + 1, + is_root=True, + ) + finally: + os.close(root_fd) + current, selection_issues = guard._select_roots( + config_fd, HERMES_DIR, config_st.st_dev, plan + ) + if ( + verification_issues + or selection_issues + or {(root.name, root.dev, root.ino) for root in current} != expected_roots + ): + _fail("publisher-state-posture-invalid") + except PublisherError: + raise + except Exception: + _fail("publisher-state-posture-invalid") + finally: + if "config_fd" in locals(): + os.close(config_fd) + + +def _verify_final_posture(posture: str, plan_json: str) -> str: + _verify_top_posture(posture) + _verify_state_posture(posture, plan_json) + payload = { + "schemaVersion": SCHEMA_VERSION, + "posture": posture, + "stateLockPlanSha256": hashlib.sha256(plan_json.encode("utf-8")).hexdigest(), + } + return hashlib.sha256(_canonical(payload)).hexdigest() + + +def _receipt( + normalized: dict[str, object], verification_sha256: str +) -> dict[str, object]: + return { + "schemaVersion": SCHEMA_VERSION, + "protocol": "nemoclaw-runtime-state-mutation-publisher-v1", + "transactionId": normalized["transactionId"], + "nonce": normalized["nonce"], + "planSha256": normalized["planSha256"], + "projectionSha256": normalized["projectionSha256"], + "posture": normalized["posture"], + "verificationSha256": verification_sha256, + } + + +def _persist_phase( + directory_fd: int, + journal: dict[str, object], + operation: dict[str, object], + phase: str, + token: str | None = None, +) -> None: + operation["phase"] = phase + if token is not None: + operation["guardToken"] = token + journal["operation"] = operation + _write_journal(directory_fd, journal) + + +def _complete( + directory_fd: int, + journal: dict[str, object], + normalized: dict[str, object], +) -> dict[str, object]: + verification = _verify_final_posture( + str(normalized["posture"]), str(normalized["stateLockPlanJson"]) + ) + journal["finalPosture"] = normalized["posture"] + journal["operation"] = None + _write_journal(directory_fd, journal) + return _receipt(normalized, verification) + + +def _continue_forward( + directory_fd: int, + journal: dict[str, object], + operation: dict[str, object], + normalized: dict[str, object], +) -> dict[str, object]: + posture = str(operation["posture"]) + rollback_posture = str(operation["rollbackPosture"]) + phase = str(operation["phase"]) + token = operation["guardToken"] + guard_state = _matching_guard_token(directory_fd, posture, rollback_posture) + if phase == "intent": + if guard_state is None: + token = _begin_guard(posture, rollback_posture) + else: + token, guard_phase = guard_state + if guard_phase not in ( + "shields-transition-pending", + "shields-transition-applied", + ): + _fail("publisher-guard-state-incomplete") + _persist_phase(directory_fd, journal, operation, "begun", str(token)) + phase = "begun" + if not isinstance(token, str) or HEX_64.fullmatch(token) is None: + _fail("publisher-journal-invalid") + if phase == "begun": + _state_guard(token, posture, str(normalized["stateLockPlanJson"])) + _persist_phase(directory_fd, journal, operation, "state-applied") + phase = "state-applied" + if phase == "state-applied": + _apply_guard(token) + _persist_phase(directory_fd, journal, operation, "top-applied") + phase = "top-applied" + if phase == "top-applied": + if _load_guard_state(directory_fd) is not None: + _finish_guard(token) + return _complete(directory_fd, journal, normalized) + return _fail("publisher-journal-invalid") + + +def _continue_abort( + directory_fd: int, + journal: dict[str, object], + operation: dict[str, object], + normalized: dict[str, object], +) -> dict[str, object]: + token = operation["guardToken"] + if not isinstance(token, str) or HEX_64.fullmatch(token) is None: + _fail("publisher-journal-invalid") + requested = str(normalized["posture"]) + if operation["rollbackPosture"] != requested: + _fail("publisher-posture-invalid") + phase = str(operation["phase"]) + if phase == "abort-requested": + state = _load_guard_state(directory_fd) + transition = ( + state.get("shields_transition") if isinstance(state, dict) else None + ) + if ( + isinstance(state, dict) + and state.get("phase") == "shields-transition-aborting" + and isinstance(transition, dict) + and transition.get("mode") == requested + ): + pass + else: + _prepare_abort_guard(token) + _persist_phase(directory_fd, journal, operation, "abort-prepared") + phase = "abort-prepared" + if phase == "abort-prepared": + _state_guard(token, requested, str(normalized["stateLockPlanJson"])) + _persist_phase(directory_fd, journal, operation, "abort-state-applied") + phase = "abort-state-applied" + if phase == "abort-state-applied": + if _load_guard_state(directory_fd) is not None: + _abort_guard(token) + return _complete(directory_fd, journal, normalized) + return _fail("publisher-journal-invalid") + + +def apply_plan_posture(marker: dict[str, object], posture: str) -> dict[str, object]: + """Apply and verify ``posture`` for one controller-normalized marker. + + ``posture`` must be exactly ``marker["target"]`` or + ``marker["rollback"]``. The return value is a canonicalizable receipt; + callers must still keep the controller fence active until activation and + host-ledger completion. + """ + + normalized = _normalize_marker(marker, posture) + directory_fd = _open_durable_directory() + lock_fd = -1 + try: + lock_fd = _acquire_lock(directory_fd) + journal = _load_journal(directory_fd, normalized) + operation = _validate_operation(journal["operation"]) + if operation is None and journal["finalPosture"] == posture: + verification = _verify_final_posture( + posture, str(normalized["stateLockPlanJson"]) + ) + return _receipt(normalized, verification) + if operation is None: + rollback_posture = ( + str(journal["finalPosture"]) + if journal["finalPosture"] in ("locked", "mutable") + else str( + normalized["rollback"] + if posture == normalized["target"] + else normalized["target"] + ) + ) + if rollback_posture == posture: + _fail("publisher-journal-invalid") + operation = _operation(posture, rollback_posture) + journal["operation"] = operation + _write_journal(directory_fd, journal) + if operation["posture"] != posture: + guard_state = _load_guard_state(directory_fd) + if operation["phase"] == "top-applied" and guard_state is None: + # finish committed and removed its state, but the Docker exec + # response was lost before this journal advanced. Prove that + # posture first, then perform the requested opposite posture + # as a fresh complete transaction. + _verify_final_posture( + str(operation["posture"]), + str(normalized["stateLockPlanJson"]), + ) + journal["finalPosture"] = operation["posture"] + operation = _operation(posture, str(journal["finalPosture"])) + journal["operation"] = operation + _write_journal(directory_fd, journal) + elif operation["phase"] == "intent" and guard_state is None: + rollback_posture = str(operation["posture"]) + operation = _operation(posture, rollback_posture) + journal["operation"] = operation + _write_journal(directory_fd, journal) + else: + if operation["rollbackPosture"] != posture: + _fail("publisher-posture-invalid") + if operation["phase"] == "intent": + recovered = _matching_guard_token( + directory_fd, + str(operation["posture"]), + str(operation["rollbackPosture"]), + ) + if recovered is None or recovered[1] not in ( + "shields-transition-pending", + "shields-transition-applied", + ): + _fail("publisher-guard-state-incomplete") + _persist_phase( + directory_fd, + journal, + operation, + "begun", + recovered[0], + ) + if operation["phase"] not in ( + "abort-requested", + "abort-prepared", + "abort-state-applied", + ): + _persist_phase(directory_fd, journal, operation, "abort-requested") + return _continue_abort(directory_fd, journal, operation, normalized) + if str(operation["phase"]).startswith("abort-"): + return _continue_abort(directory_fd, journal, operation, normalized) + return _continue_forward(directory_fd, journal, operation, normalized) + finally: + if lock_fd >= 0: + fcntl.flock(lock_fd, fcntl.LOCK_UN) + os.close(lock_fd) + os.close(directory_fd) + + +def main() -> int: + print( + "runtime_state_mutation_hermes_publisher is a controller-imported module", + file=sys.stderr, + ) + return 64 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts index d23a52c2297..6eeac47b531 100644 --- a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts +++ b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts @@ -11,7 +11,7 @@ const captureSandboxSshConfig = vi.hoisted(() => vi.fn()); vi.mock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, spawnSync: vi.fn() }; + return { ...actual, spawnSync: vi.fn(actual.spawnSync) }; }); vi.mock("../../adapters/openshell/runtime", () => ({ diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index c2b75ecd7cd..12bd5be0195 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -27,6 +27,7 @@ import { ROOT, shellQuote } from "../../runner"; import { isDirectSandboxFallbackUnavailableError, privilegedSandboxExecArgv, + withPrivilegedSandboxExecutionLease, } from "../../sandbox/privileged-exec"; import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; import * as registry from "../../state/registry"; @@ -98,6 +99,7 @@ function commandTransportDependencies(): CommandTransportDependencies { openshellProbeTimeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, privilegedSandboxExecArgv, root: ROOT, + withPrivilegedSandboxExecutionLease, }; } @@ -150,20 +152,26 @@ export function executePrivilegedSandboxCommand( command: readonly string[], timeout: number, ): SandboxCommandResult | null { - const argv = privilegedSandboxExecArgv(sandboxName, [...command], false, true); - const result = dockerSpawnSync(argv, { - cwd: ROOT, - encoding: "utf-8", - env: buildSubprocessEnv(), - stdio: ["ignore", "pipe", "pipe"], - timeout, - }); - if (result.error) return null; - return { - status: result.status ?? 1, - stdout: String(result.stdout || ""), - stderr: String(result.stderr || ""), - }; + return withPrivilegedSandboxExecutionLease( + sandboxName, + "sandbox process recovery controller", + () => { + const argv = privilegedSandboxExecArgv(sandboxName, [...command], false, true); + const result = dockerSpawnSync(argv, { + cwd: ROOT, + encoding: "utf-8", + env: buildSubprocessEnv(), + stdio: ["ignore", "pipe", "pipe"], + timeout, + }); + if (result.error) return null; + return { + status: result.status ?? 1, + stdout: String(result.stdout || ""), + stderr: String(result.stderr || ""), + }; + }, + ); } export function executeSandboxExecCommand( @@ -188,15 +196,49 @@ function executeGatewaySupervisorActionPinned( expectedContainerId?: string, ): ManagedGatewaySupervisorActionResult | null { const nonce = randomBytes(32).toString("hex"); - let argv: string[]; try { - argv = privilegedSandboxExecArgv( - sandboxName, - [MANAGED_GATEWAY_CONTROL_PATH, action, nonce], - false, - true, - expectedContainerId, - ); + return withPrivilegedSandboxExecutionLease(sandboxName, `gateway supervisor ${action}`, () => { + const argv = privilegedSandboxExecArgv( + sandboxName, + [MANAGED_GATEWAY_CONTROL_PATH, action, nonce], + false, + true, + expectedContainerId, + ); + const controlPathIndex = argv.lastIndexOf(MANAGED_GATEWAY_CONTROL_PATH); + const targetContainerId = controlPathIndex > 0 ? argv[controlPathIndex - 1] : null; + 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(); + const restartingContainerMatch = stderr.match(DOCKER_CONTAINER_RESTARTING_ERROR); + const managedControlRestartingContainerId = + status === 1 && + stdout === "" && + restartingContainerMatch?.[1] !== undefined && + restartingContainerMatch[1] === targetContainerId + ? restartingContainerMatch[1] + : undefined; + 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, + ...(managedControlRestartingContainerId ? { managedControlRestartingContainerId } : {}), + }; + }); } catch (error) { if (isDirectSandboxFallbackUnavailableError(error)) { // New clones can report Ready before their labeled direct container is @@ -215,40 +257,6 @@ function executeGatewaySupervisorActionPinned( stderr: `PRIVILEGED_CONTROL_UNAVAILABLE: ${detail}`, }; } - - const controlPathIndex = argv.lastIndexOf(MANAGED_GATEWAY_CONTROL_PATH); - const targetContainerId = controlPathIndex > 0 ? argv[controlPathIndex - 1] : null; - 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(); - const restartingContainerMatch = stderr.match(DOCKER_CONTAINER_RESTARTING_ERROR); - const managedControlRestartingContainerId = - status === 1 && - stdout === "" && - restartingContainerMatch?.[1] !== undefined && - restartingContainerMatch[1] === targetContainerId - ? restartingContainerMatch[1] - : undefined; - 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, - ...(managedControlRestartingContainerId ? { managedControlRestartingContainerId } : {}), - }; } type RequestPinnedGatewaySupervisorAction = typeof executeGatewaySupervisorActionPinned; diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 9dc200a96e1..849f4ab7050 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -97,7 +97,11 @@ vi.mock("../../shields", () => ({ vi.mock("../../shields/timer-bound-lock", () => ({ withTimerBoundShieldsMutationLock: vi.fn((_sandbox, _command, fn) => fn()), })); -vi.mock("../../shields/timer-control", () => ({ readTimerMarker: vi.fn(() => null) })); +vi.mock("../../shields/timer-control", () => ({ + isProcessAlive: vi.fn(() => true), + readProcessStartIdentity: vi.fn(() => "snapshot-test-process-start"), + readTimerMarker: vi.fn(() => null), +})); vi.mock("../../state/gateway", () => ({ isGatewayHealthy: vi.fn(() => true), isSandboxReady: vi.fn((output: string, sandboxName: string) => diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index 155f1330c14..3b153ef8481 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -273,6 +273,8 @@ vi.mock("../../shields/timer-bound-lock", () => ({ })); vi.mock("../../shields/timer-control", () => ({ + isProcessAlive: vi.fn(() => true), + readProcessStartIdentity: vi.fn(() => "snapshot-test-process-start"), readTimerMarker: lifecycleMock.readTimerMarkerMock, })); diff --git a/src/lib/adapters/sandbox/command-transport.test.ts b/src/lib/adapters/sandbox/command-transport.test.ts new file mode 100644 index 00000000000..3f0413de1d8 --- /dev/null +++ b/src/lib/adapters/sandbox/command-transport.test.ts @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + createTempSshConfig: vi.fn(), + resolveOpenshellSandboxSshHost: vi.fn(), + spawnSync: vi.fn(), +})); + +vi.mock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, spawnSync: mocks.spawnSync }; +}); + +vi.mock("../../sandbox/temp-ssh-config", () => ({ + createTempSshConfig: mocks.createTempSshConfig, +})); + +vi.mock("../openshell/sandbox-ssh-host", () => ({ + resolveOpenshellSandboxSshHost: mocks.resolveOpenshellSandboxSshHost, +})); + +import { + type CommandTransportDependencies, + executeSandboxCommandTransport, + executeSandboxExecCommandTransport, +} from "./command-transport"; + +function spawnResult( + stdout: string, + overrides: Partial> = {}, +): ReturnType { + return { + error: undefined, + output: [], + pid: 1234, + signal: null, + status: 0, + stderr: "", + stdout, + ...overrides, + } as ReturnType; +} + +function createDependencies( + overrides: Partial = {}, +): CommandTransportDependencies { + return { + buildSandboxExecMarkedCommand: vi.fn((command: string) => `marked:${command}`), + buildSubprocessEnv: vi.fn(() => ({ PATH: "/usr/bin" })), + captureSandboxSshConfig: vi.fn(() => ({ + output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", + status: 0, + })), + dockerSpawnSync: vi.fn(() => spawnResult("fallback-output")), + extractSandboxExecCommandStdout: vi.fn((output: string) => output), + getOpenshellBinary: vi.fn(() => "/usr/bin/openshell"), + isDirectSandboxFallbackUnavailableError: vi.fn(() => false), + openshellProbeTimeoutMs: 5000, + privilegedSandboxExecArgv: vi.fn(() => ["exec", "container-id", "sh", "-c", "marked:id"]), + root: "/repo", + withPrivilegedSandboxExecutionLease: ( + _sandboxName: string, + _operation: string, + fn: () => T, + ): T => fn(), + ...overrides, + }; +} + +describe("sandbox command transport privileged execution lease", () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + it("holds the SSH lease from config resolution through process cleanup", () => { + const events: string[] = []; + let leaseHeld = false; + const assertLeaseHeld = (event: string): void => { + expect(leaseHeld).toBe(true); + events.push(event); + }; + const withLease: CommandTransportDependencies["withPrivilegedSandboxExecutionLease"] = ( + sandboxName: string, + operation: string, + fn: () => T, + ): T => { + expect(leaseHeld).toBe(false); + events.push(`lease:${sandboxName}:${operation}`); + leaseHeld = true; + try { + return fn(); + } finally { + leaseHeld = false; + events.push("lease:released"); + } + }; + const deps = createDependencies({ + buildSubprocessEnv: vi.fn(() => { + assertLeaseHeld("environment"); + return { PATH: "/usr/bin" }; + }), + captureSandboxSshConfig: vi.fn(() => { + assertLeaseHeld("config"); + return { + output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", + status: 0, + }; + }), + withPrivilegedSandboxExecutionLease: withLease, + }); + mocks.resolveOpenshellSandboxSshHost.mockImplementation(() => { + assertLeaseHeld("host"); + return "openshell-alpha.default"; + }); + mocks.createTempSshConfig.mockImplementation(() => { + assertLeaseHeld("temp"); + return { + cleanup: () => assertLeaseHeld("cleanup"), + dir: "/tmp/nemoclaw-ssh-test", + file: "/tmp/nemoclaw-ssh-test/ssh_config", + }; + }); + mocks.spawnSync.mockImplementation(() => { + assertLeaseHeld("spawn"); + return spawnResult("ok\n"); + }); + + expect(executeSandboxCommandTransport(deps, "alpha", "id")).toEqual({ + status: 0, + stderr: "", + stdout: "ok", + }); + expect(events).toEqual([ + "lease:alpha:sandbox SSH command transport", + "config", + "host", + "temp", + "environment", + "spawn", + "cleanup", + "lease:released", + ]); + }); + + it("does not resolve SSH state or spawn when lease acquisition is rejected", () => { + const rejection = new Error("provider fence active"); + const deps = createDependencies({ + withPrivilegedSandboxExecutionLease: ( + sandboxName: string, + operation: string, + _fn: () => T, + ): T => { + expect(sandboxName).toBe("alpha"); + expect(operation).toBe("sandbox SSH command transport"); + throw rejection; + }, + }); + + expect(() => executeSandboxCommandTransport(deps, "alpha", "id")).toThrow(rejection); + expect(deps.captureSandboxSshConfig).not.toHaveBeenCalled(); + expect(mocks.resolveOpenshellSandboxSshHost).not.toHaveBeenCalled(); + expect(mocks.createTempSshConfig).not.toHaveBeenCalled(); + expect(mocks.spawnSync).not.toHaveBeenCalled(); + }); + + it("holds one lease across OpenShell failure and the complete local fallback", () => { + const events: string[] = []; + let leaseHeld = false; + let leaseCalls = 0; + const assertLeaseHeld = (event: string): void => { + expect(leaseHeld).toBe(true); + events.push(event); + }; + const withLease: CommandTransportDependencies["withPrivilegedSandboxExecutionLease"] = ( + sandboxName: string, + operation: string, + fn: () => T, + ): T => { + leaseCalls += 1; + expect(leaseHeld).toBe(false); + events.push(`lease:${sandboxName}:${operation}`); + leaseHeld = true; + try { + return fn(); + } finally { + leaseHeld = false; + events.push("lease:released"); + } + }; + const deps = createDependencies({ + buildSandboxExecMarkedCommand: vi.fn((command: string) => { + assertLeaseHeld("mark"); + return `marked:${command}`; + }), + buildSubprocessEnv: vi.fn(() => { + assertLeaseHeld("environment"); + return { PATH: "/usr/bin" }; + }), + dockerSpawnSync: vi.fn(() => { + assertLeaseHeld("fallback-spawn"); + return spawnResult("fallback-output"); + }), + extractSandboxExecCommandStdout: vi.fn((output: string) => { + assertLeaseHeld(`parse:${output}`); + return output === "fallback-output" ? "fallback-ok" : null; + }), + getOpenshellBinary: vi.fn(() => { + assertLeaseHeld("openshell-resolution"); + return "/usr/bin/openshell"; + }), + privilegedSandboxExecArgv: vi.fn(() => { + assertLeaseHeld("fallback-resolution"); + return ["exec", "container-id", "sh", "-c", "marked:id"]; + }), + withPrivilegedSandboxExecutionLease: withLease, + }); + mocks.spawnSync.mockImplementation(() => { + assertLeaseHeld("openshell-spawn"); + return spawnResult("unmarked-output", { status: 1 }); + }); + + expect(executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, {})).toEqual({ + status: 0, + stderr: "", + stdout: "fallback-ok", + }); + expect(leaseCalls).toBe(1); + expect(events).toEqual([ + "lease:alpha:sandbox OpenShell command transport", + "mark", + "openshell-resolution", + "environment", + "openshell-spawn", + "parse:unmarked-output", + "fallback-resolution", + "environment", + "fallback-spawn", + "parse:fallback-output", + "lease:released", + ]); + }); + + it("does not resolve either exec transport or spawn when lease acquisition is rejected", () => { + const rejection = new Error("provider fence active"); + const deps = createDependencies({ + withPrivilegedSandboxExecutionLease: ( + sandboxName: string, + operation: string, + _fn: () => T, + ): T => { + expect(sandboxName).toBe("alpha"); + expect(operation).toBe("sandbox OpenShell command transport"); + throw rejection; + }, + }); + + expect(() => executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, {})).toThrow( + rejection, + ); + expect(deps.buildSandboxExecMarkedCommand).not.toHaveBeenCalled(); + expect(deps.getOpenshellBinary).not.toHaveBeenCalled(); + expect(deps.privilegedSandboxExecArgv).not.toHaveBeenCalled(); + expect(deps.dockerSpawnSync).not.toHaveBeenCalled(); + expect(mocks.spawnSync).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/adapters/sandbox/command-transport.ts b/src/lib/adapters/sandbox/command-transport.ts index c592e6e6af2..3065a8ab0f6 100644 --- a/src/lib/adapters/sandbox/command-transport.ts +++ b/src/lib/adapters/sandbox/command-transport.ts @@ -32,6 +32,11 @@ export type CommandTransportDependencies = { openshellProbeTimeoutMs: number; privilegedSandboxExecArgv: (sandboxName: string, command: string[]) => string[]; root: string; + withPrivilegedSandboxExecutionLease: ( + sandboxName: string, + operation: string, + fn: () => T, + ) => T; }; export const DEFAULT_SANDBOX_EXEC_TIMEOUT_MS = 15000; @@ -46,50 +51,56 @@ export function executeSandboxCommandTransport( sandboxName: string, command: string, ): SandboxCommandResult | null { - const sshConfigResult = deps.captureSandboxSshConfig(sandboxName, { - ignoreError: true, - timeout: deps.openshellProbeTimeoutMs, - }); - if (sshConfigResult.status !== 0) return null; - if (!sshConfigResult.output.trim()) return null; - const sshHost = resolveOpenshellSandboxSshHost(sandboxName, sshConfigResult.output); - if (sshHost === null) return null; + return deps.withPrivilegedSandboxExecutionLease( + sandboxName, + "sandbox SSH command transport", + () => { + const sshConfigResult = deps.captureSandboxSshConfig(sandboxName, { + ignoreError: true, + timeout: deps.openshellProbeTimeoutMs, + }); + if (sshConfigResult.status !== 0) return null; + if (!sshConfigResult.output.trim()) return null; + const sshHost = resolveOpenshellSandboxSshHost(sandboxName, sshConfigResult.output); + if (sshHost === null) return null; - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-"); - try { - const result = spawnSync( - "ssh", - [ - "-F", - tmpSshConfig.file, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=5", - "-o", - "LogLevel=ERROR", - sshHost, - command, - ], - { - encoding: "utf-8", - env: deps.buildSubprocessEnv(), - stdio: ["ignore", "pipe", "pipe"], - timeout: DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, - }, - ); - return { - status: result.status ?? 1, - stdout: (result.stdout || "").trim(), - stderr: (result.stderr || "").trim(), - }; - } catch { - return null; - } finally { - tmpSshConfig.cleanup(); - } + const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-"); + try { + const result = spawnSync( + "ssh", + [ + "-F", + tmpSshConfig.file, + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=5", + "-o", + "LogLevel=ERROR", + sshHost, + command, + ], + { + encoding: "utf-8", + env: deps.buildSubprocessEnv(), + stdio: ["ignore", "pipe", "pipe"], + timeout: DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, + }, + ); + return { + status: result.status ?? 1, + stdout: (result.stdout || "").trim(), + stderr: (result.stderr || "").trim(), + }; + } catch { + return null; + } finally { + tmpSshConfig.cleanup(); + } + }, + ); } function parseSandboxCommandResult( @@ -147,27 +158,35 @@ export function executeSandboxExecCommandTransport( timeout: number, options: SandboxExecCommandOptions, ): SandboxCommandResult | null { - const markedCommand = deps.buildSandboxExecMarkedCommand(command); - const effectiveTimeout = resolveSandboxExecTimeout(timeout); - try { - const result = spawnSync( - deps.getOpenshellBinary(), - ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", markedCommand], - { - cwd: deps.root, - encoding: "utf-8", - env: deps.buildSubprocessEnv(), - stdio: ["ignore", "pipe", "pipe"], - timeout: effectiveTimeout, - }, - ); - const parsed = parseSandboxCommandResult(deps, result); - if (parsed !== null) return parsed; - } catch { - // OpenShell transport failed; try the trusted direct-container fallback. - } - if (options.allowLocalDockerFallback === false) return null; - // 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(deps, sandboxName, markedCommand, effectiveTimeout); + return deps.withPrivilegedSandboxExecutionLease( + sandboxName, + "sandbox OpenShell command transport", + () => { + const markedCommand = deps.buildSandboxExecMarkedCommand(command); + const effectiveTimeout = resolveSandboxExecTimeout(timeout); + try { + const result = spawnSync( + deps.getOpenshellBinary(), + ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", markedCommand], + { + cwd: deps.root, + encoding: "utf-8", + env: deps.buildSubprocessEnv(), + stdio: ["ignore", "pipe", "pipe"], + timeout: effectiveTimeout, + }, + ); + const parsed = parseSandboxCommandResult(deps, result); + if (parsed !== null) return parsed; + } catch { + // OpenShell transport failed; try the trusted direct-container fallback. + } + if (options.allowLocalDockerFallback === false) return null; + // Keep the fallback outside the OpenShell try/catch so a fail-closed identity + // refusal cannot be caught and retried against changing container state. + // The outer execution lease covers argv resolution and the complete fallback + // subprocess lifetime without an unleased gap after the OpenShell attempt. + return executeLocalDockerSandboxCommand(deps, sandboxName, markedCommand, effectiveTimeout); + }, + ); } diff --git a/src/lib/domain/uninstall/shims.test.ts b/src/lib/domain/uninstall/shims.test.ts index e7c658fa838..6d8ee4a8368 100644 --- a/src/lib/domain/uninstall/shims.test.ts +++ b/src/lib/domain/uninstall/shims.test.ts @@ -40,6 +40,22 @@ describe("uninstall shim classification", () => { }); }); + it("recognizes installer-managed wrappers with an idempotent Node PATH", () => { + const contents = [ + "#!/usr/bin/env bash", + '[[ "$(command -v node 2>/dev/null)" == "/tmp/node-bin/node" ]] || export PATH="/tmp/node-bin:$PATH"', + 'exec "/tmp/prefix/bin/nemoclaw" "$@"', + ].join("\n"); + + expect(isInstallerManagedWrapperContents(contents)).toBe(true); + expect( + classifyNemoclawShim({ contents, exists: true, isFile: true, isSymlink: false }), + ).toMatchObject({ + kind: "managed-wrapper", + remove: true, + }); + }); + it("recognizes agent-alias wrapper shims by bin name (#6098)", () => { const hermesWrapper = [ "#!/usr/bin/env bash", @@ -100,6 +116,16 @@ describe("uninstall shim classification", () => { isSymlink: false, }), ).toMatchObject({ kind: "preserve-foreign-file", remove: false }); + + expect( + isInstallerManagedWrapperContents( + [ + "#!/usr/bin/env bash", + '[[ "$(command -v node 2>/dev/null)" == "/tmp/other-node-bin/node" ]] || export PATH="/tmp/node-bin:$PATH"', + 'exec "/tmp/prefix/bin/nemoclaw" "$@"', + ].join("\n"), + ), + ).toBe(false); }); it("treats missing and non-regular paths as no-remove cases", () => { diff --git a/src/lib/domain/uninstall/shims.ts b/src/lib/domain/uninstall/shims.ts index c74560a7092..45e12b3da4c 100644 --- a/src/lib/domain/uninstall/shims.ts +++ b/src/lib/domain/uninstall/shims.ts @@ -34,10 +34,14 @@ export function isInstallerManagedWrapperContents(contents: string, binName = "n const lines = normalized.split("\n"); if (lines.length !== 3) return false; const [shebang, pathLine, execLine] = lines; + const legacyPathLine = pathLine.startsWith('export PATH="') && pathLine.endsWith(':$PATH"'); + const stablePathLine = + /^\[\[ "\$\(command -v node 2>\/dev\/null\)" == "(.+)\/node" \]\] \|\| export PATH="\1:\$PATH"$/u.test( + pathLine, + ); return ( shebang === "#!/usr/bin/env bash" && - pathLine.startsWith('export PATH="') && - pathLine.endsWith(':$PATH"') && + (legacyPathLine || stablePathLine) && execLine.startsWith('exec "') && execLine.endsWith(`/${binName}" "$@"`) ); diff --git a/src/lib/inference/llama-cpp/host-local-runtime.test.ts b/src/lib/inference/llama-cpp/host-local-runtime.test.ts index f8d18e22fed..b34e86e6b17 100644 --- a/src/lib/inference/llama-cpp/host-local-runtime.test.ts +++ b/src/lib/inference/llama-cpp/host-local-runtime.test.ts @@ -220,6 +220,7 @@ describe("llama.cpp host-local runtime materializer", () => { "ALL", "--security-opt", "no-new-privileges=true", + "--no-healthcheck", "--memory", "51539607552b", "--memory-swap", @@ -279,6 +280,8 @@ describe("llama.cpp host-local runtime materializer", () => { const argv = buildLlamaCppRequestGuardDockerArgv(input, runtime); const separator = argv.indexOf("--"); + expect(valuesAfter(argv, "--publish")).toEqual([]); + expect(argv).toContain("--no-healthcheck"); expect(valuesAfter(argv, "--entrypoint")).toEqual([LLAMA_CPP_HOST_LOCAL_REQUEST_GUARD_PATH]); expect(valuesAfter(argv, "--listen-port")).toEqual([String(input.serve.port)]); expect(valuesAfter(argv, "--upstream-port")).toEqual([ diff --git a/src/lib/inference/llama-cpp/host-local-runtime.ts b/src/lib/inference/llama-cpp/host-local-runtime.ts index be0c37cb1de..37a14f0d844 100644 --- a/src/lib/inference/llama-cpp/host-local-runtime.ts +++ b/src/lib/inference/llama-cpp/host-local-runtime.ts @@ -309,6 +309,71 @@ export function buildLlamaCppHostLocalDockerArgv( ]; } +const dockerLoopbackPublishAuthorityBrand = Symbol("DockerLoopbackPublishAuthority"); +const issuedDockerLoopbackPublishAuthorities = new WeakSet(); +const consumedDockerLoopbackPublishAuthorities = new WeakSet(); +const MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION = [28, 3, 3] as const; + +export interface DockerLoopbackPublishAuthority { + readonly serverVersion: string; + readonly [dockerLoopbackPublishAuthorityBrand]: true; +} + +/** + * Admit Docker loopback publishing only after querying the live server through the launch endpoint. + * The trusted qualification host must retain Docker's default protected NAT and firewall behavior. + */ +export function qualifyDockerLoopbackPublishAuthority( + serverVersionOutput: string, +): DockerLoopbackPublishAuthority { + const serverVersion = serverVersionOutput.trim(); + const match = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:\+[0-9A-Za-z.-]+)?$/u.exec( + serverVersion, + ); + const version = match?.slice(1, 4).map(Number); + const meetsMinimum = + version !== undefined && + (version[0]! > MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION[0] || + (version[0] === MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION[0] && + (version[1]! > MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION[1] || + (version[1] === MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION[1] && + version[2]! >= MINIMUM_SECURE_DOCKER_LOOPBACK_PUBLISH_VERSION[2])))); + if ( + !version || + version.length !== 3 || + version.some((part) => !Number.isSafeInteger(part)) || + !meetsMinimum + ) { + throw new Error( + "llama.cpp qualification requires Docker Engine 28.3.3 or newer for loopback publishing.", + ); + } + const authority = Object.freeze({ + serverVersion, + [dockerLoopbackPublishAuthorityBrand]: true as const, + }); + issuedDockerLoopbackPublishAuthorities.add(authority); + return authority; +} + +/** Consume a single-use authority immediately before one Docker loopback publication. */ +export function consumeDockerLoopbackPublishAuthority( + authority: DockerLoopbackPublishAuthority, +): void { + if ( + typeof authority !== "object" || + authority === null || + authority[dockerLoopbackPublishAuthorityBrand] !== true || + !issuedDockerLoopbackPublishAuthorities.has(authority) + ) { + throw new Error("llama.cpp Docker loopback publishing authority is invalid."); + } + if (consumedDockerLoopbackPublishAuthorities.has(authority)) { + throw new Error("llama.cpp Docker loopback publishing authority was already consumed."); + } + consumedDockerLoopbackPublishAuthorities.add(authority); +} + /** Activate the request guard only for an image that declares the owned guard artifact. */ export function buildLlamaCppRequestGuardDockerArgv( contract: LlamaCppHostLocalLaunchContract, @@ -380,6 +445,7 @@ function buildLlamaCppHostLocalDockerRunArgv( "ALL", "--security-opt", "no-new-privileges=true", + "--no-healthcheck", "--memory", `${String(resources.memoryBytes)}b`, "--memory-swap", diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index b4b144c83a9..a383d2293c8 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -40,6 +40,7 @@ import type { SandboxCreateIntent, } from "../sandbox-create-intent-types"; import { + OPENSHELL_SANDBOX_SUPERVISOR_ARGV, prepareSandboxCreateLaunch, prepareSandboxCreateLaunchWithPrebuild, type SandboxCreateLaunchInput, @@ -408,7 +409,7 @@ export function resolveOnboardManagedBootstrapLaunch(input: { }, agentIdentity: managedImageRuntimeIdentity(input.workload.source.contract.agent), intendedWorkloadArgv: input.intendedWorkloadArgv, - expectedSupervisorArgv: ["/opt/openshell/bin/openshell-sandbox", "--workdir", "/sandbox"], + expectedSupervisorArgv: OPENSHELL_SANDBOX_SUPERVISOR_ARGV, } as const; } diff --git a/src/lib/onboard/runtime-provider/access.ts b/src/lib/onboard/runtime-provider/access.ts index af0360ec7af..affb856b0cb 100644 --- a/src/lib/onboard/runtime-provider/access.ts +++ b/src/lib/onboard/runtime-provider/access.ts @@ -8,8 +8,13 @@ export type { RuntimeProviderGatewayLauncher, RuntimeProviderManagedImageSupport, RuntimeProviderPreparedStateMutationPlan, + RuntimeProviderStateMutationActivationProof, + RuntimeProviderStateMutationContext, + RuntimeProviderStateMutationFence, RuntimeProviderStateMutationPlan, + RuntimeProviderStateMutationProtectionPosture, RuntimeProviderStateMutationSelector, + RuntimeProviderStateMutationStateLockPlan, RuntimeProviderStateMutationSurface, RuntimeProviderWorkloadCleanupPlan, RuntimeProviderWorkloadCleanupResult, @@ -19,6 +24,11 @@ export { CURRENT_RUNTIME_PROVIDER_BUNDLES, resolveCurrentRuntimeProviderBundle, } from "./current"; +export { + createFilePersistedEngineLifecycleStore, + hasActivePersistedEngineStateMutationTarget, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, +} from "./persisted-engine-lifecycle"; export type { RuntimeProviderDestructiveCleanupAuthority } from "./registry"; export { normalizeRuntimeProviderIdentity, @@ -28,7 +38,11 @@ export { requireRuntimeProviderDestructiveCleanupAuthority, requireRuntimeProviderHostLocalInferenceOperation, requireRuntimeProviderMutationAuthority, + requireRuntimeProviderStateMutationSurface, resolveRuntimeProviderBundle, runtimeProviderContainerEngineIdentity, } from "./registry"; -export { prepareRuntimeProviderStateMutationPlan } from "./state-mutation"; +export { + prepareAgentDefinitionProtectionTransitionPlan, + prepareRuntimeProviderStateMutationPlan, +} from "./state-mutation"; diff --git a/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index d2f41f873b2..64c1e097166 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -18,8 +18,8 @@ import type { export const RUNTIME_PROVIDER_BUNDLE_CONTRACT_VERSION = 1 as const; export const RUNTIME_PROVIDER_SNAPSHOT_CONTRACT_VERSION = 1 as const; export const RUNTIME_PROVIDER_SNAPSHOT_PREFLIGHT_SCHEMA_VERSION = 1 as const; -export const RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION = 1 as const; -export const RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION = 1 as const; +export const RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION = 2 as const; +export const RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION = 2 as const; export type RuntimeProviderGatewayLauncher = "nemoclaw" | "openshell"; export type RuntimeProviderLifecycleAction = "start" | "stop"; @@ -222,18 +222,50 @@ export type RuntimeProviderStateMutationSelector = | { readonly kind: "path"; readonly path: string } | { readonly kind: "prefix"; readonly prefix: string }; +export type RuntimeProviderStateMutationProtectionPosture = "locked" | "mutable"; +export type RuntimeProviderStateMutationFencePhase = + | "fenced" + | "published" + | "rolled-back" + | "activation-proven"; + +/** Exact recursive protection policy consumed by a fixed provider helper. */ +export interface RuntimeProviderStateMutationStateLockPlan { + readonly version: 1; + readonly readOnlyRoots: readonly string[]; + readonly confidentialRoots: readonly string[]; + readonly readOnlyPrefixes: readonly string[]; + readonly confidentialPrefixes: readonly string[]; + readonly writableSubpaths: readonly string[]; +} + /** One bounded runtime provider state mutation. Providers never accept commands or callbacks. */ -export interface RuntimeProviderStateMutationPlan { +interface RuntimeProviderStateMutationPlanBase { readonly schemaVersion: typeof RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION; - readonly intent: "protection-transition" | "restore"; readonly stateRoot: string; readonly selectors: readonly RuntimeProviderStateMutationSelector[]; /** Digest of the complete projection produced by the selected AgentDefinition. */ readonly projectionSha256: string; } +export type RuntimeProviderStateMutationPlan = + | (RuntimeProviderStateMutationPlanBase & { + readonly intent: "protection-transition"; + readonly target: RuntimeProviderStateMutationProtectionPosture; + readonly rollback: RuntimeProviderStateMutationProtectionPosture; + readonly stateLockPlan: RuntimeProviderStateMutationStateLockPlan; + }) + | (RuntimeProviderStateMutationPlanBase & { + readonly intent: "restore"; + readonly target?: never; + readonly rollback?: never; + readonly stateLockPlan?: never; + }); + export interface RuntimeProviderPreparedStateMutationPlan { readonly plan: RuntimeProviderStateMutationPlan; + /** Canonical bounded JSON suitable for a fixed provider helper's stdin. */ + readonly serializedPlan: string; readonly planSha256: string; readonly projectionSha256: string; } @@ -247,12 +279,25 @@ export interface RuntimeProviderStateMutationContext { /** Opaque provider proof for one active, exact-runtime provider state mutation fence. */ export interface RuntimeProviderStateMutationFence { readonly schemaVersion: 1; + readonly intent: "protection-transition"; + /** Last durable helper phase observed when this fence was returned. */ + readonly phase: RuntimeProviderStateMutationFencePhase; readonly providerId: string; readonly sandboxName: string; + readonly transactionId: string; readonly lifecycleGeneration: string; + readonly runtimeId: string; + readonly runtimeStateSha256: string; + /** Digest of the exact operation-scoped provider engine binding. */ + readonly engineBindingSha256: string; readonly stateRoot: string; + readonly mountNamespaceId: string; + readonly stateRootDevice: string; + readonly stateRootInode: string; readonly planSha256: string; readonly projectionSha256: string; + readonly target: RuntimeProviderStateMutationProtectionPosture; + readonly rollback: RuntimeProviderStateMutationProtectionPosture; readonly nonce: string; readonly providerHandle: string; } @@ -263,9 +308,12 @@ export interface RuntimeProviderStateMutationActivationProof { readonly providerId: string; readonly sandboxName: string; readonly lifecycleGeneration: string; + readonly runtimeId: string; + readonly nonce: string; readonly configurationGeneration: string; readonly listenerIdentity: string; readonly healthSha256: string; + readonly providerHandle: string; } /** @@ -347,19 +395,30 @@ export type RuntimeProviderStateMutationSurface = /** Frozen, digested runtime provider state mutation plan. */ readonly plan: RuntimeProviderPreparedStateMutationPlan; }, - ): Promise; + ): RuntimeProviderStateMutationFence; assertFenced( input: RuntimeProviderStateMutationContext, fence: RuntimeProviderStateMutationFence, - ): Promise; + ): void; + publish( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): void; + rollback( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): void; activate( input: RuntimeProviderStateMutationContext, fence: RuntimeProviderStateMutationFence, - proof: RuntimeProviderStateMutationActivationProof, - ): Promise; - recover( + ): RuntimeProviderStateMutationActivationProof; + release( input: RuntimeProviderStateMutationContext, - ): Promise; + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, + completedLedgerSha256: string, + ): void; + recover(input: RuntimeProviderStateMutationContext): RuntimeProviderStateMutationFence | null; }> | RuntimeProviderUnsupportedSurface; diff --git a/src/lib/onboard/runtime-provider/docker-llama-cpp-managed-lifecycle.test.ts b/src/lib/onboard/runtime-provider/docker-llama-cpp-managed-lifecycle.test.ts index b51bffbd819..171c8055820 100644 --- a/src/lib/onboard/runtime-provider/docker-llama-cpp-managed-lifecycle.test.ts +++ b/src/lib/onboard/runtime-provider/docker-llama-cpp-managed-lifecycle.test.ts @@ -386,11 +386,8 @@ describe("dormant Docker llama.cpp managed lifecycle", () => { const fixture = dockerFixture(); const store = journalStore(); const privateBridge = privateBridgeFixture(); - const lifecycle = createLifecycle( - options(fixture, store, { ...bindings(), hostPort: 8081 }), - {}, - privateBridge, - ); + const runtimeBindings = { ...bindings(), hostPort: 8081 }; + const lifecycle = createLifecycle(options(fixture, store, runtimeBindings), {}, privateBridge); const writer = receiptWriter(); const receipt = lifecycle.start(writer); const serialized = serializeHostLocalInferenceReceipt(receipt); @@ -415,6 +412,9 @@ describe("dormant Docker llama.cpp managed lifecycle", () => { expect(serialized).not.toContain(modelPath); expect(serialized).not.toContain("filesystemIdentity"); expect(serialized).not.toContain("test-only-secret"); + expect(fixture.capture.mock.calls.map(([argv]) => argv)).toContainEqual( + expect.arrayContaining(["create", "--no-healthcheck"]), + ); expect(lifecycle.runtime.inspectManaged(receipt).running).toBe(true); expect(lifecycle.runtime.stopManaged(receipt).running).toBe(false); expect(lifecycle.runtime.prepareDestroy(receipt)).toEqual(receipt); diff --git a/src/lib/onboard/runtime-provider/docker-llama-cpp-operation.ts b/src/lib/onboard/runtime-provider/docker-llama-cpp-operation.ts index 949f8f526f6..43041aa5257 100644 --- a/src/lib/onboard/runtime-provider/docker-llama-cpp-operation.ts +++ b/src/lib/onboard/runtime-provider/docker-llama-cpp-operation.ts @@ -1,277 +1,87 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { createHash } from "node:crypto"; -import os from "node:os"; -import path from "node:path"; - import { type ContainerEngine, type ContainerEngineCommandCapture, - createContainerEngineCommand, } from "../../adapters/container-engine"; -import { dockerSpawn } from "../../adapters/docker/exec"; import { createDockerLlamaCppManagedLifecycle, type DockerLlamaCppManagedLifecycle, } from "./docker-llama-cpp-managed-lifecycle"; +import { + createDockerOperationAuthority, + dockerOperationBindingSha256, + dockerOperationCommandArguments, +} from "./docker-operation-authority"; import type { HostLocalInferenceCommandSpawner, HostLocalInferenceOperation, } from "./host-local-inference"; -interface DockerClientBinding { - readonly endpointArgs: readonly string[]; - readonly identity: string; - readonly guard?: () => void; -} - export interface DockerLlamaCppOperationAuthority { readonly assertAuthority: () => void; readonly engine: ContainerEngine; readonly spawn: HostLocalInferenceCommandSpawner; } -const DOCKER_CONTEXT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,254}$/u; -const DOCKER_HOST_PATTERN = /^(?:npipe|ssh|tcp|unix):\/\/[^\s\u0000-\u001f\u007f]+$/u; -const DOCKER_ARGUMENT_MAX_BYTES = 16 * 1024; -const DOCKER_CONTEXT_INSPECT_FORMAT = "{{json .}}"; - -function exactDockerValue(value: string | undefined, label: string): string | undefined { - if (value === undefined || value === "") return undefined; - if ( - value !== value.trim() || - Buffer.byteLength(value, "utf8") > DOCKER_ARGUMENT_MAX_BYTES || - /[\u0000-\u001f\u007f-\u009f]/u.test(value) - ) { - throw new Error(`Managed llama.cpp ${label} is invalid.`); - } - return value; -} - -function absoluteDockerPath(value: string, label: string): string { - const candidate = exactDockerValue(value, label); - if (!candidate) throw new Error(`Managed llama.cpp ${label} is invalid.`); - return path.resolve(candidate); -} - -function dockerConfigPath(env: NodeJS.ProcessEnv): string { - const configured = exactDockerValue(env.DOCKER_CONFIG, "DOCKER_CONFIG"); - if (configured) return path.resolve(configured); - const home = exactDockerValue(env.HOME, "HOME") ?? os.homedir(); - return path.join(path.resolve(home), ".docker"); -} - -function dockerTlsArgs(env: NodeJS.ProcessEnv): { - readonly args: readonly string[]; - readonly verify: boolean; -} { - const tls = exactDockerValue(env.DOCKER_TLS, "DOCKER_TLS") !== undefined; - const tlsVerify = exactDockerValue(env.DOCKER_TLS_VERIFY, "DOCKER_TLS_VERIFY") !== undefined; - const certPath = exactDockerValue(env.DOCKER_CERT_PATH, "DOCKER_CERT_PATH"); - const args: string[] = []; - if (tlsVerify) args.push("--tlsverify"); - else if (tls) args.push("--tls"); - if (certPath) { - const directory = absoluteDockerPath(certPath, "DOCKER_CERT_PATH"); - args.push( - "--tlscacert", - path.join(directory, "ca.pem"), - "--tlscert", - path.join(directory, "cert.pem"), - "--tlskey", - path.join(directory, "key.pem"), - ); - } - return Object.freeze({ args: Object.freeze(args), verify: tlsVerify }); -} - -function dockerContextName(value: string, label: string): string { - const context = exactDockerValue(value, label); - if (!context || !DOCKER_CONTEXT_PATTERN.test(context)) { - throw new Error(`Managed llama.cpp ${label} is invalid.`); - } - return context; -} - -function dockerHost(value: string): string { - const host = exactDockerValue(value, "DOCKER_HOST"); - if (!host || !DOCKER_HOST_PATTERN.test(host)) { - throw new Error("Managed llama.cpp DOCKER_HOST is invalid."); - } - return host; -} - -function requireSecureDockerEndpoint(host: string, tlsVerificationEnabled: boolean): void { - if (host.startsWith("tcp://") && !tlsVerificationEnabled) { - throw new Error("Managed llama.cpp requires verified TLS for remote Docker TCP endpoints."); - } -} - -function dockerBindingProbe( - endpointArgs: readonly string[], - capture?: ContainerEngineCommandCapture, -): ContainerEngine { - return createContainerEngineCommand({ - operation: "host-local-inference", - engineId: "docker", - displayName: "Docker", - authorityId: "docker:qualification", - executable: "docker", - endpointArgs, - ...(capture ? { capture } : {}), - }); -} - -function requireDockerProbeOutput( - result: ReturnType, - label: string, -): string { - if (result.error || result.status !== 0) { - throw new Error(`Managed llama.cpp could not ${label}.`); - } - const output = result.stdout.trim(); - if (!output) throw new Error(`Managed llama.cpp could not ${label}.`); - return output; -} - -function resolvedDockerContextEndpoint(probe: ContainerEngine, context: string): string { - const output = requireDockerProbeOutput( - probe.capture(["context", "inspect", context, "--format", DOCKER_CONTEXT_INSPECT_FORMAT]), - "qualify the Docker context endpoint", - ); - let endpoint: unknown; +function withManagedLlamaCppError(run: () => T): T { try { - endpoint = JSON.parse(output); - } catch { - throw new Error("Managed llama.cpp Docker context endpoint is unreadable."); - } - if (typeof endpoint !== "object" || endpoint === null) { - throw new Error("Managed llama.cpp Docker context endpoint is invalid."); - } - const inspection = endpoint as { - Endpoints?: { docker?: { Host?: unknown; SkipTLSVerify?: unknown } }; - TLSMaterial?: { docker?: unknown }; - }; - const dockerEndpoint = inspection.Endpoints?.docker; - if ( - typeof dockerEndpoint?.Host !== "string" || - typeof dockerEndpoint.SkipTLSVerify !== "boolean" - ) { - throw new Error("Managed llama.cpp Docker context endpoint is invalid."); - } - const host = dockerHost(dockerEndpoint.Host); - const tlsMaterial = inspection.TLSMaterial?.docker ?? []; - if ( - !Array.isArray(tlsMaterial) || - tlsMaterial.some((entry) => typeof entry !== "string" || !/^[A-Za-z0-9._-]+$/u.test(entry)) - ) { - throw new Error("Managed llama.cpp Docker context TLS material is invalid."); + return run(); + } catch (error) { + if (error instanceof Error && error.message.startsWith("Docker operation ")) { + throw new Error(error.message.replace(/^Docker operation /u, "Managed llama.cpp ")); + } + if (error instanceof Error && error.message.startsWith("Docker context endpoint changed ")) { + throw new Error(`Managed llama.cpp ${error.message}`); + } + throw error; } - const tlsFiles = [...tlsMaterial].sort(); - requireSecureDockerEndpoint(host, !dockerEndpoint.SkipTLSVerify && tlsFiles.includes("ca.pem")); - return JSON.stringify({ - host, - skipTlsVerify: dockerEndpoint.SkipTLSVerify, - tlsMaterial: tlsFiles, - }); } -function dockerClientBinding( - env: NodeJS.ProcessEnv, - capture?: ContainerEngineCommandCapture, -): DockerClientBinding { - const configArgs = ["--config", dockerConfigPath(env)] as const; - const tls = dockerTlsArgs(env); - const explicitContext = exactDockerValue(env.DOCKER_CONTEXT, "DOCKER_CONTEXT"); - const explicitHost = exactDockerValue(env.DOCKER_HOST, "DOCKER_HOST"); - if (!explicitContext && explicitHost) { - const host = dockerHost(explicitHost); - requireSecureDockerEndpoint(host, tls.verify); - const endpointArgs = Object.freeze([...configArgs, "--host", host, ...tls.args]); - return { - endpointArgs, - identity: createHash("sha256").update(JSON.stringify(endpointArgs)).digest("hex"), - }; - } - - let context: string; - if (explicitContext) { - context = dockerContextName(explicitContext, "DOCKER_CONTEXT"); - } else { - const selectorProbe = dockerBindingProbe([...configArgs, ...tls.args], capture); - context = dockerContextName( - requireDockerProbeOutput( - selectorProbe.capture(["context", "show"]), - "resolve the Docker context", - ), - "current Docker context", - ); - } - const endpointArgs = Object.freeze([...configArgs, "--context", context, ...tls.args]); - const endpointProbe = dockerBindingProbe(endpointArgs, capture); - const qualifiedEndpoint = resolvedDockerContextEndpoint(endpointProbe, context); - const identity = createHash("sha256") - .update(JSON.stringify({ endpointArgs, qualifiedEndpoint })) - .digest("hex"); - return { - endpointArgs, - identity, - guard: () => { - if (resolvedDockerContextEndpoint(endpointProbe, context) !== qualifiedEndpoint) { - throw new Error( - "Managed llama.cpp Docker context endpoint changed after qualification; retry the operation.", - ); - } - }, - }; +function managedLlamaCppEngine(engine: ContainerEngine): ContainerEngine { + return Object.freeze({ + operation: engine.operation, + engineId: engine.engineId, + displayName: engine.displayName, + authorityId: engine.authorityId, + capture: (args: readonly string[], timeoutMs?: number, input?: Buffer) => + withManagedLlamaCppError(() => engine.capture(args, timeoutMs, input)), + captureHost: (args: readonly string[], timeoutMs?: number) => + withManagedLlamaCppError(() => engine.captureHost(args, timeoutMs)), + }); } /** Bind synchronous lifecycle commands and streamed acquisition to one qualified daemon. */ export function createDockerLlamaCppOperationAuthority( env: NodeJS.ProcessEnv = process.env, capture?: ContainerEngineCommandCapture, - spawnCommand: HostLocalInferenceCommandSpawner = dockerSpawn, + spawnCommand?: HostLocalInferenceCommandSpawner, ): DockerLlamaCppOperationAuthority { - const binding = dockerClientBinding(env, capture); - const assertAuthority = () => binding.guard?.(); - const engine = createContainerEngineCommand({ - operation: "host-local-inference", - engineId: "docker", - displayName: "Docker", - authorityId: `docker:${binding.identity}`, - executable: "docker", - endpointArgs: binding.endpointArgs, - ...(capture ? { capture } : {}), - ...(binding.guard ? { guard: binding.guard } : {}), - }); + const authority = withManagedLlamaCppError(() => + createDockerOperationAuthority("host-local-inference", env, capture), + ); + const assertAuthority = () => withManagedLlamaCppError(authority.assertAuthority); return Object.freeze({ assertAuthority, - engine, + engine: managedLlamaCppEngine(authority.engine), spawn: (args: readonly string[], options?: Parameters[1]) => { assertAuthority(); - return spawnCommand([...binding.endpointArgs, ...args], options); + return spawnCommand + ? spawnCommand([...dockerOperationCommandArguments(authority, args)], options) + : authority.spawn(args, options); }, }); } export function dockerLlamaCppBindingSha256(engine: ContainerEngine): string { - return createHash("sha256") - .update( - JSON.stringify({ - operation: engine.operation, - engineId: engine.engineId, - authorityId: engine.authorityId, - executable: "docker", - }), - ) - .digest("hex"); + return dockerOperationBindingSha256(engine); } export function createDockerLlamaCppHostLocalOperation( env: NodeJS.ProcessEnv = process.env, capture?: ContainerEngineCommandCapture, - spawnCommand: HostLocalInferenceCommandSpawner = dockerSpawn, + spawnCommand?: HostLocalInferenceCommandSpawner, createLifecycle: ( input: Parameters[0], ) => DockerLlamaCppManagedLifecycle = createDockerLlamaCppManagedLifecycle, diff --git a/src/lib/onboard/runtime-provider/docker-operation-authority.test.ts b/src/lib/onboard/runtime-provider/docker-operation-authority.test.ts new file mode 100644 index 00000000000..e53b8a6a525 --- /dev/null +++ b/src/lib/onboard/runtime-provider/docker-operation-authority.test.ts @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +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, vi } from "vitest"; +import { + createContextCapture as contextCapture, + createDriftingContextCapture, +} from "../../../../test/helpers/docker-operation-authority-test-helpers"; +import { createDockerLlamaCppOperationAuthority } from "./docker-llama-cpp-operation"; +import { + createDockerOperationAuthority, + dockerOperationBindingSha256, + dockerOperationCommandArguments, +} from "./docker-operation-authority"; + +const roots: string[] = []; + +function fakeExecutableRoot(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-authority-")); + roots.push(root); + return root; +} + +function writeFakeExecutable(root: string, name: string, script: string): void { + fs.writeFileSync(path.join(root, name), `#!/bin/sh\n${script}\n`, { mode: 0o700 }); +} + +function fakeDocker(output: string): string { + return fakeDockerScript(`printf '%s\\n' '${output}'`); +} + +function fakeDockerScript(script: string): string { + const root = fakeExecutableRoot(); + writeFakeExecutable(root, "docker", script); + return root; +} + +afterEach(() => { + vi.unstubAllEnvs(); + for (const root of roots.splice(0)) fs.rmSync(root, { force: true, recursive: true }); +}); + +describe("Docker operation authority", () => { + it("binds the requested operation and endpoint to every daemon command", () => { + const capture = contextCapture("ssh://nvidia@spark.example.test"); + const authority = createDockerOperationAuthority( + "sandbox-lifecycle", + { DOCKER_CONFIG: "/tmp/nemoclaw-docker", DOCKER_CONTEXT: "spark" }, + capture, + ); + + expect(authority.engine.operation).toBe("sandbox-lifecycle"); + expect(authority.engine.capture(["info"]).status).toBe(0); + expect(path.isAbsolute(capture.mock.calls.at(-2)?.[0] ?? "")).toBe(true); + expect(capture.mock.calls.at(-2)?.[1]).toEqual([ + "--config", + "/tmp/nemoclaw-docker", + "--context", + "spark", + "info", + ]); + expect(dockerOperationCommandArguments(authority, ["exec", "sandbox"])).toEqual([ + "--config", + "/tmp/nemoclaw-docker", + "--context", + "spark", + "exec", + "sandbox", + ]); + }); + + it("includes operation, engine, and executable-qualified authority in the stable binding digest", () => { + const capture = contextCapture("ssh://nvidia@spark.example.test"); + const lifecycle = createDockerOperationAuthority( + "sandbox-lifecycle", + { HOME: "/tmp/nemoclaw-home", DOCKER_CONTEXT: "spark" }, + capture, + ); + const cleanup = createDockerOperationAuthority( + "workload-cleanup", + { HOME: "/tmp/nemoclaw-home", DOCKER_CONTEXT: "spark" }, + capture, + ); + + expect(lifecycle.engine.authorityId).toBe(cleanup.engine.authorityId); + expect(dockerOperationBindingSha256(lifecycle.engine)).not.toBe( + dockerOperationBindingSha256(cleanup.engine), + ); + expect(dockerOperationBindingSha256(lifecycle.engine)).toBe( + createHash("sha256") + .update( + JSON.stringify({ + operation: "sandbox-lifecycle", + engineId: "docker", + authorityId: lifecycle.engine.authorityId, + }), + ) + .digest("hex"), + ); + }); + + it("keeps non-pulling endpoint authority stable across irrelevant PATH additions", () => { + const executableRoot = fakeDocker("qualified"); + const emptyRoot = fakeExecutableRoot(); + const first = createDockerOperationAuthority("sandbox-lifecycle", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: executableRoot, + }); + const second = createDockerOperationAuthority("sandbox-lifecycle", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: `${emptyRoot}${path.delimiter}${executableRoot}`, + }); + + expect(second.engine.authorityId).toBe(first.engine.authorityId); + }); + + it("binds the full delegated-command PATH for host-local inference pulls", () => { + const executableRoot = fakeDocker("qualified"); + const emptyRoot = fakeExecutableRoot(); + const first = createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: executableRoot, + }); + const second = createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: `${emptyRoot}${path.delimiter}${executableRoot}`, + }); + + expect(second.engine.authorityId).not.toBe(first.engine.authorityId); + }); + + it("fails closed when an earlier Docker credential helper appears", () => { + const executableRoot = fakeDocker("qualified"); + const prefixRoot = fakeExecutableRoot(); + const commandPath = `${prefixRoot}${path.delimiter}${executableRoot}`; + const authority = createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: commandPath, + }); + + writeFakeExecutable( + prefixRoot, + "docker-credential-registry+alternate", + "printf 'credential\\n'", + ); + const replacement = createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: commandPath, + }); + + expect(replacement.engine.authorityId).not.toBe(authority.engine.authorityId); + expect(() => authority.engine.capture(["version"])).toThrow( + "Docker operation delegated command set changed after qualification", + ); + }); + + it("binds and revalidates the effective SSH helper for SSH endpoints", () => { + const executableRoot = fakeDocker("qualified"); + writeFakeExecutable(executableRoot, "ssh", "printf 'first-ssh\\n'"); + const environment = { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "ssh://nvidia@spark.example.test", + PATH: executableRoot, + }; + const authority = createDockerOperationAuthority("host-local-inference", environment); + + writeFakeExecutable(executableRoot, "ssh", "printf 'second-ssh\\n'"); + const replacement = createDockerOperationAuthority("host-local-inference", environment); + + expect(replacement.engine.authorityId).not.toBe(authority.engine.authorityId); + expect(() => authority.engine.capture(["version"])).toThrow( + "Docker operation delegated command set changed after qualification", + ); + }); + + it("rejects relative PATH entries and env-based delegated interpreters", () => { + const executableRoot = fakeDocker("qualified"); + expect(() => + createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: `${executableRoot}${path.delimiter}relative-bin`, + }), + ).toThrow("PATH must contain only absolute directories"); + + fs.writeFileSync( + path.join(executableRoot, "docker-credential-registry"), + "#!/usr/bin/env sh\nprintf 'credential\\n'\n", + { mode: 0o700 }, + ); + expect(() => + createDockerOperationAuthority("host-local-inference", { + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + PATH: executableRoot, + }), + ).toThrow("cannot delegate through env"); + }); + + it("invokes one absolute qualified executable after process PATH drift", () => { + const first = fakeDocker("first"); + const second = fakeDocker("second"); + const authority = createDockerOperationAuthority("sandbox-lifecycle", { + PATH: first, + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + }); + vi.stubEnv("PATH", second); + + expect(authority.engine.capture(["version"]).stdout).toBe("first\n"); + }); + + it("streams through the same qualified executable after process PATH drift", async () => { + const first = fakeDocker("first-stream"); + const second = fakeDocker("second-stream"); + const authority = createDockerOperationAuthority("host-local-inference", { + PATH: first, + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + }); + vi.stubEnv("PATH", second); + const child = authority.spawn(["version"]); + const stdout: Buffer[] = []; + child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); + + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (status) => { + status === 0 ? resolve() : reject(new Error(`fake Docker exited ${String(status)}`)); + }); + }); + expect(Buffer.concat(stdout).toString("utf8")).toBe("first-stream\n"); + }); + + it("forwards an explicitly requested Hugging Face token and the bound SSH agent", async () => { + const executableRoot = fakeDockerScript( + `printf '%s\\n' "\${HF_TOKEN-unset}" "\${SSH_AUTH_SOCK-unset}" "\${PATH-unset}"`, + ); + writeFakeExecutable(executableRoot, "ssh", "printf 'ssh\\n'"); + const authority = createDockerOperationAuthority("host-local-inference", { + PATH: executableRoot, + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "ssh://nvidia@spark.example.test", + SSH_AUTH_SOCK: "/tmp/nemoclaw-ssh-agent.sock", + }); + const child = authority.spawn( + ["run", "-e", "HF_TOKEN", "example.invalid/downloader@sha256:deadbeef"], + { + env: { + HF_TOKEN: "hf_secret_value", + PATH: "/tmp/unqualified-path", + SSH_AUTH_SOCK: "/tmp/unqualified-ssh-agent.sock", + }, + }, + ); + const stdout: Buffer[] = []; + child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk)); + + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (status) => { + status === 0 ? resolve() : reject(new Error(`fake Docker exited ${String(status)}`)); + }); + }); + expect(Buffer.concat(stdout).toString("utf8")).toBe( + `hf_secret_value\n/tmp/nemoclaw-ssh-agent.sock\n${executableRoot}\n`, + ); + }); + + it("fails closed when the qualified executable identity changes", () => { + const executableRoot = fakeDocker("first"); + const authority = createDockerOperationAuthority("sandbox-lifecycle", { + PATH: executableRoot, + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + }); + fs.writeFileSync(path.join(executableRoot, "docker"), "#!/bin/sh\nprintf 'changed\\n'\n", { + mode: 0o700, + }); + + expect(() => authority.engine.capture(["version"])).toThrow( + "Docker operation executable changed after qualification", + ); + }); + + it("rejects plaintext remote TCP before issuing a daemon command", () => { + const capture = contextCapture("unix:///var/run/docker.sock"); + + expect(() => + createDockerOperationAuthority( + "sandbox-lifecycle", + { HOME: "/tmp/nemoclaw-home", DOCKER_HOST: "tcp://spark.example.test:2375" }, + capture, + ), + ).toThrow("requires verified TLS for remote Docker TCP endpoints"); + expect(capture).not.toHaveBeenCalled(); + }); + + it("fails closed before a daemon command when a qualified context endpoint drifts", () => { + const capture = createDriftingContextCapture(); + const authority = createDockerOperationAuthority( + "sandbox-lifecycle", + { HOME: "/tmp/nemoclaw-home", DOCKER_CONTEXT: "spark" }, + capture, + ); + + expect(() => authority.engine.capture(["info"])).toThrow( + "Docker context endpoint changed after qualification", + ); + expect(capture.mock.calls.some(([, args]) => args.at(-1) === "info")).toBe(false); + }); + + it("preserves the managed llama.cpp error and streamed-command boundary", () => { + const capture = contextCapture("ssh://nvidia@spark.example.test"); + const spawn = vi.fn(() => ({}) as never); + const authority = createDockerLlamaCppOperationAuthority( + { HOME: "/tmp/nemoclaw-home", DOCKER_CONTEXT: "spark" }, + capture, + spawn, + ); + + authority.spawn(["run", "example.invalid/downloader"]); + + expect(spawn).toHaveBeenCalledWith( + [ + "--config", + "/tmp/nemoclaw-home/.docker", + "--context", + "spark", + "run", + "example.invalid/downloader", + ], + undefined, + ); + expect(() => + createDockerLlamaCppOperationAuthority({ + HOME: "/tmp/nemoclaw-home", + DOCKER_HOST: "tcp://spark.example.test:2375", + }), + ).toThrow(/^Managed llama\.cpp requires verified TLS for remote Docker TCP endpoints\.$/u); + }); +}); diff --git a/src/lib/onboard/runtime-provider/docker-operation-authority.ts b/src/lib/onboard/runtime-provider/docker-operation-authority.ts new file mode 100644 index 00000000000..cc924ad74f4 --- /dev/null +++ b/src/lib/onboard/runtime-provider/docker-operation-authority.ts @@ -0,0 +1,698 @@ +// 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 { + type ContainerEngine, + type ContainerEngineCommandCapture, + type ContainerEngineOperationScope, + createContainerEngineCommand, +} from "../../adapters/container-engine"; + +interface DockerClientBinding { + readonly endpointArgs: readonly string[]; + readonly executable: string; + readonly executableIdentitySha256: string; + readonly commandEnvironmentSha256: string; + readonly commandEnvironment: Readonly; + readonly cwd: string; + readonly identity: string; + readonly guard?: () => void; +} + +interface DockerExecutableBinding { + readonly executable: string; + readonly selectedPath: string; + readonly identity: string; + readonly commandEnvironment: Readonly; + readonly cwd: string; + readonly guard: () => void; +} + +interface DockerDelegatedCommandBinding { + readonly identitySha256: string; + readonly guard: () => void; +} + +interface ResolvedDockerContextEndpoint { + readonly host: string; + readonly identity: string; +} + +export interface DockerOperationAuthority { + readonly assertAuthority: () => void; + readonly engine: ContainerEngine; + readonly spawn: ( + args: readonly string[], + options?: Parameters[2], + ) => ReturnType; +} + +const DOCKER_CONTEXT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,254}$/u; +const DOCKER_HOST_PATTERN = /^(?:npipe|ssh|tcp|unix):\/\/[^\s\u0000-\u001f\u007f]+$/u; +const DOCKER_CREDENTIAL_HELPER_PREFIX = "docker-credential-"; +const DOCKER_ARGUMENT_MAX_BYTES = 16 * 1024; +const DOCKER_CONTEXT_INSPECT_FORMAT = "{{json .}}"; +const EXECUTABLE_PREFIX_MAX_BYTES = 1024; +const EXECUTABLE_INTERPRETER_MAX_DEPTH = 4; +const bindings = new WeakMap(); +const DOCKER_COMMAND_ENV_NAMES = new Set([ + "HOME", + "USER", + "LOGNAME", + "SHELL", + "PATH", + "SSH_AUTH_SOCK", + "TERM", + "HOSTNAME", + "LANG", + "TMPDIR", + "TMP", + "TEMP", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "GIT_SSL_CAINFO", + "GIT_SSL_CAPATH", + "CURL_CA_BUNDLE", +]); +const DOCKER_COMMAND_ENV_PREFIXES = ["LC_", "XDG_"] as const; +const DOCKER_STREAMED_CREDENTIAL_ENV_NAMES = new Set(["HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"]); +const MAX_DOCKER_OUTPUT_BYTES = 1024 * 1024; +const MAX_DOCKER_ARGUMENTS = 512; + +function exactDockerValue(value: string | undefined, label: string): string | undefined { + if (value === undefined || value === "") return undefined; + if ( + value !== value.trim() || + Buffer.byteLength(value, "utf8") > DOCKER_ARGUMENT_MAX_BYTES || + /[\u0000-\u001f\u007f-\u009f]/u.test(value) + ) { + throw new Error(`Docker operation ${label} is invalid.`); + } + return value; +} + +function absoluteDockerPath(value: string, label: string): string { + const candidate = exactDockerValue(value, label); + if (!candidate) throw new Error(`Docker operation ${label} is invalid.`); + return path.resolve(candidate); +} + +function dockerConfigPath(env: NodeJS.ProcessEnv): string { + const configured = exactDockerValue(env.DOCKER_CONFIG, "DOCKER_CONFIG"); + if (configured) return path.resolve(configured); + const home = exactDockerValue(env.HOME, "HOME") ?? os.homedir(); + return path.join(path.resolve(home), ".docker"); +} + +function dockerTlsArgs(env: NodeJS.ProcessEnv): { + readonly args: readonly string[]; + readonly verify: boolean; +} { + const tls = exactDockerValue(env.DOCKER_TLS, "DOCKER_TLS") !== undefined; + const tlsVerify = exactDockerValue(env.DOCKER_TLS_VERIFY, "DOCKER_TLS_VERIFY") !== undefined; + const certPath = exactDockerValue(env.DOCKER_CERT_PATH, "DOCKER_CERT_PATH"); + const args: string[] = []; + if (tlsVerify) args.push("--tlsverify"); + else if (tls) args.push("--tls"); + if (certPath) { + const directory = absoluteDockerPath(certPath, "DOCKER_CERT_PATH"); + args.push( + "--tlscacert", + path.join(directory, "ca.pem"), + "--tlscert", + path.join(directory, "cert.pem"), + "--tlskey", + path.join(directory, "key.pem"), + ); + } + return Object.freeze({ args: Object.freeze(args), verify: tlsVerify }); +} + +function dockerContextName(value: string, label: string): string { + const context = exactDockerValue(value, label); + if (!context || !DOCKER_CONTEXT_PATTERN.test(context)) { + throw new Error(`Docker operation ${label} is invalid.`); + } + return context; +} + +function dockerHost(value: string): string { + const host = exactDockerValue(value, "DOCKER_HOST"); + if (!host || !DOCKER_HOST_PATTERN.test(host)) { + throw new Error("Docker operation DOCKER_HOST is invalid."); + } + return host; +} + +function requireSecureDockerEndpoint(host: string, tlsVerificationEnabled: boolean): void { + if (host.startsWith("tcp://") && !tlsVerificationEnabled) { + throw new Error("Docker operation requires verified TLS for remote Docker TCP endpoints."); + } +} + +function fixedDockerCommandEnvironment(env: NodeJS.ProcessEnv): Readonly { + const searchPath = exactDockerValue(env.PATH ?? process.env.PATH, "PATH"); + if (!searchPath) throw new Error("Docker operation PATH is unavailable."); + if (searchPath.split(path.delimiter).some((directory) => !path.isAbsolute(directory))) { + throw new Error("Docker operation PATH must contain only absolute directories."); + } + const source = { ...env, PATH: searchPath }; + const entries = Object.entries(source) + .filter( + ([name, value]) => + value !== undefined && + (DOCKER_COMMAND_ENV_NAMES.has(name) || + DOCKER_COMMAND_ENV_PREFIXES.some((prefix) => name.startsWith(prefix))), + ) + .sort(([left], [right]) => left.localeCompare(right)); + return Object.freeze(Object.fromEntries(entries)); +} + +function executableInterpreter(executable: string, status: fs.BigIntStats): string | undefined { + const descriptor = fs.openSync( + executable, + fs.constants.O_RDONLY | + (typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0), + ); + try { + const opened = fs.fstatSync(descriptor, { bigint: true }); + if (opened.dev !== status.dev || opened.ino !== status.ino) { + throw new Error("Docker operation executable changed while it was inspected."); + } + const prefix = Buffer.alloc(EXECUTABLE_PREFIX_MAX_BYTES); + const bytesRead = fs.readSync(descriptor, prefix, 0, prefix.length, 0); + if (bytesRead < 2 || prefix[0] !== 0x23 || prefix[1] !== 0x21) return undefined; + const newline = prefix.subarray(0, bytesRead).indexOf(0x0a, 2); + if (newline < 0) { + throw new Error("Docker operation executable interpreter line is invalid."); + } + const line = prefix.subarray(2, newline).toString("utf8").trim(); + const interpreter = line.split(/\s+/u)[0]; + if (!interpreter || !path.isAbsolute(interpreter)) { + throw new Error("Docker operation executable interpreter must be absolute."); + } + const resolved = fs.realpathSync(interpreter); + if (path.basename(interpreter) === "env" || path.basename(resolved) === "env") { + throw new Error("Docker operation executable cannot delegate through env."); + } + return interpreter; + } finally { + fs.closeSync(descriptor); + } +} + +function qualifiedExecutableMetadata( + selectedPath: string, + executable: string, + depth = 0, + ancestors: ReadonlySet = new Set(), +): Readonly> { + if (depth > EXECUTABLE_INTERPRETER_MAX_DEPTH || ancestors.has(executable)) { + throw new Error("Docker operation executable interpreter chain is invalid."); + } + const selected = fs.lstatSync(selectedPath, { bigint: true }); + const target = fs.statSync(executable, { bigint: true }); + if (!target.isFile()) throw new Error("Docker operation executable is not one regular file."); + fs.accessSync(executable, fs.constants.X_OK); + const interpreterPath = executableInterpreter(executable, target); + const interpreter = + interpreterPath === undefined + ? undefined + : qualifiedExecutableMetadata( + interpreterPath, + fs.realpathSync(interpreterPath), + depth + 1, + new Set([...ancestors, executable]), + ); + return Object.freeze({ + selectedPath, + executable, + selectedDev: selected.dev.toString(), + selectedIno: selected.ino.toString(), + selectedMode: selected.mode.toString(), + selectedSize: selected.size.toString(), + selectedMtimeNs: selected.mtimeNs.toString(), + selectedCtimeNs: selected.ctimeNs.toString(), + targetDev: target.dev.toString(), + targetIno: target.ino.toString(), + targetMode: target.mode.toString(), + targetUid: target.uid.toString(), + targetGid: target.gid.toString(), + targetSize: target.size.toString(), + targetMtimeNs: target.mtimeNs.toString(), + targetCtimeNs: target.ctimeNs.toString(), + ...(interpreter === undefined ? {} : { interpreter }), + }); +} + +function dockerExecutableMetadata(selectedPath: string, executable: string): string { + return JSON.stringify(qualifiedExecutableMetadata(selectedPath, executable)); +} + +function executableCandidate(candidate: string): boolean { + try { + fs.accessSync(candidate, fs.constants.X_OK); + return true; + } catch { + return false; + } +} + +function dockerDelegatedCommandSnapshot(searchPath: string, requireSsh: boolean): string { + const selected = new Map(); + for (const directory of searchPath.split(path.delimiter)) { + if (requireSsh && !selected.has("ssh")) { + const candidate = path.join(directory, "ssh"); + if (executableCandidate(candidate)) selected.set("ssh", candidate); + } + let names: readonly string[]; + try { + names = fs.readdirSync(directory).sort((left, right) => left.localeCompare(right)); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") continue; + throw new Error("Docker operation could not inspect its delegated command path."); + } + for (const name of names) { + if ( + !name.startsWith(DOCKER_CREDENTIAL_HELPER_PREFIX) || + name.length === DOCKER_CREDENTIAL_HELPER_PREFIX.length || + selected.has(name) + ) { + continue; + } + const candidate = path.join(directory, name); + if (executableCandidate(candidate)) selected.set(name, candidate); + } + } + if (requireSsh && !selected.has("ssh")) { + throw new Error("Docker operation could not resolve one absolute SSH executable."); + } + return JSON.stringify( + [...selected.entries()] + .sort(([left], [right]) => left.localeCompare(right)) + .map(([name, selectedPath]) => ({ + name, + metadata: qualifiedExecutableMetadata(selectedPath, fs.realpathSync(selectedPath)), + })), + ); +} + +function qualifyDockerDelegatedCommands( + commandEnvironment: Readonly, + endpointHost: string, +): DockerDelegatedCommandBinding { + const searchPath = commandEnvironment.PATH as string; + const requireSsh = endpointHost.startsWith("ssh://"); + const snapshot = dockerDelegatedCommandSnapshot(searchPath, requireSsh); + return Object.freeze({ + identitySha256: createHash("sha256").update(snapshot).digest("hex"), + guard: () => { + let current: string; + try { + current = dockerDelegatedCommandSnapshot(searchPath, requireSsh); + } catch { + throw new Error("Docker operation delegated command set changed after qualification."); + } + if (current !== snapshot) { + throw new Error("Docker operation delegated command set changed after qualification."); + } + }, + }); +} + +function dockerCommandEnvironmentSha256( + operation: ContainerEngineOperationScope, + commandEnvironment: Readonly, + endpointHost: string, + delegatedCommands: DockerDelegatedCommandBinding, +): string { + const authorityEnvironment = Object.fromEntries( + Object.entries(commandEnvironment).filter(([name]) => name !== "PATH"), + ); + return createHash("sha256") + .update( + JSON.stringify({ + authorityEnvironment, + delegatedCommandsSha256: delegatedCommands.identitySha256, + ...(operation === "host-local-inference" || endpointHost.startsWith("ssh://") + ? { delegatedCommandSearchPath: commandEnvironment.PATH } + : {}), + }), + ) + .digest("hex"); +} + +function qualifyDockerExecutable(env: NodeJS.ProcessEnv): DockerExecutableBinding { + const commandEnvironment = fixedDockerCommandEnvironment(env); + const searchPath = commandEnvironment.PATH as string; + let selectedPath: string | null = null; + for (const directory of searchPath.split(path.delimiter)) { + if (!directory || !path.isAbsolute(directory)) continue; + const candidate = path.join(directory, "docker"); + try { + fs.accessSync(candidate, fs.constants.X_OK); + selectedPath = candidate; + break; + } catch { + // Continue through the fixed absolute search path. + } + } + if (selectedPath === null) { + throw new Error("Docker operation could not resolve one absolute Docker executable."); + } + const executable = fs.realpathSync(selectedPath); + const metadata = dockerExecutableMetadata(selectedPath, executable); + const identity = createHash("sha256").update(metadata).digest("hex"); + const cwd = path.dirname(executable); + return Object.freeze({ + executable, + selectedPath, + identity, + commandEnvironment, + cwd, + guard: () => { + let currentExecutable: string; + let currentMetadata: string; + try { + currentExecutable = fs.realpathSync(selectedPath as string); + currentMetadata = dockerExecutableMetadata(selectedPath as string, currentExecutable); + } catch { + throw new Error("Docker operation executable changed after qualification."); + } + if (currentExecutable !== executable || currentMetadata !== metadata) { + throw new Error("Docker operation executable changed after qualification."); + } + }, + }); +} + +function fixedDockerCapture(executable: DockerExecutableBinding): ContainerEngineCommandCapture { + return (_executable, args, timeoutMs, input) => { + const result = spawnSync(executable.executable, [...args], { + cwd: executable.cwd, + env: { ...executable.commandEnvironment }, + encoding: "utf8", + maxBuffer: MAX_DOCKER_OUTPUT_BYTES, + shell: false, + stdio: [input ? "pipe" : "ignore", "pipe", "pipe"], + ...(input ? { input } : {}), + timeout: timeoutMs, + }); + return { + status: result.status ?? (result.error || result.signal ? 1 : 0), + stdout: String(result.stdout || ""), + stderr: String(result.stderr || ""), + ...(result.error ? { error: result.error } : {}), + }; + }; +} + +function fixedDockerSpawnArguments(args: readonly string[]): readonly string[] { + if (!Array.isArray(args) || args.length > MAX_DOCKER_ARGUMENTS) { + throw new Error("Docker operation has too many command arguments."); + } + return Object.freeze( + args.map((value, index) => { + if ( + typeof value !== "string" || + value.includes("\0") || + Buffer.byteLength(value, "utf8") > DOCKER_ARGUMENT_MAX_BYTES + ) { + throw new Error(`Docker operation command argument ${String(index)} is invalid.`); + } + return value; + }), + ); +} + +function fixedDockerSpawnEnvironment( + args: readonly string[], + commandEnvironment: Readonly, + callerEnvironment: NodeJS.ProcessEnv | undefined, +): NodeJS.ProcessEnv { + const environment = { ...commandEnvironment }; + for (let index = 0; index < args.length - 1; index += 1) { + if (args[index] !== "-e" && args[index] !== "--env") continue; + const name = args[index + 1]; + if (!name || !DOCKER_STREAMED_CREDENTIAL_ENV_NAMES.has(name)) continue; + const value = callerEnvironment?.[name]; + if (value !== undefined) environment[name] = value; + } + return environment; +} + +function dockerBindingProbe( + operation: ContainerEngineOperationScope, + endpointArgs: readonly string[], + executable: DockerExecutableBinding, + capture: ContainerEngineCommandCapture, +): ContainerEngine { + return createContainerEngineCommand({ + operation, + engineId: "docker", + displayName: "Docker", + authorityId: "docker:qualification", + executable: executable.executable, + endpointArgs, + capture, + guard: executable.guard, + }); +} + +function requireDockerProbeOutput( + result: ReturnType, + label: string, +): string { + if (result.error || result.status !== 0) { + throw new Error(`Docker operation could not ${label}.`); + } + const output = result.stdout.trim(); + if (!output) throw new Error(`Docker operation could not ${label}.`); + return output; +} + +function resolvedDockerContextEndpoint( + probe: ContainerEngine, + context: string, +): ResolvedDockerContextEndpoint { + const output = requireDockerProbeOutput( + probe.capture(["context", "inspect", context, "--format", DOCKER_CONTEXT_INSPECT_FORMAT]), + "qualify the Docker context endpoint", + ); + let endpoint: unknown; + try { + endpoint = JSON.parse(output); + } catch { + throw new Error("Docker operation Docker context endpoint is unreadable."); + } + if (typeof endpoint !== "object" || endpoint === null) { + throw new Error("Docker operation Docker context endpoint is invalid."); + } + const inspection = endpoint as { + Endpoints?: { docker?: { Host?: unknown; SkipTLSVerify?: unknown } }; + TLSMaterial?: { docker?: unknown }; + }; + const dockerEndpoint = inspection.Endpoints?.docker; + if ( + typeof dockerEndpoint?.Host !== "string" || + typeof dockerEndpoint.SkipTLSVerify !== "boolean" + ) { + throw new Error("Docker operation Docker context endpoint is invalid."); + } + const host = dockerHost(dockerEndpoint.Host); + const tlsMaterial = inspection.TLSMaterial?.docker ?? []; + if ( + !Array.isArray(tlsMaterial) || + tlsMaterial.some((entry) => typeof entry !== "string" || !/^[A-Za-z0-9._-]+$/u.test(entry)) + ) { + throw new Error("Docker operation Docker context TLS material is invalid."); + } + const tlsFiles = [...tlsMaterial].sort(); + requireSecureDockerEndpoint(host, !dockerEndpoint.SkipTLSVerify && tlsFiles.includes("ca.pem")); + return Object.freeze({ + host, + identity: JSON.stringify({ + host, + skipTlsVerify: dockerEndpoint.SkipTLSVerify, + tlsMaterial: tlsFiles, + }), + }); +} + +function qualifiedDockerClientBinding( + operation: ContainerEngineOperationScope, + endpointArgs: readonly string[], + endpointHost: string, + endpointIdentity: string, + executable: DockerExecutableBinding, + endpointGuard?: () => void, +): DockerClientBinding { + const delegatedCommands = qualifyDockerDelegatedCommands( + executable.commandEnvironment, + endpointHost, + ); + const commandEnvironmentSha256 = dockerCommandEnvironmentSha256( + operation, + executable.commandEnvironment, + endpointHost, + delegatedCommands, + ); + const identity = createHash("sha256") + .update( + JSON.stringify({ + endpointArgs, + endpointIdentity, + executableIdentitySha256: executable.identity, + commandEnvironmentSha256, + cwd: executable.cwd, + }), + ) + .digest("hex"); + return Object.freeze({ + endpointArgs, + executable: executable.executable, + executableIdentitySha256: executable.identity, + commandEnvironmentSha256, + commandEnvironment: executable.commandEnvironment, + cwd: executable.cwd, + identity, + guard: () => { + executable.guard(); + delegatedCommands.guard(); + endpointGuard?.(); + }, + }); +} + +function dockerClientBinding( + operation: ContainerEngineOperationScope, + env: NodeJS.ProcessEnv, + executable: DockerExecutableBinding, + capture: ContainerEngineCommandCapture, +): DockerClientBinding { + const configArgs = ["--config", dockerConfigPath(env)] as const; + const tls = dockerTlsArgs(env); + const explicitContext = exactDockerValue(env.DOCKER_CONTEXT, "DOCKER_CONTEXT"); + const explicitHost = exactDockerValue(env.DOCKER_HOST, "DOCKER_HOST"); + if (!explicitContext && explicitHost) { + const host = dockerHost(explicitHost); + requireSecureDockerEndpoint(host, tls.verify); + const endpointArgs = Object.freeze([...configArgs, "--host", host, ...tls.args]); + return qualifiedDockerClientBinding(operation, endpointArgs, host, host, executable); + } + + let context: string; + if (explicitContext) { + context = dockerContextName(explicitContext, "DOCKER_CONTEXT"); + } else { + const selectorProbe = dockerBindingProbe( + operation, + [...configArgs, ...tls.args], + executable, + capture, + ); + context = dockerContextName( + requireDockerProbeOutput( + selectorProbe.capture(["context", "show"]), + "resolve the Docker context", + ), + "current Docker context", + ); + } + const endpointArgs = Object.freeze([...configArgs, "--context", context, ...tls.args]); + const endpointProbe = dockerBindingProbe(operation, endpointArgs, executable, capture); + const qualifiedEndpoint = resolvedDockerContextEndpoint(endpointProbe, context); + return qualifiedDockerClientBinding( + operation, + endpointArgs, + qualifiedEndpoint.host, + qualifiedEndpoint.identity, + executable, + () => { + if ( + resolvedDockerContextEndpoint(endpointProbe, context).identity !== + qualifiedEndpoint.identity + ) { + throw new Error( + "Docker context endpoint changed after qualification; retry the operation.", + ); + } + }, + ); +} + +/** Bind one container-engine operation to fixed, qualified Docker client endpoint arguments. */ +export function createDockerOperationAuthority( + operation: ContainerEngineOperationScope, + env: NodeJS.ProcessEnv = process.env, + capture?: ContainerEngineCommandCapture, +): DockerOperationAuthority { + const executable = qualifyDockerExecutable(env); + const commandCapture = capture ?? fixedDockerCapture(executable); + const binding = dockerClientBinding(operation, env, executable, commandCapture); + const assertAuthority = () => binding.guard?.(); + const engine = createContainerEngineCommand({ + operation, + engineId: "docker", + displayName: "Docker", + authorityId: `docker:${binding.identity}`, + executable: binding.executable, + endpointArgs: binding.endpointArgs, + capture: commandCapture, + ...(binding.guard ? { guard: binding.guard } : {}), + }); + const authority = Object.freeze({ + assertAuthority, + engine, + spawn: (args: readonly string[], options?: Parameters[2]) => { + assertAuthority(); + const normalized = fixedDockerSpawnArguments(args); + return spawn(binding.executable, [...binding.endpointArgs, ...normalized], { + ...options, + cwd: binding.cwd, + env: fixedDockerSpawnEnvironment(normalized, binding.commandEnvironment, options?.env), + shell: false, + }); + }, + }); + bindings.set(authority, binding); + return authority; +} + +/** Prefix streamed Docker commands with the endpoint owned by this qualified authority. */ +export function dockerOperationCommandArguments( + authority: DockerOperationAuthority, + args: readonly string[], +): readonly string[] { + const binding = bindings.get(authority); + if (!binding) { + throw new Error("Docker operation authority does not own this command binding."); + } + return Object.freeze([...binding.endpointArgs, ...args]); +} + +/** Stable digest for the executable and exact endpoint authority of one Docker operation. */ +export function dockerOperationBindingSha256(engine: ContainerEngine): string { + return createHash("sha256") + .update( + JSON.stringify({ + operation: engine.operation, + engineId: engine.engineId, + authorityId: engine.authorityId, + }), + ) + .digest("hex"); +} diff --git a/src/lib/onboard/runtime-provider/docker-state-mutation.test.ts b/src/lib/onboard/runtime-provider/docker-state-mutation.test.ts new file mode 100644 index 00000000000..37d70fcc924 --- /dev/null +++ b/src/lib/onboard/runtime-provider/docker-state-mutation.test.ts @@ -0,0 +1,757 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + cleanupDockerStateMutationRoots, + createAmbiguousRuntimeCapture, + createOneTimeAcquireMountDrift, + createDockerStateMutationHarness as harness, + DOCKER_STATE_MUTATION_LIFECYCLE_GENERATION as LIFECYCLE_GENERATION, + DOCKER_STATE_MUTATION_PROJECTION_SHA256 as PROJECTION_SHA256, + persistedDockerStateMutationIntentPath as persistedIntentPath, + persistedDockerStateMutationRuntimeClaimPath as persistedRuntimeClaimPath, + dockerStateMutationPlan as plan, + DOCKER_STATE_MUTATION_RUNTIME_ID as RUNTIME_ID, + DOCKER_STATE_MUTATION_SANDBOX_FINGERPRINT as SANDBOX_FINGERPRINT, + DOCKER_STATE_MUTATION_STATE_ROOT as STATE_ROOT, + throwBeforeClaimUnlink, +} from "../../../../test/helpers/docker-state-mutation-harness"; +import { createDockerOperationAuthority } from "./docker-operation-authority"; +import { + createDockerStateMutationOwner, + createDockerStateMutationSurface, +} from "./docker-state-mutation"; + +function ownerThatStopsAfterPrepare(runtime: ReturnType) { + const acquireMutationExecution = vi.fn(() => { + throw new Error("injected controller exit before helper invocation"); + }); + return { + acquireMutationExecution, + owner: createDockerStateMutationOwner({ + sandboxName: runtime.context.sandboxName, + lifecycleGeneration: runtime.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: SANDBOX_FINGERPRINT, + runtimeId: RUNTIME_ID, + authority: runtime.authority, + engineAuthorityStore: runtime.engineAuthorityStore, + lifecycleStore: { + ...runtime.lifecycleStore, + acquireMutationExecution, + }, + }), + }; +} + +afterEach(() => { + cleanupDockerStateMutationRoots(); +}); + +describe("Docker runtime-provider state mutation surface", () => { + it("resolves one full labeled runtime and records authority only on synchronous acquire", () => { + const runtime = harness(); + const surface = createDockerStateMutationSurface({ + capture: runtime.capture, + resolveStateDir: () => runtime.root, + }); + + expect(runtime.engineAuthorityStore.load("sandbox-lifecycle")).toBeNull(); + const fence = surface.acquire({ ...runtime.context, plan: plan() }); + + expect(fence.runtimeId).toBe(RUNTIME_ID); + expect(fence).not.toBeInstanceOf(Promise); + expect(runtime.engineAuthorityStore.load("sandbox-lifecycle")).toMatchObject({ + providerId: "docker", + operation: "sandbox-lifecycle", + engineId: "docker", + }); + expect(runtime.capture.mock.calls[0]?.[1]).toEqual([ + "--config", + "/tmp/nemoclaw-docker", + "--host", + "unix:///tmp/nemoclaw-docker.sock", + "ps", + "-a", + "--no-trunc", + "--filter", + "label=openshell.ai/managed-by=openshell", + "--filter", + "label=openshell.ai/sandbox-name=alpha", + "--format", + "{{.ID}}", + ]); + }); + + it("returns null before first acquire without Docker or engine-authority access", () => { + const runtime = harness(); + const exclusionCalls: Array = []; + const exclusion = (sandbox: string, operation: string, run: () => T): T => { + exclusionCalls.push([sandbox, operation]); + return run(); + }; + const surface = createDockerStateMutationSurface({ + capture: runtime.capture, + resolveStateDir: () => runtime.root, + withDirectSandboxExecutionExclusion: exclusion, + }); + + expect(surface.recover(runtime.context)).toBeNull(); + expect(runtime.engineAuthorityStore.load("sandbox-lifecycle")).toBeNull(); + expect(runtime.capture).not.toHaveBeenCalled(); + expect(exclusionCalls).toEqual([["alpha", "Docker runtime-provider state mutation recovery"]]); + }); + + it("preserves the isolated Vitest state root from the operation environment", () => { + const runtime = harness(); + const surface = createDockerStateMutationSurface({ capture: runtime.capture }); + const context = { + ...runtime.context, + environment: { + ...runtime.context.environment, + VITEST: "true", + NEMOCLAW_TEST_BASE_HOME: runtime.context.environment.HOME, + NEMOCLAW_TEST_STATE_DIR: runtime.root, + }, + }; + + surface.acquire({ ...context, plan: plan() }); + + expect(runtime.engineAuthorityStore.load("sandbox-lifecycle")).toMatchObject({ + providerId: "docker", + operation: "sandbox-lifecycle", + }); + }); + + it("rejects a second same-sandbox mutation before another runtime lookup", () => { + const runtime = harness(); + const exclusionCalls: Array = []; + const exclusion = (sandbox: string, operation: string, run: () => T): T => { + exclusionCalls.push([sandbox, operation]); + return run(); + }; + const surface = createDockerStateMutationSurface({ + capture: runtime.capture, + resolveStateDir: () => runtime.root, + withDirectSandboxExecutionExclusion: exclusion, + }); + surface.acquire({ ...runtime.context, plan: plan() }); + const callsBeforeCompetingAcquire = runtime.capture.mock.calls.length; + + expect(() => surface.acquire({ ...runtime.context, plan: plan() })).toThrow( + "already has one unfinished state mutation", + ); + expect(runtime.capture).toHaveBeenCalledTimes(callsBeforeCompetingAcquire); + expect(exclusionCalls).toEqual([ + ["alpha", "Docker runtime-provider state mutation acquire"], + ["alpha", "Docker runtime-provider state mutation acquire"], + ]); + }); + + it("proves a repeated successful release from its tombstone without Docker access", () => { + const runtime = harness(); + const surface = createDockerStateMutationSurface({ + capture: runtime.capture, + resolveStateDir: () => runtime.root, + }); + const fence = surface.acquire({ ...runtime.context, plan: plan() }); + surface.rollback(runtime.context, fence); + const proof = surface.activate(runtime.context, fence); + const completedLedgerSha256 = "e".repeat(64); + surface.release(runtime.context, fence, proof, completedLedgerSha256); + const callsAfterRelease = runtime.capture.mock.calls.length; + + runtime.capture.mockImplementation(() => ({ + status: 1, + stdout: "", + stderr: "Docker is unavailable", + })); + expect(() => + surface.release(runtime.context, fence, proof, completedLedgerSha256), + ).not.toThrow(); + expect(runtime.capture).toHaveBeenCalledTimes(callsAfterRelease); + }); + + it("requires preexisting persisted authority before resolving a later-phase runtime", () => { + const runtime = harness(); + const surface = createDockerStateMutationSurface({ + capture: runtime.capture, + resolveStateDir: () => runtime.root, + }); + + expect(() => surface.assertFenced(runtime.context, null as never)).toThrow( + "persisted sandbox-lifecycle engine authority is missing", + ); + expect(runtime.capture).not.toHaveBeenCalled(); + }); + + it("rejects ambiguous labeled runtime resolution before recording authority", () => { + const runtime = harness(); + const ambiguous = createAmbiguousRuntimeCapture(runtime); + const surface = createDockerStateMutationSurface({ + capture: ambiguous, + resolveStateDir: () => runtime.root, + }); + + expect(() => surface.acquire({ ...runtime.context, plan: plan() })).toThrow( + "requires one exact full container identity", + ); + expect(runtime.engineAuthorityStore.load("sandbox-lifecycle")).toBeNull(); + expect(runtime.helperActions).toEqual([]); + }); +}); + +describe("Docker state mutation owner", () => { + it("uses the exact shared lifecycle-generation wire grammar", () => { + const plus = harness({ lifecycleGeneration: "generation+7" }); + expect(plus.owner.acquire({ ...plus.context, plan: plan() })).toMatchObject({ + lifecycleGeneration: "generation+7", + }); + + expect(() => harness({ lifecycleGeneration: ":generation" })).toThrow( + "lifecycle generation is malformed", + ); + }); + + it("keeps the exact Docker fence active through rollback, activation, and release", async () => { + const runtime = harness(); + + const fence = await runtime.owner.acquire({ ...runtime.context, plan: plan() }); + + expect(fence).toMatchObject({ + intent: "protection-transition", + phase: "fenced", + providerId: "docker", + sandboxName: "alpha", + transactionId: expect.stringMatching(/^[a-f0-9]{64}$/u), + lifecycleGeneration: LIFECYCLE_GENERATION, + runtimeId: RUNTIME_ID, + runtimeStateSha256: expect.stringMatching(/^[a-f0-9]{64}$/u), + engineBindingSha256: expect.stringMatching(/^[a-f0-9]{64}$/u), + stateRoot: STATE_ROOT, + mountNamespaceId: "mnt:[4026533007]", + stateRootDevice: "2050", + stateRootInode: "94212", + projectionSha256: PROJECTION_SHA256, + target: "mutable", + rollback: "locked", + nonce: expect.stringMatching(/^[a-f0-9]{64}$/u), + providerHandle: expect.stringMatching(/^docker-state-mutation-v1:/u), + }); + expect(runtime.lifecycleStore.listUnfinished()).toHaveLength(1); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + + await runtime.owner.assertFenced(runtime.context, fence); + await runtime.owner.rollback(runtime.context, fence); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + const proof = await runtime.owner.activate(runtime.context, fence); + expect(proof).toMatchObject({ + providerId: "docker", + nonce: fence.nonce, + configurationGeneration: "config-generation-8", + listenerIdentity: "tcp:18789", + healthSha256: "c".repeat(64), + providerHandle: expect.stringMatching(/^docker-state-mutation-activation-v1:/u), + }); + await runtime.owner.release(runtime.context, fence, proof, "e".repeat(64)); + + expect(runtime.helperActions).toEqual([ + "acquire", + "assert", + "rollback", + "activate", + "activate", + "release", + ]); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + const helperCalls = runtime.capture.mock.calls.filter(([, args]) => + args.includes("/usr/local/lib/nemoclaw/runtime-state-mutation-control.py"), + ); + expect(helperCalls.map(([, args]) => args.slice(-10))).toEqual([ + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "acquire", + ], + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "assert", + ], + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "rollback", + ], + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "activate", + ], + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "activate", + ], + [ + "container", + "exec", + "--interactive", + "--user", + "root", + RUNTIME_ID, + "/opt/hermes/.venv/bin/python3", + "-I", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "release", + ], + ]); + expect(helperCalls.map(([, args, timeout]) => [args.at(-1), timeout])).toEqual([ + ["acquire", 30_000], + ["assert", 30_000], + ["rollback", 15 * 60_000], + ["activate", 5 * 60_000], + ["activate", 5 * 60_000], + ["release", 5 * 60_000], + ]); + const acquireRequest = JSON.parse(helperCalls[0]?.[3]?.toString("utf8") ?? "null"); + expect(acquireRequest).toMatchObject({ + action: "acquire", + providerId: "docker", + sandboxName: "alpha", + lifecycleGeneration: LIFECYCLE_GENERATION, + runtimeId: RUNTIME_ID, + runtimePid: 4812, + stateRoot: STATE_ROOT, + planSha256: fence.planSha256, + projectionSha256: PROJECTION_SHA256, + nonce: fence.nonce, + target: "mutable", + rollback: "locked", + }); + expect(JSON.parse(acquireRequest.plan)).toMatchObject({ + intent: "protection-transition", + stateRoot: STATE_ROOT, + }); + const inspectFormats = runtime.capture.mock.calls + .filter( + ([, args]) => args[4] === "container" && args[5] === "inspect" && args[8] === RUNTIME_ID, + ) + .map(([, args]) => args[7]); + expect(inspectFormats.length).toBeGreaterThan(0); + expect(inspectFormats).not.toContain("{{json .}}"); + expect(inspectFormats.every((format) => !format.includes("Config.Env"))).toBe(true); + }); + + it("publishes without retiring the host lifecycle fence", async () => { + const runtime = harness(); + const fence = await runtime.owner.acquire({ ...runtime.context, plan: plan() }); + + await runtime.owner.publish(runtime.context, fence); + + const recovered = await runtime.owner.recover(runtime.context); + + expect(recovered).toMatchObject({ + intent: "protection-transition", + phase: "published", + target: "mutable", + rollback: "locked", + }); + expect(runtime.helperActions).toEqual(["acquire", "publish", "recover"]); + expect(runtime.capture.mock.calls.find(([, args]) => args.at(-1) === "publish")?.[2]).toBe( + 15 * 60_000, + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("recovers release from exact durable completion and keeps final release idempotent", async () => { + const runtime = harness({ failReleaseOnce: true }); + const fence = await runtime.owner.acquire({ ...runtime.context, plan: plan() }); + await runtime.owner.rollback(runtime.context, fence); + const proof = await runtime.owner.activate(runtime.context, fence); + const completedLedgerSha256 = "e".repeat(64); + + expect(() => + runtime.owner.release(runtime.context, fence, proof, completedLedgerSha256), + ).toThrow("root helper release did not complete successfully"); + expect(runtime.lifecycleStore.listUnfinished()[0]).toMatchObject({ + phase: "completed", + resultSha256: completedLedgerSha256, + }); + + expect(runtime.owner.recover(runtime.context)).toBeNull(); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + const actionsAfterRecovery = [...runtime.helperActions]; + + await runtime.owner.release(runtime.context, fence, proof, completedLedgerSha256); + expect(runtime.helperActions).toEqual(actionsAfterRecovery); + }); + + it("recovers a successful provider release whose response was lost", async () => { + const runtime = harness({ loseReleaseResponseOnce: true }); + const fence = await runtime.owner.acquire({ ...runtime.context, plan: plan() }); + await runtime.owner.rollback(runtime.context, fence); + const proof = await runtime.owner.activate(runtime.context, fence); + const completedLedgerSha256 = "e".repeat(64); + + expect(() => + runtime.owner.release(runtime.context, fence, proof, completedLedgerSha256), + ).toThrow("root helper release did not complete successfully"); + expect(runtime.lifecycleStore.listUnfinished()[0]).toMatchObject({ + phase: "completed", + resultSha256: completedLedgerSha256, + }); + + expect(runtime.owner.recover(runtime.context)).toBeNull(); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + expect(runtime.helperActions.slice(-3)).toEqual(["release", "recover", "release"]); + }); + + it("recovers a durable provider-release receipt without requiring the removed marker", () => { + const runtime = harness(); + const fence = runtime.owner.acquire({ ...runtime.context, plan: plan() }); + runtime.owner.rollback(runtime.context, fence); + const proof = runtime.owner.activate(runtime.context, fence); + const completedLedgerSha256 = "e".repeat(64); + const claimPath = persistedRuntimeClaimPath(runtime.root); + const originalUnlink = fs.unlinkSync.bind(fs); + const unlink = vi + .spyOn(fs, "unlinkSync") + .mockImplementation((target) => throwBeforeClaimUnlink(originalUnlink, claimPath, target)); + + expect(() => + runtime.owner.release(runtime.context, fence, proof, completedLedgerSha256), + ).toThrow("before claim unlink"); + unlink.mockRestore(); + const actionsAfterProviderRelease = [...runtime.helperActions]; + + expect(runtime.owner.recover(runtime.context)).toBeNull(); + expect(runtime.helperActions).toEqual(actionsAfterProviderRelease); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + expect(runtime.lifecycleStore.isRetired(fence.transactionId, completedLedgerSha256)).toBe(true); + }); + + it("converges when the first helper acquire wins before ledger publication", async () => { + const runtime = harness({ + afterHelper: createOneTimeAcquireMountDrift(), + }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "Docker runtime changed while the state mutation fence was established", + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + + runtime.state.mountSource = "/var/lib/openshell/alpha/hermes"; + const recovered = await runtime.owner.recover(runtime.context); + + expect(recovered?.providerHandle).toMatch(/^docker-state-mutation-v1:/u); + expect(runtime.helperActions).toEqual(["acquire", "acquire"]); + expect(runtime.acquireRequests[1]).toBe(runtime.acquireRequests[0]); + expect(runtime.capture.mock.calls.filter(([, args]) => args.at(-1) === "acquire")[1]?.[2]).toBe( + 30_000, + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("replays the persisted acquire after a controller exit before helper invocation", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + const prepared = runtime.lifecycleStore.listUnfinished()[0]; + expect(prepared).toMatchObject({ action: "state-mutation", phase: "prepared" }); + expect( + runtime.lifecycleStore.loadStateMutationIntent(prepared?.transactionId as string), + ).toMatchObject({ + transactionId: prepared?.transactionId, + planSha256: plan().planSha256, + projectionSha256: plan().projectionSha256, + }); + expect(runtime.helperActions).toEqual([]); + + const recovered = runtime.owner.recover(runtime.context); + + expect(recovered).toMatchObject({ + transactionId: prepared?.transactionId, + phase: "fenced", + }); + expect(runtime.helperActions).toEqual(["acquire"]); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("replays the persisted acquire from mutation-authorized recovery", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + const transactionId = runtime.lifecycleStore.listUnfinished()[0]?.transactionId as string; + runtime.lifecycleStore.authorizeMutation(transactionId); + + const recovered = runtime.owner.recover(runtime.context); + + expect(recovered).toMatchObject({ transactionId, phase: "fenced" }); + expect(runtime.helperActions).toEqual(["acquire"]); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("converges when an orphan acquire writes its marker before recovery", () => { + const runtime = harness({ loseAcquireResponseOnce: true }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "root helper acquire did not complete successfully", + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + + const recovered = runtime.owner.recover(runtime.context); + + expect(recovered?.providerHandle).toMatch(/^docker-state-mutation-v1:/u); + expect(runtime.helperActions).toEqual(["acquire", "acquire"]); + expect(runtime.acquireRequests[1]).toBe(runtime.acquireRequests[0]); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("converges when recovery writes the marker before a delayed orphan acquire", () => { + const runtime = harness({ deferAcquireOnce: true }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "root helper acquire did not complete successfully", + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + + const recovered = runtime.owner.recover(runtime.context); + const orphanReceipt = runtime.replayDeferredAcquire(); + + expect(orphanReceipt).toMatchObject({ + transactionId: recovered?.transactionId, + nonce: recovered?.nonce, + phase: "fenced", + }); + expect(runtime.helperActions).toEqual(["acquire", "acquire", "acquire"]); + expect(new Set(runtime.acquireRequests).size).toBe(1); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("fails closed when a prepared transaction loses its persisted acquire intent", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + const transactionId = runtime.lifecycleStore.listUnfinished()[0]?.transactionId as string; + fs.unlinkSync(persistedIntentPath(runtime.root, transactionId)); + + expect(() => runtime.owner.recover(runtime.context)).toThrow( + "prepared state mutation is missing its exact intent", + ); + expect(runtime.helperActions).toEqual([]); + }); + + it("fails closed when a persisted acquire intent changes", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + const transactionId = runtime.lifecycleStore.listUnfinished()[0]?.transactionId as string; + const intentPath = persistedIntentPath(runtime.root, transactionId); + const intent = JSON.parse(fs.readFileSync(intentPath, "utf8")) as Record; + fs.writeFileSync(intentPath, `${JSON.stringify({ ...intent, nonce: "f".repeat(64) })}\n`, { + mode: 0o600, + }); + + expect(() => runtime.owner.recover(runtime.context)).toThrow( + "persisted state mutation intent does not match the lifecycle transaction", + ); + expect(runtime.helperActions).toEqual([]); + }); + + it("fails closed before helper replay when the Docker runtime changes", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + runtime.state.mountSource = "/var/lib/openshell/replaced/hermes"; + + expect(() => runtime.owner.recover(runtime.context)).toThrow( + "Docker runtime changed before the state mutation fence was established", + ); + expect(runtime.helperActions).toEqual([]); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + }); + + it("fails closed before Docker inspection when engine authority changes", () => { + const runtime = harness(); + const interrupted = ownerThatStopsAfterPrepare(runtime); + expect(() => interrupted.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "controller exit before helper invocation", + ); + const captureCallsBeforeRecovery = runtime.capture.mock.calls.length; + const changedAuthority = createDockerOperationAuthority( + "sandbox-lifecycle", + { + ...runtime.context.environment, + DOCKER_HOST: "unix:///tmp/changed-docker.sock", + }, + runtime.capture, + ); + const changedOwner = createDockerStateMutationOwner({ + sandboxName: runtime.context.sandboxName, + lifecycleGeneration: runtime.lifecycleGeneration, + lifecycleLiveIdentityFingerprint: SANDBOX_FINGERPRINT, + runtimeId: RUNTIME_ID, + authority: changedAuthority, + engineAuthorityStore: runtime.engineAuthorityStore, + lifecycleStore: runtime.lifecycleStore, + }); + + expect(() => changedOwner.recover(runtime.context)).toThrow( + /binding does not match|endpoint does not match/u, + ); + expect(runtime.capture).toHaveBeenCalledTimes(captureCallsBeforeRecovery); + expect(runtime.helperActions).toEqual([]); + }); + + it("rejects mount drift before asking the root helper to assert an established fence", async () => { + const runtime = harness(); + const fence = await runtime.owner.acquire({ ...runtime.context, plan: plan() }); + runtime.state.mountSource = "/var/lib/openshell/replaced/hermes"; + + expect(() => runtime.owner.assertFenced(runtime.context, fence)).toThrow( + "Docker runtime changed after the state mutation fence was established", + ); + + expect(runtime.helperActions).toEqual(["acquire"]); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("fence-established"); + }); + + it("rejects registry-to-label sandbox identity drift before helper invocation", () => { + const runtime = harness(); + runtime.state.sandboxId = "replacement-sandbox-id"; + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "does not match the registered live identity", + ); + expect(runtime.helperActions).toEqual([]); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + }); + + it("rejects unsafe PID and procfs authority before invoking the root helper", async () => { + const hostPid = harness(); + hostPid.state.pidMode = "host"; + + expect(() => hostPid.owner.acquire({ ...hostPid.context, plan: plan() })).toThrow( + "private unprivileged PID namespace", + ); + expect(hostPid.helperActions).toEqual([]); + + const privileged = harness(); + privileged.state.privileged = true; + expect(() => privileged.owner.acquire({ ...privileged.context, plan: plan() })).toThrow( + "private unprivileged PID namespace", + ); + expect(privileged.helperActions).toEqual([]); + + const procOverlay = harness(); + procOverlay.state.overlayProc = true; + expect(() => procOverlay.owner.acquire({ ...procOverlay.context, plan: plan() })).toThrow( + "overlays the trusted private procfs", + ); + expect(procOverlay.helperActions).toEqual([]); + }); + + it("does not publish a fence when the helper changes the provider nonce", async () => { + const runtime = harness({ + mutateReceipt(receipt, action) { + return action === "acquire" ? { ...receipt, nonce: "f".repeat(64) } : receipt; + }, + }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "root helper receipt changed the prepared state mutation plan", + ); + + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + }); + + it("rejects a non-canonical provider receipt even when its fields are equivalent", async () => { + const runtime = harness({ + mutateReceipt(receipt, action) { + return action === "acquire" + ? Object.fromEntries(Object.entries(receipt).reverse()) + : receipt; + }, + }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "root helper receipt is not canonical", + ); + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + }); + + it("keeps prepared authority when exact acquire replay fails", async () => { + const runtime = harness({ failAcquire: true }); + + expect(() => runtime.owner.acquire({ ...runtime.context, plan: plan() })).toThrow( + "root helper acquire did not complete successfully", + ); + expect(() => runtime.owner.recover(runtime.context)).toThrow( + "root helper acquire did not complete successfully", + ); + + expect(runtime.lifecycleStore.listUnfinished()[0]?.phase).toBe("prepared"); + }); + + it("rejects sandbox lifecycle drift before Docker inspection", async () => { + const runtime = harness(); + const changed = { + ...runtime.context, + sandbox: { ...runtime.context.sandbox, lifecycleGeneration: "generation-8" }, + }; + + expect(() => runtime.owner.acquire({ ...changed, plan: plan() })).toThrow( + "sandbox lifecycle generation changed", + ); + expect(runtime.capture).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/runtime-provider/docker-state-mutation.ts b/src/lib/onboard/runtime-provider/docker-state-mutation.ts new file mode 100644 index 00000000000..6042fcbc9e7 --- /dev/null +++ b/src/lib/onboard/runtime-provider/docker-state-mutation.ts @@ -0,0 +1,2072 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash, randomBytes } from "node:crypto"; +import path from "node:path"; + +import type { ContainerEngineCommandCapture } from "../../adapters/container-engine"; +import { resolveShieldsStateDir, withShieldsTransitionLock } from "../../shields/transition-lock"; +import type { + RuntimeProviderPreparedStateMutationPlan, + RuntimeProviderStateMutationActivationProof, + RuntimeProviderStateMutationContext, + RuntimeProviderStateMutationFence, + RuntimeProviderStateMutationProtectionPosture, + RuntimeProviderStateMutationSurface, +} from "./contract"; +import { RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION } from "./contract"; +import { + createDockerOperationAuthority, + type DockerOperationAuthority, + dockerOperationBindingSha256, +} from "./docker-operation-authority"; +import { + createFilePersistedEngineAuthorityStore, + createPersistedEngineAuthority, + type PersistedEngineAuthorityStore, + requirePersistedEngineAuthority, +} from "./persisted-engine-authority"; +import { + type AuthorizedPersistedEngineLifecycle, + assertActivePersistedEngineStateMutation, + completePersistedEngineStateMutation, + createFilePersistedEngineLifecycleStore, + executePersistedEngineStateMutation, + hasActivePersistedEngineStateMutationTarget, + loadPersistedEngineStateMutationIntent, + type PersistedEngineLifecycleExecutionInput, + type PersistedEngineLifecycleRecord, + type PersistedEngineLifecycleStore, + type PersistedEngineStateMutationIntent, + preparePersistedEngineLifecycle, + releaseCompletedPersistedEngineStateMutation, +} from "./persisted-engine-lifecycle"; +import { prepareRuntimeProviderStateMutationPlan } from "./state-mutation"; + +const PROVIDER_ID = "docker"; +const SUPPORTED_STATE_ROOT = "/sandbox/.hermes"; +const HELPER_PYTHON_PATH = "/opt/hermes/.venv/bin/python3"; +const HELPER_PATH = "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py"; +const HELPER_FAST_TIMEOUT_MS = 30_000; +const HELPER_ACTIVATION_TIMEOUT_MS = 5 * 60_000; +const HELPER_GUARD_TIMEOUT_MS = 15 * 60_000; +const INSPECT_TIMEOUT_MS = 15_000; +const MAX_HELPER_TRANSPORT_BYTES = 128 * 1024; +const MAX_INSPECTION_BYTES = 1024 * 1024; +const MAX_MOUNTS = 256; +const RUNTIME_QUERY_FORMAT = "{{.ID}}"; +const INSPECT_FORMAT = + '[{{json .Id}},{{json .State.Running}},{{json .State.Status}},{{json .State.Paused}},{{json .State.Restarting}},{{json .State.Dead}},{{json .State.Pid}},{{json (index .Config.Labels "openshell.ai/managed-by")}},{{json (index .Config.Labels "openshell.ai/sandbox-name")}},{{json (index .Config.Labels "openshell.ai/sandbox-id")}},{{json .HostConfig.PidMode}},{{json .HostConfig.Privileged}},{{json .Mounts}}]'; +const SHA256 = /^[a-f0-9]{64}$/u; +const CONTAINER_ID = /^[a-f0-9]{64}$/u; +const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u; +const LIFECYCLE_GENERATION = /^[A-Za-z0-9][A-Za-z0-9._:/=+-]{0,511}$/u; +const MOUNT_NAMESPACE = /^mnt:\[[1-9][0-9]*\]$/u; +const POSITIVE_DECIMAL = /^[1-9][0-9]*$/u; +const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u; +const PROVIDER_HANDLE = /^docker-state-mutation-v1:([a-f0-9]{64}):([a-f0-9]{64})$/u; +const ACTIVATION_PROVIDER_HANDLE = + /^docker-state-mutation-activation-v1:([a-f0-9]{64}):([a-f0-9]{64})$/u; + +type HelperAction = + | "acquire" + | "assert" + | "publish" + | "recover" + | "rollback" + | "activate" + | "release"; +type HelperPhase = "fenced" | "published" | "rolled-back" | "activation-proven"; + +function helperTimeoutMs(action: HelperAction): number { + switch (action) { + case "publish": + case "recover": + case "rollback": + return HELPER_GUARD_TIMEOUT_MS; + case "activate": + case "release": + return HELPER_ACTIVATION_TIMEOUT_MS; + case "acquire": + case "assert": + return HELPER_FAST_TIMEOUT_MS; + } +} + +interface DockerMountIdentity { + readonly type: string; + readonly source: string; + readonly name: string | null; + readonly destination: string; + readonly driver: string | null; + readonly mode: string; + readonly readWrite: boolean; + readonly propagation: string; +} + +interface DockerRuntimeObservation { + readonly runtimeId: string; + readonly runtimePid: number; + readonly pidMode: ""; + readonly privileged: false; + readonly sandboxIdentitySha256: string; + readonly containerMountsSha256: string; + readonly mounts: readonly DockerMountIdentity[]; +} + +interface DockerStateRootBinding { + readonly stateRoot: string; + readonly stateRootMountsSha256: string; +} + +interface DockerStateMutationHelperReceipt { + readonly schemaVersion: 1; + readonly phase: HelperPhase; + readonly transactionId: string; + readonly providerId: typeof PROVIDER_ID; + readonly sandboxName: string; + readonly lifecycleGeneration: string; + readonly engineBindingSha256: string; + readonly runtimeId: string; + readonly runtimePid: number; + readonly sandboxIdentitySha256: string; + readonly containerMountsSha256: string; + readonly stateRoot: string; + readonly stateRootMountsSha256: string; + readonly mountNamespace: string; + readonly stateRootDevice: string; + readonly stateRootInode: string; + readonly planSha256: string; + readonly projectionSha256: string; + readonly nonce: string; + readonly target: RuntimeProviderStateMutationProtectionPosture; + readonly rollback: RuntimeProviderStateMutationProtectionPosture; + readonly configurationGeneration?: string; + readonly listenerIdentity?: string; + readonly healthSha256?: string; + readonly activationProviderHandle?: string; +} + +export interface DockerStateMutationOwnerOptions { + readonly sandboxName: string; + readonly lifecycleGeneration: string; + /** SHA-256 of the raw OpenShell sandbox ID recorded with this generation. */ + readonly lifecycleLiveIdentityFingerprint?: string; + /** Full immutable Docker container ID. Names and short IDs are not accepted. */ + readonly runtimeId: string; + readonly authority: DockerOperationAuthority; + readonly engineAuthorityStore: PersistedEngineAuthorityStore; + readonly lifecycleStore: PersistedEngineLifecycleStore; +} + +export interface DockerStateMutationSurfaceOptions { + /** Test seam for the fixed Docker executable; production uses the real capture adapter. */ + readonly capture?: ContainerEngineCommandCapture; + readonly resolveStateDir?: (environment: NodeJS.ProcessEnv) => string; + /** Test seam for the shared per-sandbox direct-execution exclusion. */ + readonly withDirectSandboxExecutionExclusion?: ( + sandboxName: string, + operation: string, + fn: () => T, + ) => T; +} + +function resolveDockerStateMutationStateDir(environment: NodeJS.ProcessEnv): string { + if ( + environment.VITEST === "true" && + (environment.HOME ?? "") === environment.NEMOCLAW_TEST_BASE_HOME && + environment.NEMOCLAW_TEST_STATE_DIR && + path.isAbsolute(environment.NEMOCLAW_TEST_STATE_DIR) + ) { + return environment.NEMOCLAW_TEST_STATE_DIR; + } + return resolveShieldsStateDir(environment.HOME?.trim() || undefined); +} + +export interface DockerStateMutationOwner { + acquire( + input: RuntimeProviderStateMutationContext & { + readonly plan: RuntimeProviderPreparedStateMutationPlan; + }, + ): RuntimeProviderStateMutationFence; + assertFenced( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): void; + publish( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): void; + recover(input: RuntimeProviderStateMutationContext): RuntimeProviderStateMutationFence | null; + /** Restore the plan's fixed rollback posture while retaining the exact fence. */ + rollback( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): void; + activate( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + ): RuntimeProviderStateMutationActivationProof; + release( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, + completedLedgerSha256: string, + ): void; +} + +function fail(message: string): never { + throw new Error(`Docker state mutation failed: ${message}`); +} + +function record(value: unknown, label: string): Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + fail(`${label} is malformed`); + } + return value as Record; +} + +function exactKeys( + value: Record, + expected: readonly string[], + label: string, +): void { + const actual = Object.keys(value).sort(); + const ordered = [...expected].sort(); + if (actual.length !== ordered.length || actual.some((key, index) => key !== ordered[index])) { + fail(`${label} schema is unsupported`); + } +} + +function boundedString(value: unknown, pattern: RegExp, label: string, maxBytes = 4096): string { + if ( + typeof value !== "string" || + !pattern.test(value) || + Buffer.byteLength(value, "utf8") > maxBytes || + CONTROL_CHARACTERS.test(value) + ) { + fail(`${label} is malformed`); + } + return value; +} + +function exactText(value: unknown, label: string, maxBytes = 16 * 1024): string { + if ( + typeof value !== "string" || + Buffer.byteLength(value, "utf8") > maxBytes || + CONTROL_CHARACTERS.test(value) + ) { + fail(`${label} is malformed`); + } + return value; +} + +function sha256(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} + +function canonicalRecord(fields: readonly (readonly [string, unknown])[]): string { + const transport: Record = Object.create(null); + for (const [key, value] of fields) transport[key] = value; + return JSON.stringify(transport); +} + +function canonicalAbsolutePath(value: unknown, label: string): string { + const candidate = exactText(value, label, 4096); + if ( + candidate.length === 0 || + !candidate.startsWith("/") || + candidate.endsWith("/") || + candidate.includes("\\") || + path.posix.normalize(candidate) !== candidate + ) { + fail(`${label} is not a canonical absolute path`); + } + return candidate; +} + +function canonicalStateRoot(value: unknown): string { + const stateRoot = canonicalAbsolutePath(value, "state root"); + if (!stateRoot.startsWith("/sandbox/")) fail("state root is outside /sandbox"); + if (stateRoot !== SUPPORTED_STATE_ROOT) fail("state root is unsupported by the Docker helper"); + return stateRoot; +} + +function exactOptionalText(value: unknown, label: string): string | null { + if (value === undefined || value === null) return null; + return exactText(value, label); +} + +function parseMount(value: unknown, index: number): DockerMountIdentity { + const source = record(value, `Docker mount ${String(index)}`); + const type = exactText(source.Type, `Docker mount ${String(index)} type`, 128); + const mountSource = exactText(source.Source, `Docker mount ${String(index)} source`); + const destination = canonicalAbsolutePath( + source.Destination, + `Docker mount ${String(index)} destination`, + ); + const name = exactOptionalText(source.Name, `Docker mount ${String(index)} name`); + const driver = exactOptionalText(source.Driver, `Docker mount ${String(index)} driver`); + const mode = exactText(source.Mode, `Docker mount ${String(index)} mode`, 1024); + const propagation = exactText( + source.Propagation, + `Docker mount ${String(index)} propagation`, + 1024, + ); + if (type.length === 0 || mountSource.length === 0 || typeof source.RW !== "boolean") { + fail(`Docker mount ${String(index)} is malformed`); + } + return Object.freeze({ + type, + source: mountSource, + name, + destination, + driver, + mode, + readWrite: source.RW, + propagation, + }); +} + +function mountTransport(mount: DockerMountIdentity): Record { + const transport: Record = Object.create(null); + transport.type = mount.type; + transport.source = mount.source; + transport.name = mount.name; + transport.destination = mount.destination; + transport.driver = mount.driver; + transport.mode = mount.mode; + transport.readWrite = mount.readWrite; + transport.propagation = mount.propagation; + return transport; +} + +function mountsSha256(mounts: readonly DockerMountIdentity[]): string { + const transport = mounts.map(mountTransport); + Object.setPrototypeOf(transport, null); + return sha256(JSON.stringify(transport)); +} + +function isPathAtOrBelow(candidate: string, root: string): boolean { + return candidate === root || candidate.startsWith(`${root}/`); +} + +function bindStateRoot( + observation: DockerRuntimeObservation, + stateRootInput: unknown, +): DockerStateRootBinding { + const stateRoot = canonicalStateRoot(stateRootInput); + const owners = observation.mounts.filter((mount) => + isPathAtOrBelow(stateRoot, mount.destination), + ); + if (owners.length === 0) fail("state root has no durable Docker mount"); + const deepestLength = Math.max(...owners.map((mount) => mount.destination.length)); + const deepest = owners.filter((mount) => mount.destination.length === deepestLength); + if (deepest.length !== 1 || !["bind", "volume"].includes(deepest[0]?.type ?? "")) { + fail("state root Docker mount is ambiguous or not durable"); + } + if (!deepest[0]?.readWrite) fail("state root Docker mount is not writable"); + const related = observation.mounts.filter( + (mount) => + isPathAtOrBelow(stateRoot, mount.destination) || + isPathAtOrBelow(mount.destination, stateRoot), + ); + return Object.freeze({ stateRoot, stateRootMountsSha256: mountsSha256(related) }); +} + +function parseInspection( + output: string, + expectedRuntimeId: string, + expectedSandboxName: string, +): DockerRuntimeObservation { + if ( + output.length === 0 || + Buffer.byteLength(output, "utf8") > MAX_INSPECTION_BYTES || + output.includes("\0") + ) { + fail("Docker container inspection output is empty or too large"); + } + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + fail("Docker container inspection returned unreadable JSON"); + } + if (!Array.isArray(parsed) || parsed.length !== 13) { + fail("Docker container inspection schema is unsupported"); + } + const [ + runtimeIdInput, + running, + status, + paused, + restarting, + dead, + runtimePid, + managedBy, + sandboxName, + sandboxIdInput, + pidMode, + privileged, + mountsInput, + ] = parsed; + const runtimeId = boundedString(runtimeIdInput, CONTAINER_ID, "Docker container identity"); + if (runtimeId !== expectedRuntimeId) fail("Docker container identity changed"); + if ( + running !== true || + status !== "running" || + paused !== false || + restarting !== false || + dead !== false || + !Number.isSafeInteger(runtimePid) || + (runtimePid as number) <= 0 + ) { + fail("Docker container is not one stable running runtime"); + } + if (managedBy !== "openshell" || sandboxName !== expectedSandboxName) { + fail("Docker container does not belong to the exact OpenShell sandbox"); + } + if (pidMode !== "" || privileged !== false) { + fail("Docker container does not have one private unprivileged PID namespace"); + } + const sandboxId = exactText(sandboxIdInput, "OpenShell sandbox identity", 512); + if (sandboxId.length === 0) fail("OpenShell sandbox identity is missing"); + if (!Array.isArray(mountsInput) || mountsInput.length > MAX_MOUNTS) { + fail("Docker container mounts are malformed"); + } + const mounts = mountsInput + .map(parseMount) + .sort((left, right) => + left.destination < right.destination + ? -1 + : left.destination > right.destination + ? 1 + : left.source.localeCompare(right.source), + ); + if (new Set(mounts.map((mount) => mount.destination)).size !== mounts.length) { + fail("Docker container has ambiguous mount destinations"); + } + if ( + mounts.some( + (mount) => + mount.destination === "/" || + mount.destination === "/proc" || + mount.destination.startsWith("/proc/"), + ) + ) { + fail("Docker container overlays the trusted private procfs"); + } + const sandboxIdentitySha256 = sha256(sandboxId); + return Object.freeze({ + runtimeId, + runtimePid: runtimePid as number, + pidMode: "", + privileged: false, + sandboxIdentitySha256, + containerMountsSha256: mountsSha256(mounts), + mounts: Object.freeze(mounts), + }); +} + +function exactPosture( + value: unknown, + label: string, +): RuntimeProviderStateMutationProtectionPosture { + if (value !== "locked" && value !== "mutable") fail(`${label} is malformed`); + return value; +} + +function parseHelperReceipt(output: string): DockerStateMutationHelperReceipt { + if ( + output.length === 0 || + !output.endsWith("\n") || + output.slice(0, -1).includes("\n") || + output.includes("\0") || + Buffer.byteLength(output, "utf8") > MAX_HELPER_TRANSPORT_BYTES + ) { + fail("root helper returned an invalid bounded receipt"); + } + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + fail("root helper returned unreadable JSON"); + } + const receipt = record(parsed, "root helper receipt"); + const activationFields = + receipt.phase === "activation-proven" + ? ["activationProviderHandle", "configurationGeneration", "healthSha256", "listenerIdentity"] + : []; + exactKeys( + receipt, + [ + "containerMountsSha256", + "engineBindingSha256", + "lifecycleGeneration", + "mountNamespace", + "nonce", + "phase", + "planSha256", + "projectionSha256", + "providerId", + "rollback", + "runtimeId", + "runtimePid", + "sandboxIdentitySha256", + "sandboxName", + "schemaVersion", + "stateRoot", + "stateRootDevice", + "stateRootInode", + "stateRootMountsSha256", + "target", + "transactionId", + ...activationFields, + ], + "root helper receipt", + ); + if ( + receipt.schemaVersion !== 1 || + (receipt.phase !== "fenced" && + receipt.phase !== "published" && + receipt.phase !== "rolled-back" && + receipt.phase !== "activation-proven") + ) { + fail("root helper receipt version or phase is unsupported"); + } + if (!Number.isSafeInteger(receipt.runtimePid) || (receipt.runtimePid as number) <= 0) { + fail("root helper runtime PID is malformed"); + } + const activation = + receipt.phase === "activation-proven" + ? { + configurationGeneration: boundedString( + receipt.configurationGeneration, + LIFECYCLE_GENERATION, + "helper configuration generation", + ), + listenerIdentity: boundedString( + receipt.listenerIdentity, + LIFECYCLE_GENERATION, + "helper listener identity", + ), + healthSha256: boundedString(receipt.healthSha256, SHA256, "helper health digest"), + activationProviderHandle: boundedString( + receipt.activationProviderHandle, + ACTIVATION_PROVIDER_HANDLE, + "helper activation provider handle", + ), + } + : {}; + const normalized = Object.freeze({ + schemaVersion: 1, + phase: receipt.phase, + transactionId: boundedString(receipt.transactionId, SHA256, "helper transaction identity"), + providerId: boundedString( + receipt.providerId, + /^docker$/u, + "helper provider identity", + ) as typeof PROVIDER_ID, + sandboxName: boundedString(receipt.sandboxName, SAFE_NAME, "helper sandbox name"), + lifecycleGeneration: boundedString( + receipt.lifecycleGeneration, + LIFECYCLE_GENERATION, + "helper lifecycle generation", + ), + engineBindingSha256: boundedString( + receipt.engineBindingSha256, + SHA256, + "helper engine binding digest", + ), + runtimeId: boundedString(receipt.runtimeId, CONTAINER_ID, "helper runtime identity"), + runtimePid: receipt.runtimePid as number, + sandboxIdentitySha256: boundedString( + receipt.sandboxIdentitySha256, + SHA256, + "helper sandbox identity digest", + ), + containerMountsSha256: boundedString( + receipt.containerMountsSha256, + SHA256, + "helper container mounts digest", + ), + stateRoot: canonicalStateRoot(receipt.stateRoot), + stateRootMountsSha256: boundedString( + receipt.stateRootMountsSha256, + SHA256, + "helper state root mounts digest", + ), + mountNamespace: boundedString( + receipt.mountNamespace, + MOUNT_NAMESPACE, + "helper mount namespace", + ), + stateRootDevice: boundedString( + receipt.stateRootDevice, + POSITIVE_DECIMAL, + "helper state root device", + ), + stateRootInode: boundedString( + receipt.stateRootInode, + POSITIVE_DECIMAL, + "helper state root inode", + ), + planSha256: boundedString(receipt.planSha256, SHA256, "helper plan digest"), + projectionSha256: boundedString(receipt.projectionSha256, SHA256, "helper projection digest"), + nonce: boundedString(receipt.nonce, SHA256, "helper nonce"), + target: exactPosture(receipt.target, "helper target posture"), + rollback: exactPosture(receipt.rollback, "helper rollback posture"), + ...activation, + }); + if (output !== `${fullReceiptTransport(normalized)}\n`) { + fail("root helper receipt is not canonical"); + } + return normalized; +} + +function receiptTransport(receipt: DockerStateMutationHelperReceipt): string { + return canonicalRecord([ + ["schemaVersion", receipt.schemaVersion], + ["phase", receipt.phase], + ["transactionId", receipt.transactionId], + ["providerId", receipt.providerId], + ["sandboxName", receipt.sandboxName], + ["lifecycleGeneration", receipt.lifecycleGeneration], + ["engineBindingSha256", receipt.engineBindingSha256], + ["runtimeId", receipt.runtimeId], + ["runtimePid", receipt.runtimePid], + ["sandboxIdentitySha256", receipt.sandboxIdentitySha256], + ["containerMountsSha256", receipt.containerMountsSha256], + ["stateRoot", receipt.stateRoot], + ["stateRootMountsSha256", receipt.stateRootMountsSha256], + ["mountNamespace", receipt.mountNamespace], + ["stateRootDevice", receipt.stateRootDevice], + ["stateRootInode", receipt.stateRootInode], + ["planSha256", receipt.planSha256], + ["projectionSha256", receipt.projectionSha256], + ["nonce", receipt.nonce], + ["target", receipt.target], + ["rollback", receipt.rollback], + ]); +} + +function fullReceiptTransport(receipt: DockerStateMutationHelperReceipt): string { + const base = JSON.parse(receiptTransport(receipt)) as Record; + if (receipt.phase === "activation-proven") { + base.configurationGeneration = receipt.configurationGeneration; + base.listenerIdentity = receipt.listenerIdentity; + base.healthSha256 = receipt.healthSha256; + base.activationProviderHandle = receipt.activationProviderHandle; + } + return JSON.stringify(base); +} + +function receiptWithPhase( + receipt: DockerStateMutationHelperReceipt, + phase: HelperPhase, +): DockerStateMutationHelperReceipt { + return Object.freeze({ ...receipt, phase }); +} + +function providerHandle(receipt: DockerStateMutationHelperReceipt): string { + return `docker-state-mutation-v1:${receipt.transactionId}:${sha256(receiptTransport(receipt))}`; +} + +function activationProviderHandleFor( + evidence: Pick< + RuntimeProviderStateMutationActivationProof, + | "providerId" + | "sandboxName" + | "lifecycleGeneration" + | "runtimeId" + | "nonce" + | "configurationGeneration" + | "listenerIdentity" + | "healthSha256" + >, + transactionId: string, + fenceProviderHandle: string, +): string { + const digest = sha256( + canonicalRecord([ + ["schemaVersion", 1], + ["providerId", evidence.providerId], + ["sandboxName", evidence.sandboxName], + ["lifecycleGeneration", evidence.lifecycleGeneration], + ["runtimeId", evidence.runtimeId], + ["nonce", evidence.nonce], + ["configurationGeneration", evidence.configurationGeneration], + ["listenerIdentity", evidence.listenerIdentity], + ["healthSha256", evidence.healthSha256], + ["fenceProviderHandle", fenceProviderHandle], + ]), + ); + return `docker-state-mutation-activation-v1:${transactionId}:${digest}`; +} + +function expectedActivationProviderHandle( + receipt: DockerStateMutationHelperReceipt, + fenceProviderHandle: string, +): string { + if ( + receipt.phase !== "activation-proven" || + receipt.configurationGeneration === undefined || + receipt.listenerIdentity === undefined || + receipt.healthSha256 === undefined + ) { + fail("root helper did not return complete activation evidence"); + } + return activationProviderHandleFor( + { + providerId: receipt.providerId, + sandboxName: receipt.sandboxName, + lifecycleGeneration: receipt.lifecycleGeneration, + runtimeId: receipt.runtimeId, + nonce: receipt.nonce, + configurationGeneration: receipt.configurationGeneration, + listenerIdentity: receipt.listenerIdentity, + healthSha256: receipt.healthSha256, + }, + receipt.transactionId, + fenceProviderHandle, + ); +} + +function activationProofFromReceipt( + receipt: DockerStateMutationHelperReceipt, + fenceProviderHandle: string, +): RuntimeProviderStateMutationActivationProof { + const expected = expectedActivationProviderHandle(receipt, fenceProviderHandle); + if (receipt.activationProviderHandle !== expected) { + fail("root helper activation provider handle is not bound to the exact fence"); + } + const normalized = Object.freeze({ + schemaVersion: 1, + providerId: receipt.providerId, + sandboxName: receipt.sandboxName, + lifecycleGeneration: receipt.lifecycleGeneration, + runtimeId: receipt.runtimeId, + nonce: receipt.nonce, + configurationGeneration: receipt.configurationGeneration as string, + listenerIdentity: receipt.listenerIdentity as string, + healthSha256: receipt.healthSha256 as string, + providerHandle: expected, + }); + return normalized; +} + +function normalizeActivationProof( + proof: RuntimeProviderStateMutationActivationProof, + fence: RuntimeProviderStateMutationFence, +): RuntimeProviderStateMutationActivationProof { + const source = record(proof, "state mutation activation proof"); + exactKeys( + source, + [ + "configurationGeneration", + "healthSha256", + "lifecycleGeneration", + "listenerIdentity", + "nonce", + "providerHandle", + "providerId", + "runtimeId", + "sandboxName", + "schemaVersion", + ], + "state mutation activation proof", + ); + const handle = + typeof proof.providerHandle === "string" + ? proof.providerHandle.match(ACTIVATION_PROVIDER_HANDLE) + : null; + if ( + proof.schemaVersion !== 1 || + proof.providerId !== fence.providerId || + proof.sandboxName !== fence.sandboxName || + proof.lifecycleGeneration !== fence.lifecycleGeneration || + proof.runtimeId !== fence.runtimeId || + proof.nonce !== fence.nonce || + !handle || + handle[1] !== fence.transactionId + ) { + fail("activation proof does not match the exact state mutation fence"); + } + const normalized = Object.freeze({ + schemaVersion: 1, + providerId: PROVIDER_ID, + sandboxName: fence.sandboxName, + lifecycleGeneration: fence.lifecycleGeneration, + runtimeId: fence.runtimeId, + nonce: fence.nonce, + configurationGeneration: boundedString( + proof.configurationGeneration, + LIFECYCLE_GENERATION, + "activation configuration generation", + ), + listenerIdentity: boundedString( + proof.listenerIdentity, + LIFECYCLE_GENERATION, + "activation listener identity", + ), + healthSha256: boundedString(proof.healthSha256, SHA256, "activation health digest"), + providerHandle: boundedString( + proof.providerHandle, + ACTIVATION_PROVIDER_HANDLE, + "activation provider handle", + ), + }); + if ( + normalized.providerHandle !== + activationProviderHandleFor(normalized, fence.transactionId, fence.providerHandle) + ) { + fail("activation proof provider handle is not bound to the exact fence"); + } + return normalized; +} + +function runtimeStateSha256( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + observation: DockerRuntimeObservation, + stateRoot: DockerStateRootBinding, +): string { + return sha256( + canonicalRecord([ + ["schemaVersion", 1], + ["providerId", PROVIDER_ID], + ["sandboxName", options.sandboxName], + ["lifecycleGeneration", options.lifecycleGeneration], + ["engineBindingSha256", bindingSha256], + ["runtimeId", observation.runtimeId], + ["runtimePid", observation.runtimePid], + ["pidMode", observation.pidMode], + ["privileged", observation.privileged], + ["sandboxIdentitySha256", observation.sandboxIdentitySha256], + ["containerMountsSha256", observation.containerMountsSha256], + ["stateRoot", stateRoot.stateRoot], + ["stateRootMountsSha256", stateRoot.stateRootMountsSha256], + ]), + ); +} + +function transactionId( + runtimeStateDigest: string, + planSha256: string, + projectionSha256: string, + nonce: string, + target: RuntimeProviderStateMutationProtectionPosture, + rollback: RuntimeProviderStateMutationProtectionPosture, +): string { + return sha256( + canonicalRecord([ + ["schemaVersion", 1], + ["action", "state-mutation"], + ["runtimeStateSha256", runtimeStateDigest], + ["planSha256", planSha256], + ["projectionSha256", projectionSha256], + ["nonce", nonce], + ["target", target], + ["rollback", rollback], + ]), + ); +} + +function requireContext( + options: DockerStateMutationOwnerOptions, + input: RuntimeProviderStateMutationContext, +): void { + if ( + input.sandboxName !== options.sandboxName || + input.sandbox.name !== options.sandboxName || + input.sandbox.openshellDriver !== PROVIDER_ID + ) { + fail("sandbox provider identity changed"); + } + if (input.sandbox.lifecycleGeneration !== options.lifecycleGeneration) { + fail("sandbox lifecycle generation changed"); + } + if (input.sandbox.lifecycleLiveIdentityFingerprint !== options.lifecycleLiveIdentityFingerprint) { + fail("sandbox live identity authority changed"); + } +} + +function requireRegistryLiveIdentity( + options: DockerStateMutationOwnerOptions, + observation: DockerRuntimeObservation, +): void { + const expected = options.lifecycleLiveIdentityFingerprint; + if (expected === undefined) return; + boundedString(expected, SHA256, "sandbox live identity fingerprint"); + if (observation.sandboxIdentitySha256 !== expected) { + fail("Docker sandbox identity does not match the registered live identity"); + } +} + +function requireCurrentEngineAuthority( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, +): void { + options.authority.assertAuthority(); + const persisted = options.engineAuthorityStore.load("sandbox-lifecycle"); + if (!persisted) fail("persisted sandbox-lifecycle engine authority is missing"); + requirePersistedEngineAuthority(persisted, PROVIDER_ID, options.authority.engine, bindingSha256); +} + +function inspectCommand(runtimeId: string) { + return Object.freeze({ + args: Object.freeze(["container", "inspect", "--format", INSPECT_FORMAT, runtimeId]), + targetIndex: 4, + }); +} + +function helperCommand(runtimeId: string, action: HelperAction) { + return Object.freeze({ + args: Object.freeze([ + "container", + "exec", + "--interactive", + "--user", + "root", + runtimeId, + HELPER_PYTHON_PATH, + "-I", + HELPER_PATH, + action, + ]), + targetIndex: 5, + }); +} + +function requireCommandSuccess( + result: { + readonly status: number; + readonly stdout: string; + readonly stderr: string; + readonly error?: Error; + }, + label: string, +): string { + if (result.error || result.status !== 0 || result.stderr.length !== 0) { + fail(`${label} did not complete successfully`); + } + return result.stdout; +} + +function inspectDirect( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, +): DockerRuntimeObservation { + requireCurrentEngineAuthority(options, bindingSha256); + const result = options.authority.engine.capture( + inspectCommand(options.runtimeId).args, + INSPECT_TIMEOUT_MS, + ); + requireCurrentEngineAuthority(options, bindingSha256); + const observation = parseInspection( + requireCommandSuccess(result, "Docker container inspection"), + options.runtimeId, + options.sandboxName, + ); + requireRegistryLiveIdentity(options, observation); + return observation; +} + +function inspectAuthorized( + scope: AuthorizedPersistedEngineLifecycle, + options: DockerStateMutationOwnerOptions, +): DockerRuntimeObservation { + const result = scope.captureExact("target", inspectCommand, INSPECT_TIMEOUT_MS); + const observation = parseInspection( + requireCommandSuccess(result, "Docker container inspection"), + options.runtimeId, + options.sandboxName, + ); + requireRegistryLiveIdentity(options, observation); + return observation; +} + +function sameObservation( + expected: DockerRuntimeObservation, + actual: DockerRuntimeObservation, +): void { + if ( + expected.runtimeId !== actual.runtimeId || + expected.runtimePid !== actual.runtimePid || + expected.pidMode !== actual.pidMode || + expected.privileged !== actual.privileged || + expected.sandboxIdentitySha256 !== actual.sandboxIdentitySha256 || + expected.containerMountsSha256 !== actual.containerMountsSha256 + ) { + fail("Docker runtime changed while the state mutation fence was established"); + } +} + +function helperInput(fields: readonly (readonly [string, unknown])[]): Buffer { + const serialized = `${canonicalRecord(fields)}\n`; + if (Buffer.byteLength(serialized, "utf8") > MAX_HELPER_TRANSPORT_BYTES) { + fail("root helper request exceeds its bounded transport"); + } + return Buffer.from(serialized, "utf8"); +} + +function invokeHelperAuthorized( + scope: AuthorizedPersistedEngineLifecycle, + action: HelperAction, + input: Buffer, +): DockerStateMutationHelperReceipt { + const result = scope.captureExact( + "target", + (runtimeId) => helperCommand(runtimeId, action), + helperTimeoutMs(action), + input, + ); + return parseHelperReceipt(requireCommandSuccess(result, `root helper ${action}`)); +} + +function lifecycleInput( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + record: Pick< + PersistedEngineLifecycleRecord, + "transactionId" | "sandboxName" | "resources" | "runtimeStateSha256" + >, +): PersistedEngineLifecycleExecutionInput { + return { + transactionId: record.transactionId, + action: "state-mutation", + sandboxName: record.sandboxName, + resources: record.resources, + runtimeStateSha256: record.runtimeStateSha256, + providerId: PROVIDER_ID, + bindingSha256, + engine: options.authority.engine, + engineAuthorityStore: options.engineAuthorityStore, + lifecycleStore: options.lifecycleStore, + }; +} + +function normalizePreparedPlan( + prepared: RuntimeProviderPreparedStateMutationPlan, +): RuntimeProviderPreparedStateMutationPlan & { + readonly plan: Extract< + RuntimeProviderPreparedStateMutationPlan["plan"], + { intent: "protection-transition" } + >; +} { + const normalized = prepareRuntimeProviderStateMutationPlan(prepared.plan); + if ( + prepared.serializedPlan !== normalized.serializedPlan || + prepared.planSha256 !== normalized.planSha256 || + prepared.projectionSha256 !== normalized.projectionSha256 + ) { + fail("prepared state mutation plan changed after validation"); + } + if (normalized.plan.intent !== "protection-transition") { + fail("Docker adapter does not implement restore publication"); + } + if (normalized.plan.target === normalized.plan.rollback) { + fail("protection transition target must differ from its rollback posture"); + } + return normalized as RuntimeProviderPreparedStateMutationPlan & { + readonly plan: Extract< + RuntimeProviderPreparedStateMutationPlan["plan"], + { intent: "protection-transition" } + >; + }; +} + +function preparedPlanFromPersistedIntent( + intent: PersistedEngineStateMutationIntent, +): ReturnType { + let parsed: unknown; + try { + parsed = JSON.parse(intent.serializedPlan); + } catch { + fail("persisted state mutation plan is not valid JSON"); + } + return normalizePreparedPlan({ + plan: parsed as RuntimeProviderPreparedStateMutationPlan["plan"], + serializedPlan: intent.serializedPlan, + planSha256: intent.planSha256, + projectionSha256: intent.projectionSha256, + }); +} + +function acquireRequest( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + observation: DockerRuntimeObservation, + stateRoot: DockerStateRootBinding, + plan: ReturnType, + nonce: string, + exactTransactionId: string, +): Buffer { + return helperInput([ + ["schemaVersion", 1], + ["action", "acquire"], + ["transactionId", exactTransactionId], + ["providerId", PROVIDER_ID], + ["sandboxName", options.sandboxName], + ["lifecycleGeneration", options.lifecycleGeneration], + ["engineBindingSha256", bindingSha256], + ["runtimeId", observation.runtimeId], + ["runtimePid", observation.runtimePid], + ["sandboxIdentitySha256", observation.sandboxIdentitySha256], + ["containerMountsSha256", observation.containerMountsSha256], + ["stateRoot", stateRoot.stateRoot], + ["stateRootMountsSha256", stateRoot.stateRootMountsSha256], + ["plan", plan.serializedPlan], + ["planSha256", plan.planSha256], + ["projectionSha256", plan.projectionSha256], + ["nonce", nonce], + ["target", plan.plan.target], + ["rollback", plan.plan.rollback], + ]); +} + +function statusRequest( + action: Exclude, + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + observation: DockerRuntimeObservation, + exactTransactionId: string, + expectedProviderHandle?: string, + activationProviderHandle?: string, + completedLedgerSha256?: string, +): Buffer { + return helperInput([ + ["schemaVersion", 1], + ["action", action], + ["transactionId", exactTransactionId], + ["providerId", PROVIDER_ID], + ["sandboxName", options.sandboxName], + ["lifecycleGeneration", options.lifecycleGeneration], + ["engineBindingSha256", bindingSha256], + ["runtimeId", observation.runtimeId], + ["runtimePid", observation.runtimePid], + ["sandboxIdentitySha256", observation.sandboxIdentitySha256], + ["containerMountsSha256", observation.containerMountsSha256], + ...(expectedProviderHandle === undefined + ? [] + : ([["providerHandle", expectedProviderHandle]] as const)), + ...(activationProviderHandle === undefined + ? [] + : ([["activationProviderHandle", activationProviderHandle]] as const)), + ...(completedLedgerSha256 === undefined + ? [] + : ([["completedLedgerSha256", completedLedgerSha256]] as const)), + ]); +} + +function validateReceipt( + receipt: DockerStateMutationHelperReceipt, + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + observation: DockerRuntimeObservation, + record: PersistedEngineLifecycleRecord, +): DockerStateRootBinding { + const stateRoot = bindStateRoot(observation, receipt.stateRoot); + if ( + receipt.providerId !== PROVIDER_ID || + receipt.sandboxName !== options.sandboxName || + receipt.lifecycleGeneration !== options.lifecycleGeneration || + receipt.engineBindingSha256 !== bindingSha256 || + receipt.runtimeId !== observation.runtimeId || + receipt.runtimePid !== observation.runtimePid || + receipt.sandboxIdentitySha256 !== observation.sandboxIdentitySha256 || + receipt.containerMountsSha256 !== observation.containerMountsSha256 || + receipt.stateRootMountsSha256 !== stateRoot.stateRootMountsSha256 || + receipt.target === receipt.rollback + ) { + fail("root helper receipt does not match the exact Docker runtime binding"); + } + const expectedRuntimeState = runtimeStateSha256(options, bindingSha256, observation, stateRoot); + const expectedTransactionId = transactionId( + expectedRuntimeState, + receipt.planSha256, + receipt.projectionSha256, + receipt.nonce, + receipt.target, + receipt.rollback, + ); + const targetRuntime = record.resources.find((resource) => resource.role === "target")?.runtimeId; + if ( + record.action !== "state-mutation" || + record.sandboxName !== options.sandboxName || + targetRuntime !== observation.runtimeId || + record.runtimeStateSha256 !== expectedRuntimeState || + record.transactionId !== expectedTransactionId || + receipt.transactionId !== expectedTransactionId + ) { + fail("root helper receipt does not match the durable lifecycle transaction"); + } + return stateRoot; +} + +function fenceFromReceipt( + receipt: DockerStateMutationHelperReceipt, + runtimeStateDigest: string, + bindingSha256: string, +): RuntimeProviderStateMutationFence { + const activeReceipt = receiptWithPhase(receipt, "fenced"); + return Object.freeze({ + schemaVersion: 1, + intent: "protection-transition", + phase: receipt.phase, + providerId: receipt.providerId, + sandboxName: receipt.sandboxName, + transactionId: receipt.transactionId, + lifecycleGeneration: receipt.lifecycleGeneration, + runtimeId: receipt.runtimeId, + runtimeStateSha256: runtimeStateDigest, + engineBindingSha256: bindingSha256, + stateRoot: receipt.stateRoot, + mountNamespaceId: receipt.mountNamespace, + stateRootDevice: receipt.stateRootDevice, + stateRootInode: receipt.stateRootInode, + planSha256: receipt.planSha256, + projectionSha256: receipt.projectionSha256, + target: receipt.target, + rollback: receipt.rollback, + nonce: receipt.nonce, + providerHandle: providerHandle(activeReceipt), + }); +} + +function normalizeFence( + fence: RuntimeProviderStateMutationFence, + options: DockerStateMutationOwnerOptions, + bindingSha256: string, +): RuntimeProviderStateMutationFence { + const source = record(fence, "state mutation fence"); + exactKeys( + source, + [ + "intent", + "lifecycleGeneration", + "engineBindingSha256", + "mountNamespaceId", + "nonce", + "phase", + "planSha256", + "projectionSha256", + "providerHandle", + "providerId", + "runtimeId", + "runtimeStateSha256", + "rollback", + "sandboxName", + "schemaVersion", + "stateRoot", + "stateRootDevice", + "stateRootInode", + "target", + "transactionId", + ], + "state mutation fence", + ); + const handle = + typeof fence.providerHandle === "string" ? fence.providerHandle.match(PROVIDER_HANDLE) : null; + if ( + fence.schemaVersion !== 1 || + fence.intent !== "protection-transition" || + (fence.phase !== "fenced" && + fence.phase !== "published" && + fence.phase !== "rolled-back" && + fence.phase !== "activation-proven") || + fence.providerId !== PROVIDER_ID || + fence.sandboxName !== options.sandboxName || + fence.lifecycleGeneration !== options.lifecycleGeneration || + fence.runtimeId !== options.runtimeId || + fence.engineBindingSha256 !== bindingSha256 || + fence.transactionId !== handle?.[1] || + fence.target === fence.rollback || + !handle + ) { + fail("state mutation fence does not match the bound Docker runtime"); + } + return Object.freeze({ + ...fence, + transactionId: boundedString(fence.transactionId, SHA256, "fence transaction identity"), + runtimeId: boundedString(fence.runtimeId, CONTAINER_ID, "fence runtime identity"), + runtimeStateSha256: boundedString( + fence.runtimeStateSha256, + SHA256, + "fence runtime state digest", + ), + engineBindingSha256: boundedString( + fence.engineBindingSha256, + SHA256, + "fence engine authority digest", + ), + stateRoot: canonicalStateRoot(fence.stateRoot), + mountNamespaceId: boundedString( + fence.mountNamespaceId, + MOUNT_NAMESPACE, + "fence mount namespace", + ), + stateRootDevice: boundedString( + fence.stateRootDevice, + POSITIVE_DECIMAL, + "fence state root device", + ), + stateRootInode: boundedString(fence.stateRootInode, POSITIVE_DECIMAL, "fence state root inode"), + planSha256: boundedString(fence.planSha256, SHA256, "fence plan digest"), + projectionSha256: boundedString(fence.projectionSha256, SHA256, "fence projection digest"), + target: exactPosture(fence.target, "fence target posture"), + rollback: exactPosture(fence.rollback, "fence rollback posture"), + nonce: boundedString(fence.nonce, SHA256, "fence nonce"), + }); +} + +function requireFenceReceipt( + fence: ReturnType, + receipt: DockerStateMutationHelperReceipt, +): void { + const activeReceipt = receiptWithPhase(receipt, "fenced"); + if ( + fence.transactionId !== receipt.transactionId || + fence.runtimeId !== receipt.runtimeId || + fence.stateRoot !== receipt.stateRoot || + fence.mountNamespaceId !== receipt.mountNamespace || + fence.stateRootDevice !== receipt.stateRootDevice || + fence.stateRootInode !== receipt.stateRootInode || + fence.planSha256 !== receipt.planSha256 || + fence.projectionSha256 !== receipt.projectionSha256 || + fence.intent !== "protection-transition" || + fence.target !== receipt.target || + fence.rollback !== receipt.rollback || + fence.nonce !== receipt.nonce || + fence.providerHandle !== providerHandle(activeReceipt) + ) { + fail("state mutation fence does not match the root helper receipt"); + } +} + +function unfinishedRecord( + options: DockerStateMutationOwnerOptions, +): PersistedEngineLifecycleRecord | null { + const matches = options.lifecycleStore + .listUnfinished() + .filter( + (record) => record.action === "state-mutation" && record.sandboxName === options.sandboxName, + ); + if (matches.length > 1) fail("more than one state mutation owns the OpenShell sandbox"); + const match = matches[0]; + if (!match) return null; + const targetRuntime = match.resources.find((resource) => resource.role === "target")?.runtimeId; + if (targetRuntime !== options.runtimeId) { + fail("durable state mutation target does not match the exact labeled Docker runtime"); + } + return match; +} + +function validateAcquireReceipt( + receipt: DockerStateMutationHelperReceipt, + plan: ReturnType, + nonce: string, + expectedTransactionId: string, +): void { + if ( + receipt.phase !== "fenced" || + receipt.transactionId !== expectedTransactionId || + receipt.planSha256 !== plan.planSha256 || + receipt.projectionSha256 !== plan.projectionSha256 || + receipt.nonce !== nonce || + receipt.stateRoot !== plan.plan.stateRoot || + receipt.target !== plan.plan.target || + receipt.rollback !== plan.plan.rollback + ) { + fail("root helper receipt changed the prepared state mutation plan"); + } +} + +function acquireAuthorizedReceipt( + scope: AuthorizedPersistedEngineLifecycle, + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + plan: ReturnType, + nonce: string, + exactTransactionId: string, + expectedRuntimeStateSha256: string, + expectedObservation?: DockerRuntimeObservation, +): DockerStateMutationHelperReceipt { + const observation = inspectAuthorized(scope, options); + if (expectedObservation) sameObservation(expectedObservation, observation); + const stateRoot = bindStateRoot(observation, plan.plan.stateRoot); + const observedRuntimeStateSha256 = runtimeStateSha256( + options, + bindingSha256, + observation, + stateRoot, + ); + if (observedRuntimeStateSha256 !== expectedRuntimeStateSha256) { + fail("Docker runtime changed before the state mutation fence was established"); + } + if ( + transactionId( + observedRuntimeStateSha256, + plan.planSha256, + plan.projectionSha256, + nonce, + plan.plan.target, + plan.plan.rollback, + ) !== exactTransactionId + ) { + fail("persisted state mutation intent does not match the lifecycle transaction"); + } + const receipt = invokeHelperAuthorized( + scope, + "acquire", + acquireRequest(options, bindingSha256, observation, stateRoot, plan, nonce, exactTransactionId), + ); + validateAcquireReceipt(receipt, plan, nonce, exactTransactionId); + validateReceipt(receipt, options, bindingSha256, observation, scope.record); + const after = inspectAuthorized(scope, options); + sameObservation(observation, after); + return receipt; +} + +function queryEstablishedReceipt( + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + execution: PersistedEngineLifecycleExecutionInput, + action: "assert" | "publish" | "recover" | "rollback" | "activate", + expectedFence?: RuntimeProviderStateMutationFence, +): DockerStateMutationHelperReceipt { + assertActivePersistedEngineStateMutation(execution); + const lease = options.lifecycleStore.acquireMutationExecution(execution.transactionId); + try { + const guard = () => { + assertActivePersistedEngineStateMutation(execution); + options.lifecycleStore.assertMutationExecution(lease); + requireCurrentEngineAuthority(options, bindingSha256); + }; + guard(); + const before = inspectDirect(options, bindingSha256); + const currentRecord = executionRecord(execution); + if (expectedFence) { + const stateRoot = bindStateRoot(before, expectedFence.stateRoot); + if ( + expectedFence.runtimeStateSha256 !== currentRecord.runtimeStateSha256 || + currentRecord.runtimeStateSha256 !== + runtimeStateSha256(options, bindingSha256, before, stateRoot) + ) { + fail("Docker runtime changed after the state mutation fence was established"); + } + } + guard(); + const result = options.authority.engine.capture( + helperCommand(options.runtimeId, action).args, + helperTimeoutMs(action), + statusRequest( + action, + options, + bindingSha256, + before, + execution.transactionId, + expectedFence?.providerHandle, + ), + ); + guard(); + const receipt = parseHelperReceipt(requireCommandSuccess(result, `root helper ${action}`)); + validateReceipt(receipt, options, bindingSha256, before, currentRecord); + if (expectedFence) requireFenceReceipt(expectedFence, receipt); + const after = inspectDirect(options, bindingSha256); + sameObservation(before, after); + guard(); + return receipt; + } finally { + try { + options.lifecycleStore.releaseMutationExecution(lease); + } catch { + // A recovered process can own the exact lease after this process fails. + } + } +} + +function executionRecord( + input: PersistedEngineLifecycleExecutionInput, +): PersistedEngineLifecycleRecord { + const current = input.lifecycleStore.load(input.transactionId); + if (!current) fail("durable state mutation transaction is missing"); + return current; +} + +function requireRecordMatchesFence( + record: PersistedEngineLifecycleRecord, + fence: RuntimeProviderStateMutationFence, + options: DockerStateMutationOwnerOptions, +): void { + const targetRuntime = record.resources.find((resource) => resource.role === "target")?.runtimeId; + if ( + record.action !== "state-mutation" || + record.transactionId !== fence.transactionId || + record.sandboxName !== options.sandboxName || + targetRuntime !== fence.runtimeId || + record.runtimeStateSha256 !== fence.runtimeStateSha256 + ) { + fail("state mutation fence does not match the durable lifecycle transaction"); + } +} + +function sameActivationProof( + expected: RuntimeProviderStateMutationActivationProof, + actual: RuntimeProviderStateMutationActivationProof, +): void { + const fields: ReadonlyArray = [ + "schemaVersion", + "providerId", + "sandboxName", + "lifecycleGeneration", + "runtimeId", + "nonce", + "configurationGeneration", + "listenerIdentity", + "healthSha256", + "providerHandle", + ]; + if (fields.some((field) => expected[field] !== actual[field])) { + fail("activation proof changed after provider validation"); + } +} + +function releaseAuthorizedFence( + scope: AuthorizedPersistedEngineLifecycle, + options: DockerStateMutationOwnerOptions, + bindingSha256: string, + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, + completedLedgerSha256: string, +): void { + const before = inspectAuthorized(scope, options); + const receipt = invokeHelperAuthorized( + scope, + "release", + statusRequest( + "release", + options, + bindingSha256, + before, + fence.transactionId, + fence.providerHandle, + proof.providerHandle, + completedLedgerSha256, + ), + ); + validateReceipt(receipt, options, bindingSha256, before, scope.record); + requireFenceReceipt(fence, receipt); + sameActivationProof(proof, activationProofFromReceipt(receipt, fence.providerHandle)); + const after = inspectAuthorized(scope, options); + sameObservation(before, after); +} + +/** + * Own Docker's durable state-mutation fence without accepting a shell command, + * helper path, runtime alias, or caller-authored provider receipt. + */ +export function createDockerStateMutationOwner( + optionsInput: DockerStateMutationOwnerOptions, +): DockerStateMutationOwner { + const options = Object.freeze({ ...optionsInput }); + boundedString(options.sandboxName, SAFE_NAME, "sandbox name"); + boundedString(options.lifecycleGeneration, LIFECYCLE_GENERATION, "lifecycle generation"); + if (options.lifecycleLiveIdentityFingerprint !== undefined) { + boundedString( + options.lifecycleLiveIdentityFingerprint, + SHA256, + "sandbox live identity fingerprint", + ); + } + boundedString(options.runtimeId, CONTAINER_ID, "Docker runtime identity"); + if ( + options.authority.engine.operation !== "sandbox-lifecycle" || + options.authority.engine.engineId !== PROVIDER_ID + ) { + fail("Docker authority does not own sandbox-lifecycle operations"); + } + const bindingSha256 = dockerOperationBindingSha256(options.authority.engine); + + const owner: DockerStateMutationOwner = { + acquire(input) { + requireContext(options, input); + if ( + options.lifecycleStore + .listUnfinished() + .some( + (record) => + record.action === "state-mutation" && record.sandboxName === options.sandboxName, + ) + ) { + fail("OpenShell sandbox already has one unfinished state mutation"); + } + const plan = normalizePreparedPlan(input.plan); + options.authority.assertAuthority(); + options.engineAuthorityStore.record( + createPersistedEngineAuthority(PROVIDER_ID, options.authority.engine, bindingSha256), + ); + const before = inspectDirect(options, bindingSha256); + const stateRoot = bindStateRoot(before, plan.plan.stateRoot); + const runtimeStateDigest = runtimeStateSha256(options, bindingSha256, before, stateRoot); + const nonce = randomBytes(32).toString("hex"); + const exactTransactionId = transactionId( + runtimeStateDigest, + plan.planSha256, + plan.projectionSha256, + nonce, + plan.plan.target, + plan.plan.rollback, + ); + const execution = lifecycleInput(options, bindingSha256, { + transactionId: exactTransactionId, + sandboxName: options.sandboxName, + resources: [{ role: "target", runtimeId: options.runtimeId }], + runtimeStateSha256: runtimeStateDigest, + }); + preparePersistedEngineLifecycle({ + ...execution, + stateMutationIntent: { + serializedPlan: plan.serializedPlan, + planSha256: plan.planSha256, + projectionSha256: plan.projectionSha256, + nonce, + }, + }); + const established = executePersistedEngineStateMutation(execution, (scope) => + acquireAuthorizedReceipt( + scope, + options, + bindingSha256, + plan, + nonce, + exactTransactionId, + runtimeStateDigest, + before, + ), + ); + return fenceFromReceipt(established.value, runtimeStateDigest, bindingSha256); + }, + + assertFenced(input, fenceInput) { + requireContext(options, input); + requireCurrentEngineAuthority(options, bindingSha256); + const fence = normalizeFence(fenceInput, options, bindingSha256); + const record = options.lifecycleStore.load(fence.transactionId); + if (!record) fail("durable state mutation transaction is missing"); + requireRecordMatchesFence(record, fence, options); + const execution = lifecycleInput(options, bindingSha256, record); + queryEstablishedReceipt(options, bindingSha256, execution, "assert", fence); + }, + + publish(input, fenceInput) { + requireContext(options, input); + requireCurrentEngineAuthority(options, bindingSha256); + const fence = normalizeFence(fenceInput, options, bindingSha256); + const record = options.lifecycleStore.load(fence.transactionId); + if (!record) fail("durable state mutation transaction is missing"); + requireRecordMatchesFence(record, fence, options); + const receipt = queryEstablishedReceipt( + options, + bindingSha256, + lifecycleInput(options, bindingSha256, record), + "publish", + fence, + ); + if (receipt.phase !== "published") fail("root helper did not publish the target posture"); + }, + + rollback(input, fenceInput) { + requireContext(options, input); + requireCurrentEngineAuthority(options, bindingSha256); + const fence = normalizeFence(fenceInput, options, bindingSha256); + const record = options.lifecycleStore.load(fence.transactionId); + if (!record) fail("durable state mutation transaction is missing"); + requireRecordMatchesFence(record, fence, options); + const receipt = queryEstablishedReceipt( + options, + bindingSha256, + lifecycleInput(options, bindingSha256, record), + "rollback", + fence, + ); + if (receipt.phase !== "rolled-back") fail("root helper did not restore rollback posture"); + }, + + activate(input, fenceInput) { + requireContext(options, input); + requireCurrentEngineAuthority(options, bindingSha256); + const fence = normalizeFence(fenceInput, options, bindingSha256); + const record = options.lifecycleStore.load(fence.transactionId); + if (!record) fail("durable state mutation transaction is missing"); + requireRecordMatchesFence(record, fence, options); + const receipt = queryEstablishedReceipt( + options, + bindingSha256, + lifecycleInput(options, bindingSha256, record), + "activate", + fence, + ); + return activationProofFromReceipt(receipt, fence.providerHandle); + }, + + release(input, fenceInput, proofInput, completedLedgerSha256Input) { + requireContext(options, input); + requireCurrentEngineAuthority(options, bindingSha256); + const fence = normalizeFence(fenceInput, options, bindingSha256); + const proof = normalizeActivationProof(proofInput, fence); + const completedLedgerSha256 = boundedString( + completedLedgerSha256Input, + SHA256, + "completed ledger digest", + ); + const record = options.lifecycleStore.load(fence.transactionId); + if (!record) { + if (options.lifecycleStore.isRetired(fence.transactionId, completedLedgerSha256)) return; + fail("durable state mutation transaction is missing"); + } + requireRecordMatchesFence(record, fence, options); + const execution = lifecycleInput(options, bindingSha256, record); + + if (record.phase === "completed") { + if (record.resultSha256 !== completedLedgerSha256) { + fail("completed ledger digest changed after durable host completion"); + } + const stillOwnsRuntime = options.lifecycleStore + .listUnfinished() + .some((candidate) => candidate.transactionId === record.transactionId); + if (!stillOwnsRuntime) { + if ( + options.lifecycleStore.isStateMutationReleaseFinalized( + record.transactionId, + completedLedgerSha256, + ) + ) { + options.lifecycleStore.retire(record.transactionId, completedLedgerSha256); + return; + } + fail("completed state mutation lost its provider release authority"); + } + releaseCompletedPersistedEngineStateMutation(execution, (scope, completed) => { + if (completed.resultSha256 !== completedLedgerSha256) { + fail("completed ledger digest changed before provider release"); + } + releaseAuthorizedFence( + scope, + options, + bindingSha256, + fence, + proof, + completedLedgerSha256, + ); + }); + options.lifecycleStore.retire(record.transactionId, completedLedgerSha256); + return; + } + if (record.phase !== "fence-established") { + fail("state mutation release requires one established provider fence"); + } + + let activatedProof: RuntimeProviderStateMutationActivationProof | undefined; + completePersistedEngineStateMutation( + execution, + (scope) => { + const before = inspectAuthorized(scope, options); + const receipt = invokeHelperAuthorized( + scope, + "activate", + statusRequest( + "activate", + options, + bindingSha256, + before, + fence.transactionId, + fence.providerHandle, + ), + ); + validateReceipt(receipt, options, bindingSha256, before, scope.record); + requireFenceReceipt(fence, receipt); + activatedProof = activationProofFromReceipt(receipt, fence.providerHandle); + sameActivationProof(proof, activatedProof); + const after = inspectAuthorized(scope, options); + sameObservation(before, after); + return { resultSha256: completedLedgerSha256, value: undefined }; + }, + (scope, completed) => { + if (!activatedProof || completed.resultSha256 !== completedLedgerSha256) { + fail("provider activation proof changed before release"); + } + releaseAuthorizedFence( + scope, + options, + bindingSha256, + fence, + activatedProof, + completedLedgerSha256, + ); + }, + ); + options.lifecycleStore.retire(record.transactionId, completedLedgerSha256); + }, + + recover(input) { + requireContext(options, input); + const record = unfinishedRecord(options); + if (!record) return null; + requireCurrentEngineAuthority(options, bindingSha256); + const execution = lifecycleInput(options, bindingSha256, record); + let receipt: DockerStateMutationHelperReceipt; + if (record.phase === "completed") { + if (record.resultSha256 === null) fail("completed lifecycle receipt is malformed"); + releaseCompletedPersistedEngineStateMutation(execution, (scope, completed) => { + const before = inspectAuthorized(scope, options); + const recovered = invokeHelperAuthorized( + scope, + "recover", + statusRequest("recover", options, bindingSha256, before, record.transactionId), + ); + validateReceipt(recovered, options, bindingSha256, before, scope.record); + const recoveredFence = fenceFromReceipt( + recovered, + record.runtimeStateSha256, + bindingSha256, + ); + const recoveredProof = activationProofFromReceipt( + recovered, + recoveredFence.providerHandle, + ); + releaseAuthorizedFence( + scope, + options, + bindingSha256, + recoveredFence, + recoveredProof, + completed.resultSha256 as string, + ); + }); + options.lifecycleStore.retire(record.transactionId, record.resultSha256); + return null; + } + if (record.phase === "fence-established") { + receipt = queryEstablishedReceipt(options, bindingSha256, execution, "recover"); + } else { + const intent = loadPersistedEngineStateMutationIntent(execution); + const plan = preparedPlanFromPersistedIntent(intent); + const nonce = boundedString(intent.nonce, SHA256, "persisted state mutation nonce"); + const established = executePersistedEngineStateMutation(execution, (scope) => { + return acquireAuthorizedReceipt( + scope, + options, + bindingSha256, + plan, + nonce, + record.transactionId, + record.runtimeStateSha256, + ); + }); + receipt = established.value; + } + return fenceFromReceipt(receipt, record.runtimeStateSha256, bindingSha256); + }, + }; + return Object.freeze(owner); +} + +function lifecycleGeneration(input: RuntimeProviderStateMutationContext): string { + return boundedString( + input.sandbox.lifecycleGeneration, + LIFECYCLE_GENERATION, + "sandbox lifecycle generation", + ); +} + +function requireSurfaceContext(input: RuntimeProviderStateMutationContext): void { + const sandboxName = boundedString(input.sandboxName, SAFE_NAME, "sandbox name"); + if ( + input.sandbox.name !== sandboxName || + input.sandbox.openshellDriver !== PROVIDER_ID || + typeof input.environment !== "object" || + input.environment === null + ) { + fail("sandbox provider identity changed"); + } + lifecycleGeneration(input); +} + +function resolveExactLabeledRuntimeId( + authority: DockerOperationAuthority, + sandboxName: string, +): string { + const result = authority.engine.capture( + [ + "ps", + "-a", + "--no-trunc", + "--filter", + "label=openshell.ai/managed-by=openshell", + "--filter", + `label=openshell.ai/sandbox-name=${sandboxName}`, + "--format", + RUNTIME_QUERY_FORMAT, + ], + INSPECT_TIMEOUT_MS, + ); + const output = requireCommandSuccess(result, "Docker labeled runtime resolution"); + if (Buffer.byteLength(output, "utf8") > 4096 || output.includes("\0") || output.includes("\r")) { + fail("Docker labeled runtime resolution returned malformed output"); + } + const ids = output + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); + if (ids.length !== 1 || !CONTAINER_ID.test(ids[0] as string)) { + fail("Docker labeled runtime resolution requires one exact full container identity"); + } + authority.assertAuthority(); + return ids[0] as string; +} + +function requireExistingSurfaceAuthority( + authority: DockerOperationAuthority, + engineAuthorityStore: PersistedEngineAuthorityStore, +): void { + authority.assertAuthority(); + const persisted = engineAuthorityStore.load("sandbox-lifecycle"); + if (!persisted) fail("persisted sandbox-lifecycle engine authority is missing"); + requirePersistedEngineAuthority( + persisted, + PROVIDER_ID, + authority.engine, + dockerOperationBindingSha256(authority.engine), + ); +} + +function createSurfaceOwner( + input: RuntimeProviderStateMutationContext, + options: DockerStateMutationSurfaceOptions, + phase: "acquire" | "existing", +): DockerStateMutationOwner { + requireSurfaceContext(input); + + // The operation-qualified endpoint is established from this invocation's + // environment before any mutable-name lookup occurs. + const authority = createDockerOperationAuthority( + "sandbox-lifecycle", + input.environment, + options.capture, + ); + const stateDir = (options.resolveStateDir ?? resolveDockerStateMutationStateDir)( + input.environment, + ); + const engineAuthorityStore = createFilePersistedEngineAuthorityStore(stateDir); + if (phase === "existing") { + requireExistingSurfaceAuthority(authority, engineAuthorityStore); + } + const runtimeId = resolveExactLabeledRuntimeId(authority, input.sandboxName); + return createDockerStateMutationOwner({ + sandboxName: input.sandboxName, + lifecycleGeneration: lifecycleGeneration(input), + ...(input.sandbox.lifecycleLiveIdentityFingerprint === undefined + ? {} + : { + lifecycleLiveIdentityFingerprint: input.sandbox.lifecycleLiveIdentityFingerprint, + }), + runtimeId, + authority, + engineAuthorityStore, + lifecycleStore: createFilePersistedEngineLifecycleStore(stateDir), + }); +} + +function recoverSurface( + input: RuntimeProviderStateMutationContext, + options: DockerStateMutationSurfaceOptions, +): RuntimeProviderStateMutationFence | null { + requireSurfaceContext(input); + const stateDir = (options.resolveStateDir ?? resolveDockerStateMutationStateDir)( + input.environment, + ); + const lifecycleStore = createFilePersistedEngineLifecycleStore(stateDir); + lifecycleStore.retireReleasedStateMutations(input.sandboxName); + if (!hasActivePersistedEngineStateMutationTarget(lifecycleStore, input.sandboxName)) { + return null; + } + return createSurfaceOwner(input, options, "existing").recover(input); +} + +function releaseSurface( + input: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, + completedLedgerSha256: string, + options: DockerStateMutationSurfaceOptions, +): void { + requireSurfaceContext(input); + const source = record(fence, "state mutation fence"); + const transactionId = boundedString(source.transactionId, SHA256, "fence transaction identity"); + const resultSha256 = boundedString(completedLedgerSha256, SHA256, "completed ledger digest"); + if ( + source.providerId !== PROVIDER_ID || + source.sandboxName !== input.sandboxName || + source.lifecycleGeneration !== input.sandbox.lifecycleGeneration + ) { + fail("state mutation fence does not match the sandbox release context"); + } + const stateDir = (options.resolveStateDir ?? resolveDockerStateMutationStateDir)( + input.environment, + ); + const lifecycleStore = createFilePersistedEngineLifecycleStore(stateDir); + if (lifecycleStore.isRetired(transactionId, resultSha256)) return; + createSurfaceOwner(input, options, "existing").release(input, fence, proof, resultSha256); +} + +/** Production Docker provider surface for one exact, durable runtime fence. */ +export function createDockerStateMutationSurface( + options: DockerStateMutationSurfaceOptions = {}, +): Extract { + const withDirectSandboxExecutionExclusion = + options.withDirectSandboxExecutionExclusion ?? withShieldsTransitionLock; + const acquireSurface = ( + input: RuntimeProviderStateMutationContext & { + readonly plan: RuntimeProviderPreparedStateMutationPlan; + }, + ): RuntimeProviderStateMutationFence => { + requireSurfaceContext(input); + const stateDir = (options.resolveStateDir ?? resolveDockerStateMutationStateDir)( + input.environment, + ); + const lifecycleStore = createFilePersistedEngineLifecycleStore(stateDir); + lifecycleStore.retireReleasedStateMutations(input.sandboxName); + if (hasActivePersistedEngineStateMutationTarget(lifecycleStore, input.sandboxName)) { + fail("OpenShell sandbox already has one unfinished state mutation"); + } + return createSurfaceOwner(input, options, "acquire").acquire(input); + }; + const surface: Extract = { + providerId: PROVIDER_ID, + supported: true, + contractVersion: RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION, + acquire: (input) => + withDirectSandboxExecutionExclusion( + input.sandboxName, + "Docker runtime-provider state mutation acquire", + () => acquireSurface(input), + ), + assertFenced: (input, fence) => + createSurfaceOwner(input, options, "existing").assertFenced(input, fence), + publish: (input, fence) => createSurfaceOwner(input, options, "existing").publish(input, fence), + rollback: (input, fence) => + createSurfaceOwner(input, options, "existing").rollback(input, fence), + activate: (input, fence) => + createSurfaceOwner(input, options, "existing").activate(input, fence), + release: (input, fence, proof, completedLedgerSha256) => + releaseSurface(input, fence, proof, completedLedgerSha256, options), + recover: (input) => + withDirectSandboxExecutionExclusion( + input.sandboxName, + "Docker runtime-provider state mutation recovery", + () => recoverSurface(input, options), + ), + }; + return Object.freeze(surface); +} diff --git a/src/lib/onboard/runtime-provider/docker.ts b/src/lib/onboard/runtime-provider/docker.ts index 0331ea1a4eb..dacc02615a9 100644 --- a/src/lib/onboard/runtime-provider/docker.ts +++ b/src/lib/onboard/runtime-provider/docker.ts @@ -35,6 +35,7 @@ import { type RuntimeProviderWorkloadProfile, } from "./contract"; import { createDockerLlamaCppHostLocalOperation } from "./docker-llama-cpp-operation"; +import { createDockerStateMutationSurface } from "./docker-state-mutation"; import { createDockerRuntimeProviderSnapshotSurface } from "./snapshot"; type DockerOpResult = { status?: number | null }; @@ -365,7 +366,7 @@ export function createDockerRuntimeProviderBundle( "workload-cleanup", ], }, - stateMutation: unsupported(providerId, futureReason), + stateMutation: createDockerStateMutationSurface(), bootstrap: createDockerManagedBootstrapSurface(providerId), snapshot: createDockerRuntimeProviderSnapshotSurface(providerId, { captureHostCommand: deps.captureHostCommand, diff --git a/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.test.ts b/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.test.ts index ffbf8298133..e2a7e839ece 100644 --- a/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.test.ts +++ b/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.test.ts @@ -1,11 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +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, vi } from "vitest"; +import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest"; +import { createDurableReceiptUnlinkInterruption } from "../../../../test/helpers/docker-state-mutation-harness"; import { type ContainerEngineCommandCapture, @@ -17,15 +19,27 @@ import { type PersistedEngineAuthorityStore, } from "./persisted-engine-authority"; import { + assertActivePersistedEngineStateMutation, + completePersistedEngineStateMutation, createFilePersistedEngineLifecycleStore, executePersistedEngineLifecycle, + executePersistedEngineStateMutation, + hasActivePersistedEngineStateMutationTarget, + loadPersistedEngineStateMutationIntent, normalizePersistedEngineLifecycleRecord, + normalizePersistedEngineStateMutationIntent, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE, type PersistedEngineLifecycleAction, type PersistedEngineLifecycleResource, parsePersistedEngineLifecycleRecord, + parsePersistedEngineStateMutationIntent, preparePersistedEngineLifecycle, + releaseCompletedPersistedEngineStateMutation, serializePersistedEngineLifecycleRecord, + serializePersistedEngineStateMutationIntent, } from "./persisted-engine-lifecycle"; const TRANSACTION_ID = "1".repeat(64); @@ -35,8 +49,50 @@ const RESULT_SHA256 = "4".repeat(64); const SOURCE_ID = `mxc-session:${"5".repeat(64)}`; const TARGET_ID = `mxc-session:${"6".repeat(64)}`; const AUTHORITY_ID = `mxc-endpoint:${"7".repeat(64)}`; +const SERIALIZED_STATE_MUTATION_PLAN = '{"schemaVersion":1,"intent":"protection-transition"}'; +const STATE_MUTATION_PLAN_SHA256 = createHash("sha256") + .update(SERIALIZED_STATE_MUTATION_PLAN, "utf8") + .digest("hex"); +const STATE_MUTATION_PROJECTION_SHA256 = "8".repeat(64); +const STATE_MUTATION_NONCE = "9".repeat(64); const roots: string[] = []; +function stateMutationIntent(serializedPlan = SERIALIZED_STATE_MUTATION_PLAN) { + return { + serializedPlan, + planSha256: createHash("sha256").update(serializedPlan, "utf8").digest("hex"), + projectionSha256: STATE_MUTATION_PROJECTION_SHA256, + nonce: STATE_MUTATION_NONCE, + }; +} + +function runtimeTargetClaimPath(root: string, targetId = TARGET_ID): string { + const identity = createHash("sha256") + .update("mxc", "utf8") + .update("\0", "utf8") + .update(targetId, "utf8") + .digest("hex"); + return path.join(root, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, "runtime-target-claims", identity); +} + +function stateMutationIntentPath(root: string, transactionId = TRANSACTION_ID): string { + return path.join( + root, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + transactionId, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE, + ); +} + +function stateMutationReleasePath(root: string, transactionId = TRANSACTION_ID): string { + return path.join( + root, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + transactionId, + PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE, + ); +} + function temporaryRoot(): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-engine-lifecycle-")); roots.push(root); @@ -64,19 +120,21 @@ function lifecycleEngine( function resources( action: PersistedEngineLifecycleAction, + targetId = TARGET_ID, ): readonly PersistedEngineLifecycleResource[] { switch (action) { case "snapshot-create": case "backup": return [{ role: "source", runtimeId: SOURCE_ID }]; case "recovery": - return [{ role: "target", runtimeId: TARGET_ID }]; + case "state-mutation": + return [{ role: "target", runtimeId: targetId }]; case "snapshot-clone": case "rebuild": case "restore": return [ { role: "source", runtimeId: SOURCE_ID }, - { role: "target", runtimeId: TARGET_ID }, + { role: "target", runtimeId: targetId }, ]; } } @@ -89,6 +147,8 @@ function harness( readonly authorityId?: string; readonly transactionId?: string; readonly runtimeStateSha256?: string; + readonly sandboxName?: string; + readonly targetId?: string; } = {}, ) { const root = options.root ?? temporaryRoot(); @@ -108,14 +168,15 @@ function harness( input: { transactionId: options.transactionId ?? TRANSACTION_ID, action, - sandboxName: "alpha", - resources: resources(action), + sandboxName: options.sandboxName ?? "alpha", + resources: resources(action, options.targetId), runtimeStateSha256: options.runtimeStateSha256 ?? RUNTIME_STATE_SHA256, providerId: "mxc", bindingSha256: BINDING_SHA256, engine, engineAuthorityStore, lifecycleStore, + ...(action === "state-mutation" ? { stateMutationIntent: stateMutationIntent() } : {}), }, }; } @@ -228,6 +289,761 @@ describe("persisted engine lifecycle", () => { await expect(first).resolves.toMatchObject({ value: "first" }); }); + it("keeps an active state mutation durable across restarted stores", async () => { + const capture = vi.fn(() => ({ status: 0, stdout: "fenced", stderr: "" })); + const runtime = harness({ action: "state-mutation", capture }); + const prepared = preparePersistedEngineLifecycle(runtime.input); + expect( + hasActivePersistedEngineStateMutationTarget( + runtime.lifecycleStore, + runtime.input.sandboxName, + TARGET_ID, + ), + ).toBe(true); + + const result = await executePersistedEngineStateMutation(runtime.input, (scope) => { + expect(scope.record).toMatchObject({ + action: "state-mutation", + phase: "prepared", + }); + scope.captureExact("target", (runtimeId) => ({ + args: ["fence", "--runtime", runtimeId], + targetIndex: 2, + })); + return "active"; + }); + + expect(prepared.phase).toBe("prepared"); + expect(result).toMatchObject({ + value: "active", + record: { action: "state-mutation", phase: "fence-established", resultSha256: null }, + }); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([result.record]); + expect(capture).toHaveBeenCalledExactlyOnceWith( + "mxcctl", + ["--endpoint", "unix:///run/mxc/runtime.sock", "fence", "--runtime", TARGET_ID], + 15_000, + ); + + const restartedInput = { + ...runtime.input, + engine: lifecycleEngine(), + engineAuthorityStore: createFilePersistedEngineAuthorityStore(runtime.root), + lifecycleStore: createFilePersistedEngineLifecycleStore(runtime.root), + }; + expect(assertActivePersistedEngineStateMutation(restartedInput)).toEqual(result.record); + expect( + hasActivePersistedEngineStateMutationTarget( + restartedInput.lifecycleStore, + runtime.input.sandboxName, + ), + ).toBe(true); + }); + + it("streams a bounded plan to a fixed helper under exact-runtime authority", async () => { + const capture = vi.fn(() => ({ status: 0, stdout: "accepted", stderr: "" })); + const runtime = harness({ action: "state-mutation", capture }); + const serializedPlan = Buffer.from('{"schemaVersion":2}\n', "utf8"); + preparePersistedEngineLifecycle(runtime.input); + + await executePersistedEngineStateMutation(runtime.input, (scope) => { + scope.captureExact( + "target", + (runtimeId) => ({ + args: ["exec", "-i", "--user", "root", runtimeId, "fixed-state-helper", "acquire"], + targetIndex: 4, + }), + 30_000, + serializedPlan, + ); + }); + + expect(capture).toHaveBeenCalledExactlyOnceWith( + "mxcctl", + [ + "--endpoint", + "unix:///run/mxc/runtime.sock", + "exec", + "-i", + "--user", + "root", + TARGET_ID, + "fixed-state-helper", + "acquire", + ], + 30_000, + serializedPlan, + ); + }); + + it("publishes the state-mutation intent before prepared authority and retries an interruption", () => { + const runtime = harness({ action: "state-mutation" }); + const events: string[] = []; + const recordStateMutationIntent = runtime.lifecycleStore.recordStateMutationIntent; + const interruptedStore = { + ...runtime.lifecycleStore, + recordStateMutationIntent(intent: Parameters[0]) { + const recorded = recordStateMutationIntent(intent); + events.push("ledger:intent"); + return recorded; + }, + create: vi.fn(() => { + events.push("ledger:prepared"); + throw new Error("injected exit before prepared publication"); + }), + }; + + expect(() => + preparePersistedEngineLifecycle({ ...runtime.input, lifecycleStore: interruptedStore }), + ).toThrow("before prepared publication"); + expect(events).toEqual(["ledger:intent", "ledger:prepared"]); + expect(runtime.lifecycleStore.load(TRANSACTION_ID)).toBeNull(); + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(false); + + const expectedIntent = normalizePersistedEngineStateMutationIntent({ + schemaVersion: PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + transactionId: TRANSACTION_ID, + ...stateMutationIntent(), + }); + const restarted = createFilePersistedEngineLifecycleStore(runtime.root); + expect(restarted.loadStateMutationIntent(TRANSACTION_ID)).toEqual(expectedIntent); + + const prepared = preparePersistedEngineLifecycle({ + ...runtime.input, + lifecycleStore: restarted, + }); + expect(prepared).toMatchObject({ action: "state-mutation", phase: "prepared" }); + expect(restarted.loadStateMutationIntent(TRANSACTION_ID)).toEqual(expectedIntent); + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(true); + }); + + it("records one canonical state-mutation intent without changing lifecycle record schema v1", () => { + const runtime = harness({ action: "state-mutation" }); + const first = preparePersistedEngineLifecycle(runtime.input); + const second = preparePersistedEngineLifecycle(runtime.input); + const intent = loadPersistedEngineStateMutationIntent(runtime.input); + const serialized = serializePersistedEngineStateMutationIntent(intent); + + expect(second).toEqual(first); + expect(intent).toEqual({ + schemaVersion: PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + transactionId: TRANSACTION_ID, + serializedPlan: SERIALIZED_STATE_MUTATION_PLAN, + planSha256: STATE_MUTATION_PLAN_SHA256, + projectionSha256: STATE_MUTATION_PROJECTION_SHA256, + nonce: STATE_MUTATION_NONCE, + }); + expect(fs.readFileSync(stateMutationIntentPath(runtime.root), "utf8")).toBe(serialized); + expect(parsePersistedEngineStateMutationIntent(serialized)).toEqual(intent); + expect(() => parsePersistedEngineStateMutationIntent(serialized.trim())).toThrow( + "not canonical", + ); + expect(first.schemaVersion).toBe(1); + expect(Object.keys(first).sort()).toEqual([ + "action", + "engineAuthority", + "phase", + "resources", + "resultSha256", + "runtimeStateSha256", + "sandboxName", + "schemaVersion", + "transactionId", + ]); + expect(serializePersistedEngineLifecycleRecord(first)).not.toMatch( + /nonce|planSha256|serializedPlan/u, + ); + + expect(() => + preparePersistedEngineLifecycle({ + ...runtime.input, + stateMutationIntent: stateMutationIntent( + '{"schemaVersion":1,"intent":"protection-transition","changed":true}', + ), + }), + ).toThrow("intent already exists with different content"); + expect(loadPersistedEngineStateMutationIntent(runtime.input)).toEqual(intent); + }); + + it("loads a state-mutation intent only under the exact lifecycle authority", () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + + expect(loadPersistedEngineStateMutationIntent(runtime.input).transactionId).toBe( + TRANSACTION_ID, + ); + expect(() => + loadPersistedEngineStateMutationIntent({ + ...runtime.input, + runtimeStateSha256: "a".repeat(64), + }), + ).toThrow("do not describe the same lifecycle authority"); + expect(() => + loadPersistedEngineStateMutationIntent({ ...runtime.input, providerId: "other" }), + ).toThrow("provider does not match"); + }); + + it("rejects private-file control violations for a state-mutation intent", () => { + const wrongMode = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(wrongMode.input); + fs.chmodSync(stateMutationIntentPath(wrongMode.root), 0o644); + expect(() => wrongMode.lifecycleStore.loadStateMutationIntent(TRANSACTION_ID)).toThrow( + "mode, link, or size checks", + ); + + const symlink = harness({ action: "state-mutation", transactionId: "a".repeat(64) }); + preparePersistedEngineLifecycle(symlink.input); + const intentPath = stateMutationIntentPath(symlink.root, "a".repeat(64)); + const outside = path.join(symlink.root, "outside-intent.json"); + fs.renameSync(intentPath, outside); + fs.symlinkSync(outside, intentPath); + expect(() => symlink.lifecycleStore.loadStateMutationIntent("a".repeat(64))).toThrow( + "must not be a symbolic link", + ); + }); + + it("rejects tampered and oversized state-mutation intent artifacts", () => { + const tampered = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(tampered.input); + const intentPath = stateMutationIntentPath(tampered.root); + const durable = JSON.parse(fs.readFileSync(intentPath, "utf8")) as Record; + fs.writeFileSync( + intentPath, + `${JSON.stringify({ ...durable, serializedPlan: `${SERIALIZED_STATE_MUTATION_PLAN} ` })}\n`, + { mode: 0o600 }, + ); + expect(() => tampered.lifecycleStore.loadStateMutationIntent(TRANSACTION_ID)).toThrow( + "plan digest does not match", + ); + + const oversized = harness({ action: "state-mutation", transactionId: "b".repeat(64) }); + const oversizedDirectory = path.dirname( + stateMutationIntentPath(oversized.root, "b".repeat(64)), + ); + fs.mkdirSync(oversizedDirectory, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + stateMutationIntentPath(oversized.root, "b".repeat(64)), + "x".repeat(128 * 1024 + 1), + { mode: 0o600 }, + ); + expect(() => oversized.lifecycleStore.loadStateMutationIntent("b".repeat(64))).toThrow( + "mode, link, or size checks", + ); + }); + + it("rejects prepared state-mutation authority without a durable intent", () => { + const runtime = harness({ action: "state-mutation" }); + const prepared = normalizePersistedEngineLifecycleRecord({ + schemaVersion: 1, + transactionId: TRANSACTION_ID, + action: "state-mutation", + phase: "prepared", + sandboxName: runtime.input.sandboxName, + resources: runtime.input.resources, + runtimeStateSha256: runtime.input.runtimeStateSha256, + engineAuthority: runtime.authority, + resultSha256: null, + }); + + expect(() => runtime.lifecycleStore.create(prepared)).toThrow( + "preparation requires its exact durable intent", + ); + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(false); + + const directory = path.dirname(stateMutationIntentPath(runtime.root)); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(directory, "prepared.json"), + serializePersistedEngineLifecycleRecord(prepared), + { + mode: 0o600, + }, + ); + expect(() => runtime.lifecycleStore.load(TRANSACTION_ID)).toThrow( + "prepared state mutation is missing its exact intent", + ); + }); + + it("does not treat an interrupted fence callback as an established external fence", async () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + + expect(() => + executePersistedEngineStateMutation(runtime.input, () => { + throw new Error("injected controller exit before fence proof"); + }), + ).toThrow("before fence proof"); + + expect(runtime.lifecycleStore.load(TRANSACTION_ID)?.phase).toBe("prepared"); + expect(() => assertActivePersistedEngineStateMutation(runtime.input)).toThrow( + "fence is not established", + ); + + expect(executePersistedEngineStateMutation(runtime.input, () => "revalidated")).toMatchObject({ + value: "revalidated", + record: { phase: "fence-established" }, + }); + }); + + it("requires explicit activation completion before retiring a state mutation", async () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + + expect(() => + completePersistedEngineStateMutation( + runtime.input, + () => ({ + resultSha256: RESULT_SHA256, + value: "unsafe", + }), + () => undefined, + ), + ).toThrow("requires an established fence"); + + await expect( + executePersistedEngineLifecycle(runtime.input, () => ({ + resultSha256: RESULT_SHA256, + value: "unsafe", + })), + ).rejects.toThrow("must remain active until explicit activation completion"); + + await executePersistedEngineStateMutation(runtime.input, () => "published"); + const release = vi.fn((_scope, receipt) => { + expect(receipt).toMatchObject({ phase: "completed", resultSha256: RESULT_SHA256 }); + }); + const completed = await completePersistedEngineStateMutation( + runtime.input, + (scope) => { + expect(scope.record.phase).toBe("fence-established"); + return { resultSha256: RESULT_SHA256, value: "activated" }; + }, + release, + ); + + expect(completed).toMatchObject({ + value: "activated", + record: { action: "state-mutation", phase: "completed", resultSha256: RESULT_SHA256 }, + }); + expect(release).toHaveBeenCalledOnce(); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + }); + + it("keeps the exact target claimed until a completed activation releases its provider fence", async () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + await executePersistedEngineStateMutation(runtime.input, () => "published"); + + expect(() => + completePersistedEngineStateMutation( + runtime.input, + () => ({ resultSha256: RESULT_SHA256, value: "activated" }), + () => { + throw new Error("injected controller exit before provider fence release"); + }, + ), + ).toThrow("before provider fence release"); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([ + expect.objectContaining({ phase: "completed", resultSha256: RESULT_SHA256 }), + ]); + expect(() => runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256)).toThrow( + "finalized provider release receipt", + ); + + const competing = harness({ + root: runtime.root, + action: "recovery", + transactionId: "8".repeat(64), + }); + expect(() => preparePersistedEngineLifecycle(competing.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + + const released = await releaseCompletedPersistedEngineStateMutation( + runtime.input, + (scope, receipt) => { + expect(scope.record).toEqual(receipt); + return Promise.resolve("released"); + }, + ); + expectTypeOf(released.value).toEqualTypeOf(); + expect(released).toMatchObject({ value: "released", record: { phase: "completed" } }); + expect(runtime.lifecycleStore.listUnfinished()).toEqual([]); + expect( + hasActivePersistedEngineStateMutationTarget( + runtime.lifecycleStore, + runtime.input.sandboxName, + TARGET_ID, + ), + ).toBe(false); + runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256); + expect(runtime.lifecycleStore.load(TRANSACTION_ID)).toBeNull(); + }); + + it("reacquires a missing prepared claim before replaying the exact helper", () => { + const runtime = harness({ action: "state-mutation" }); + const prepared = preparePersistedEngineLifecycle(runtime.input); + fs.unlinkSync(runtimeTargetClaimPath(runtime.root)); + + expect(runtime.lifecycleStore.listUnfinished()).toEqual([prepared]); + const replay = vi.fn(() => { + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(true); + return "replayed"; + }); + + expect(executePersistedEngineStateMutation(runtime.input, replay)).toMatchObject({ + value: "replayed", + record: { phase: "fence-established" }, + }); + expect(replay).toHaveBeenCalledOnce(); + }); + + it("reacquires a missing completed claim before retrying provider release", () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + executePersistedEngineStateMutation(runtime.input, () => "fenced"); + expect(() => + completePersistedEngineStateMutation( + runtime.input, + () => ({ resultSha256: RESULT_SHA256, value: "activated" }), + () => { + throw new Error("injected provider release interruption"); + }, + ), + ).toThrow("provider release interruption"); + fs.unlinkSync(runtimeTargetClaimPath(runtime.root)); + + const release = vi.fn(() => { + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(true); + return "released"; + }); + expect(releaseCompletedPersistedEngineStateMutation(runtime.input, release)).toMatchObject({ + value: "released", + record: { phase: "completed", resultSha256: RESULT_SHA256 }, + }); + expect(release).toHaveBeenCalledOnce(); + expect(fs.existsSync(stateMutationReleasePath(runtime.root))).toBe(true); + expect(fs.existsSync(runtimeTargetClaimPath(runtime.root))).toBe(false); + }); + + it("uses a durable release receipt to unlink a retained claim without another provider callback", () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + executePersistedEngineStateMutation(runtime.input, () => "fenced"); + const claimPath = runtimeTargetClaimPath(runtime.root); + const originalUnlink = fs.unlinkSync.bind(fs); + const interruption = createDurableReceiptUnlinkInterruption( + originalUnlink, + claimPath, + stateMutationReleasePath(runtime.root), + ); + const unlink = vi.spyOn(fs, "unlinkSync").mockImplementation(interruption.unlink); + + expect(() => + completePersistedEngineStateMutation( + runtime.input, + () => ({ resultSha256: RESULT_SHA256, value: "activated" }), + () => undefined, + ), + ).toThrow("before claim unlink"); + unlink.mockRestore(); + + expect(fs.existsSync(stateMutationReleasePath(runtime.root))).toBe(true); + expect(interruption.receiptWasDurable()).toBe(true); + expect(fs.existsSync(claimPath)).toBe(true); + const duplicateRelease = vi.fn(() => { + throw new Error("provider callback must not be retried"); + }); + expect( + releaseCompletedPersistedEngineStateMutation(runtime.input, duplicateRelease), + ).toMatchObject({ record: { phase: "completed" }, value: undefined }); + expect(duplicateRelease).not.toHaveBeenCalled(); + expect(fs.existsSync(claimPath)).toBe(false); + + runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256); + expect(runtime.lifecycleStore.isRetired(TRANSACTION_ID, RESULT_SHA256)).toBe(true); + expect(runtime.lifecycleStore.load(TRANSACTION_ID)).toBeNull(); + expect(() => runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256)).not.toThrow(); + }); + + it("fails closed when the provider release receipt is tampered", () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + executePersistedEngineStateMutation(runtime.input, () => "fenced"); + completePersistedEngineStateMutation( + runtime.input, + () => ({ resultSha256: RESULT_SHA256, value: "activated" }), + () => undefined, + ); + const releasePath = stateMutationReleasePath(runtime.root); + const receipt = JSON.parse(fs.readFileSync(releasePath, "utf8")) as Record; + fs.writeFileSync( + releasePath, + `${JSON.stringify({ ...receipt, completedRecordSha256: "f".repeat(64) })}\n`, + { mode: 0o600 }, + ); + + expect(() => createFilePersistedEngineLifecycleStore(runtime.root).listUnfinished()).toThrow( + "provider release receipt does not match", + ); + }); + + it("retires only after finalized provider release gives up execution ownership", () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + executePersistedEngineStateMutation(runtime.input, () => "fenced"); + const lease = runtime.lifecycleStore.acquireMutationExecution(TRANSACTION_ID); + runtime.lifecycleStore.complete(lease, RESULT_SHA256); + runtime.lifecycleStore.finalizeStateMutationRelease(lease, RESULT_SHA256); + + expect(() => runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256)).toThrow( + "released mutation execution ownership", + ); + runtime.lifecycleStore.releaseMutationExecution(lease); + runtime.lifecycleStore.retire(TRANSACTION_ID, RESULT_SHA256); + expect(runtime.lifecycleStore.isRetired(TRANSACTION_ID, RESULT_SHA256)).toBe(true); + }); + + it("rejects drift from an active state mutation's exact authority and runtime identity", async () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + await executePersistedEngineStateMutation(runtime.input, () => undefined); + const restartedInput = { + ...runtime.input, + engineAuthorityStore: createFilePersistedEngineAuthorityStore(runtime.root), + lifecycleStore: createFilePersistedEngineLifecycleStore(runtime.root), + }; + + expect(() => + assertActivePersistedEngineStateMutation({ ...restartedInput, providerId: "other" }), + ).toThrow("provider does not match"); + expect(() => + assertActivePersistedEngineStateMutation({ + ...restartedInput, + resources: [{ role: "target", runtimeId: `mxc-session:${"8".repeat(64)}` }], + }), + ).toThrow("do not describe the same lifecycle authority"); + }); + + it("admits only one concurrent executor for an active state mutation", async () => { + const runtime = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(runtime.input); + let releaseFirst: (() => void) | undefined; + let announceFirst: (() => void) | undefined; + const firstEntered = new Promise((resolve) => { + announceFirst = resolve; + }); + const holdFirst = new Promise((resolve) => { + releaseFirst = resolve; + }); + const firstMutation = vi.fn(async () => { + announceFirst?.(); + await holdFirst; + return "first"; + }); + const competingMutation = vi.fn(() => "competing"); + + const first = executePersistedEngineStateMutation(runtime.input, firstMutation); + await firstEntered; + expect(() => executePersistedEngineStateMutation(runtime.input, competingMutation)).toThrow( + "already owned by a live process", + ); + expect(firstMutation).toHaveBeenCalledOnce(); + expect(competingMutation).not.toHaveBeenCalled(); + + releaseFirst?.(); + await expect(first).resolves.toMatchObject({ + value: "first", + record: { phase: "fence-established" }, + }); + }); + + it("rejects a second unfinished state mutation for the same exact target", async () => { + const first = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(first.input); + await executePersistedEngineStateMutation(first.input, () => undefined); + const second = harness({ + root: first.root, + action: "state-mutation", + transactionId: "8".repeat(64), + }); + + expect(() => preparePersistedEngineLifecycle(second.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + expect( + fs.existsSync( + path.join( + first.root, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + "8".repeat(64), + "prepared.json", + ), + ), + ).toBe(false); + expect(() => second.lifecycleStore.authorizeMutation("8".repeat(64))).toThrow( + "mutation authorization requires prepared authority", + ); + const renamedAlias = harness({ + root: first.root, + action: "state-mutation", + transactionId: "9".repeat(64), + sandboxName: "renamed-alpha", + }); + expect(() => preparePersistedEngineLifecycle(renamedAlias.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + expect(second.lifecycleStore.listUnfinished()).toEqual([ + expect.objectContaining({ transactionId: TRANSACTION_ID, phase: "fence-established" }), + ]); + }); + + it("does not let inherited JSON hooks alias distinct runtime target claims", () => { + const root = temporaryRoot(); + const first = harness({ root, action: "state-mutation" }); + const second = harness({ + root, + action: "state-mutation", + transactionId: "8".repeat(64), + targetId: `mxc-session:${"9".repeat(64)}`, + }); + const objectToJson = Object.getOwnPropertyDescriptor(Object.prototype, "toJSON"); + try { + Object.defineProperty(Object.prototype, "toJSON", { + configurable: true, + value(this: Record) { + return Object.keys(this).sort().join(",") === "providerId,runtimeId" + ? "polluted-target-claim" + : this; + }, + }); + expect(preparePersistedEngineLifecycle(first.input).phase).toBe("prepared"); + expect(preparePersistedEngineLifecycle(second.input).phase).toBe("prepared"); + expect(first.lifecycleStore.listUnfinished()).toEqual([ + expect.objectContaining({ transactionId: TRANSACTION_ID }), + expect.objectContaining({ transactionId: "8".repeat(64) }), + ]); + } finally { + objectToJson === undefined + ? Reflect.deleteProperty(Object.prototype, "toJSON") + : Object.defineProperty(Object.prototype, "toJSON", objectToJson); + } + }); + + it("excludes recovery and state mutation in both exact-target orderings", async () => { + const mutationFirst = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(mutationFirst.input); + await executePersistedEngineStateMutation(mutationFirst.input, () => undefined); + const recoverySecond = harness({ + root: mutationFirst.root, + action: "recovery", + transactionId: "8".repeat(64), + }); + expect(() => preparePersistedEngineLifecycle(recoverySecond.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + + const recoveryFirst = harness({ action: "recovery", transactionId: "9".repeat(64) }); + preparePersistedEngineLifecycle(recoveryFirst.input); + const mutationSecond = harness({ + root: recoveryFirst.root, + action: "state-mutation", + transactionId: "a".repeat(64), + }); + expect(() => preparePersistedEngineLifecycle(mutationSecond.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + }); + + it("recovers an exact-target claim when its prepared phase was interrupted", () => { + const first = harness({ action: "state-mutation" }); + const prepared = preparePersistedEngineLifecycle(first.input); + fs.rmSync(path.join(first.root, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, TRANSACTION_ID), { + recursive: true, + }); + const restartedStore = createFilePersistedEngineLifecycleStore(first.root); + + expect(restartedStore.listUnfinished()).toEqual([prepared]); + expect( + preparePersistedEngineLifecycle({ ...first.input, lifecycleStore: restartedStore }), + ).toEqual(prepared); + + const competing = harness({ + root: first.root, + action: "state-mutation", + transactionId: "8".repeat(64), + }); + expect(() => preparePersistedEngineLifecycle(competing.input)).toThrow( + "exact runtime target already has an unfinished transaction", + ); + }); + + it("never lets a competitor reclaim a claim-only interrupted transaction", () => { + const crashed = harness({ action: "state-mutation" }); + const prepared = preparePersistedEngineLifecycle(crashed.input); + fs.rmSync(path.join(crashed.root, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, TRANSACTION_ID), { + recursive: true, + }); + const replacement = harness({ + root: crashed.root, + action: "state-mutation", + transactionId: "8".repeat(64), + }); + + expect(() => preparePersistedEngineLifecycle(replacement.input)).toThrow( + "runtime target claim is missing its prepared authority", + ); + expect(() => replacement.lifecycleStore.authorizeMutation("8".repeat(64))).toThrow( + "mutation authorization requires prepared authority", + ); + expect(preparePersistedEngineLifecycle(crashed.input)).toEqual(prepared); + expect(replacement.lifecycleStore.listUnfinished()).toEqual([prepared]); + }); + + it("requires the exact target claim for authorization and execution", () => { + const authorization = harness({ action: "state-mutation" }); + preparePersistedEngineLifecycle(authorization.input); + fs.unlinkSync(runtimeTargetClaimPath(authorization.root)); + + expect(() => authorization.lifecycleStore.authorizeMutation(TRANSACTION_ID)).toThrow( + "mutation authorization requires the exact runtime target claim", + ); + expect(authorization.lifecycleStore.listUnfinished()).toEqual([ + expect.objectContaining({ transactionId: TRANSACTION_ID, phase: "prepared" }), + ]); + + const execution = harness({ action: "state-mutation", transactionId: "8".repeat(64) }); + preparePersistedEngineLifecycle(execution.input); + execution.lifecycleStore.authorizeMutation("8".repeat(64)); + const lease = execution.lifecycleStore.acquireMutationExecution("8".repeat(64)); + fs.unlinkSync(runtimeTargetClaimPath(execution.root)); + + expect(() => execution.lifecycleStore.acquireMutationExecution("8".repeat(64))).toThrow( + "mutation execution requires the exact runtime target claim", + ); + expect(() => execution.lifecycleStore.assertMutationExecution(lease)).toThrow( + "mutation execution requires the exact runtime target claim", + ); + expect(() => execution.lifecycleStore.establishStateMutationFence(lease)).toThrow( + "external fence establishment requires the exact runtime target claim", + ); + execution.lifecycleStore.releaseMutationExecution(lease); + + const completion = harness({ action: "state-mutation", transactionId: "9".repeat(64) }); + preparePersistedEngineLifecycle(completion.input); + completion.lifecycleStore.authorizeMutation("9".repeat(64)); + const completionLease = completion.lifecycleStore.acquireMutationExecution("9".repeat(64)); + completion.lifecycleStore.establishStateMutationFence(completionLease); + fs.unlinkSync(runtimeTargetClaimPath(completion.root)); + + expect(() => assertActivePersistedEngineStateMutation(completion.input)).toThrow( + "active state mutation requires the exact runtime target claim", + ); + expect(() => completion.lifecycleStore.complete(completionLease, RESULT_SHA256)).toThrow( + "completion requires the exact runtime target claim", + ); + completion.lifecycleStore.releaseMutationExecution(completionLease); + }); + it("reconstructs mutation-authorized recovery after process-local state is rebuilt", async () => { const firstCapture = vi.fn(() => { throw new Error("injected process crash after exact stop"); @@ -392,6 +1208,39 @@ describe("persisted engine lifecycle", () => { expect(runtime.lifecycleStore.listUnfinished()).toEqual([prepared]); }); + it("repairs crash-left post-link phase and target-claim publications", () => { + const runtime = harness({ action: "state-mutation" }); + const prepared = preparePersistedEngineLifecycle(runtime.input); + const transactionDirectory = path.join( + runtime.root, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + TRANSACTION_ID, + ); + const preparedPath = path.join(transactionDirectory, "prepared.json"); + const claimPath = runtimeTargetClaimPath(runtime.root); + const temporaryIdentity = "01234567-89ab-4cde-8fab-0123456789ab"; + const preparedTemporary = path.join( + transactionDirectory, + `.prepared.json.${temporaryIdentity}.tmp`, + ); + const claimTemporary = path.join( + path.dirname(claimPath), + `.${path.basename(claimPath)}.${temporaryIdentity}.tmp`, + ); + fs.linkSync(preparedPath, preparedTemporary); + fs.linkSync(claimPath, claimTemporary); + expect(fs.lstatSync(preparedPath).nlink).toBe(2); + expect(fs.lstatSync(claimPath).nlink).toBe(2); + + const restarted = createFilePersistedEngineLifecycleStore(runtime.root); + expect(restarted.load(TRANSACTION_ID)).toEqual(prepared); + expect(restarted.listUnfinished()).toEqual([prepared]); + expect(fs.existsSync(preparedTemporary)).toBe(false); + expect(fs.existsSync(claimTemporary)).toBe(false); + expect(fs.lstatSync(preparedPath).nlink).toBe(1); + expect(fs.lstatSync(claimPath).nlink).toBe(1); + }); + it("preserves a mutation failure when execution-lease release also fails", async () => { const runtime = harness(); preparePersistedEngineLifecycle(runtime.input); diff --git a/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.ts b/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.ts index 2de6e4069aa..4edb9c57d8b 100644 --- a/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.ts +++ b/src/lib/onboard/runtime-provider/persisted-engine-lifecycle.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; @@ -20,6 +20,9 @@ import { export const PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION = 1 as const; export const PERSISTED_ENGINE_LIFECYCLE_DIRECTORY = "runtime-provider-lifecycle"; +export const PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION = 1 as const; +export const PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE = "state-mutation-intent.json"; +export const PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE = "provider-release-finalized.json"; export type PersistedEngineLifecycleAction = | "snapshot-create" @@ -27,9 +30,14 @@ export type PersistedEngineLifecycleAction = | "rebuild" | "backup" | "restore" - | "recovery"; + | "recovery" + | "state-mutation"; -export type PersistedEngineLifecyclePhase = "prepared" | "mutation-authorized" | "completed"; +export type PersistedEngineLifecyclePhase = + | "prepared" + | "mutation-authorized" + | "fence-established" + | "completed"; export type PersistedEngineLifecycleResourceRole = "source" | "target"; @@ -52,14 +60,52 @@ export interface PersistedEngineLifecycleRecord { readonly resultSha256: string | null; } +export interface PersistedEngineStateMutationIntentInput { + /** Canonical bounded provider plan that can reconstruct the exact acquire request. */ + readonly serializedPlan: string; + readonly planSha256: string; + readonly projectionSha256: string; + readonly nonce: string; +} + +export interface PersistedEngineStateMutationIntent + extends PersistedEngineStateMutationIntentInput { + readonly schemaVersion: typeof PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION; + readonly transactionId: string; +} + +interface PersistedEngineStateMutationReleaseReceipt { + readonly schemaVersion: typeof PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION; + readonly transactionId: string; + readonly resultSha256: string; + readonly completedRecordSha256: string; +} + export interface PersistedEngineLifecycleStore { readonly load: (transactionId: string) => PersistedEngineLifecycleRecord | null; + /** Load a write-once intent, including an intent published before prepared authority. */ + readonly loadStateMutationIntent: ( + transactionId: string, + ) => PersistedEngineStateMutationIntent | null; + /** Publish the exact intent before any state-mutation prepared authority. */ + readonly recordStateMutationIntent: ( + intent: PersistedEngineStateMutationIntent, + ) => PersistedEngineStateMutationIntent; readonly listUnfinished: () => readonly PersistedEngineLifecycleRecord[]; readonly create: (record: PersistedEngineLifecycleRecord) => PersistedEngineLifecycleRecord; readonly authorizeMutation: (transactionId: string) => PersistedEngineLifecycleRecord; + readonly assertStateMutationTargetClaim: ( + transactionId: string, + ) => PersistedEngineLifecycleRecord; + readonly establishStateMutationFence: ( + lease: PersistedEngineLifecycleExecutionLease, + ) => PersistedEngineLifecycleRecord; /** * Acquire one process-owned execution lease before invoking a mutation. - * A dead or PID-recycled owner may be recovered, but the exact live owner wins. + * State-mutation preparation may hold this lease before publishing mutation + * authority so an external fence marker can be established without a crash + * window. A dead or PID-recycled owner may be recovered, but the exact live + * owner wins. */ readonly acquireMutationExecution: ( transactionId: string, @@ -70,8 +116,25 @@ export interface PersistedEngineLifecycleStore { lease: PersistedEngineLifecycleExecutionLease, resultSha256: string, ) => PersistedEngineLifecycleRecord; + /** + * Retire the exact-target claim only after the provider's external fence was + * released from the already-durable state-mutation completion receipt. + */ + readonly finalizeStateMutationRelease: ( + lease: PersistedEngineLifecycleExecutionLease, + resultSha256: string, + ) => PersistedEngineLifecycleRecord; + /** True only after provider release returned and its exact receipt is durable. */ + readonly isStateMutationReleaseFinalized: ( + transactionId: string, + resultSha256: string, + ) => boolean; /** Retire only the exact completed receipt; a durable tombstone prevents ID reuse. */ readonly retire: (transactionId: string, resultSha256: string) => void; + /** Finish safe cleanup left after a released mutation lost its final response. */ + readonly retireReleasedStateMutations: (sandboxName: string) => void; + /** Match only an exact durable retirement receipt. */ + readonly isRetired: (transactionId: string, resultSha256: string) => boolean; } export interface PreparePersistedEngineLifecycleInput { @@ -85,6 +148,8 @@ export interface PreparePersistedEngineLifecycleInput { readonly engine: ContainerEngine; readonly engineAuthorityStore: PersistedEngineAuthorityStore; readonly lifecycleStore: PersistedEngineLifecycleStore; + /** Required only for state-mutation preparation. */ + readonly stateMutationIntent?: PersistedEngineStateMutationIntentInput; } export type PersistedEngineLifecycleExecutionInput = PreparePersistedEngineLifecycleInput; @@ -113,6 +178,7 @@ export interface AuthorizedPersistedEngineLifecycle { role: PersistedEngineLifecycleResourceRole, buildCommand: (runtimeId: string) => PersistedEngineLifecycleExactCommand, timeoutMs?: number, + commandInput?: Buffer, ) => ContainerEngineCommandResult; readonly captureHostExact: ( role: PersistedEngineLifecycleResourceRole, @@ -129,6 +195,9 @@ export interface PersistedEngineLifecycleMutationResult { const DIRECTORY_MODE = 0o700; const FILE_MODE = 0o600; const MAX_RECORD_BYTES = 32 * 1024; +const MAX_STATE_MUTATION_PLAN_BYTES = 64 * 1024; +const MAX_STATE_MUTATION_INTENT_BYTES = 128 * 1024; +const MAX_STATE_MUTATION_NONCE_BYTES = 512; const MAX_ARGUMENTS = 512; const MAX_ARGUMENT_BYTES = 16 * 1024; const SHA256 = /^[a-f0-9]{64}$/u; @@ -143,20 +212,23 @@ const ACTIONS = new Set([ "backup", "restore", "recovery", + "state-mutation", ]); const PHASES = new Set([ "prepared", "mutation-authorized", + "fence-established", "completed", ]); -const PHASE_FILES = ["prepared", "mutation-authorized", "completed"] as const; +const PHASE_FILES = ["prepared", "mutation-authorized", "fence-established", "completed"] as const; const EXECUTION_LEASE_FILE = "mutation-execution.json"; const EXECUTION_RECOVERY_FILE = ".mutation-execution-recovery"; -const CURRENT_PROCESS_START_IDENTITY = - readMcpLockProcessIdentity(process.pid, true) ?? - `unverified-self:${String(process.pid)}:${randomUUID()}`; +const RUNTIME_TARGET_CLAIM_DIRECTORY = "runtime-target-claims"; +let currentProcessStartIdentityValue: string | undefined; const TRANSACTION_PUBLISH_TARGETS = [ ...PHASE_FILES.map((phase) => `${phase}.json`), + PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE, + PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE, EXECUTION_LEASE_FILE, EXECUTION_RECOVERY_FILE, ] as const; @@ -172,6 +244,7 @@ const REQUIRED_ROLES: Readonly< backup: resourceRoles("source"), restore: resourceRoles("source", "target"), recovery: resourceRoles("target"), + "state-mutation": resourceRoles("target"), }); function fail(message: string): never { @@ -264,6 +337,9 @@ export function normalizePersistedEngineLifecycleRecord( } const action = exactAction(record.action); const phase = exactPhase(record.phase); + if (phase === "fence-established" && action !== "state-mutation") { + fail("only state-mutation may establish an external fence"); + } const resultSha256 = record.resultSha256 === null ? null @@ -321,6 +397,194 @@ export function parsePersistedEngineLifecycleRecord( return record; } +function exactStateMutationPlan(value: unknown): string { + if ( + typeof value !== "string" || + value.length === 0 || + CONTROL_CHARACTERS.test(value) || + Buffer.byteLength(value, "utf8") > MAX_STATE_MUTATION_PLAN_BYTES || + Buffer.from(value, "utf8").toString("utf8") !== value + ) { + fail("state-mutation plan is empty, malformed, or too large"); + } + return value; +} + +function exactStateMutationNonce(value: unknown): string { + if ( + typeof value !== "string" || + value.length === 0 || + CONTROL_CHARACTERS.test(value) || + Buffer.byteLength(value, "utf8") > MAX_STATE_MUTATION_NONCE_BYTES || + Buffer.from(value, "utf8").toString("utf8") !== value + ) { + fail("state-mutation nonce is empty, malformed, or too large"); + } + return value; +} + +export function normalizePersistedEngineStateMutationIntent( + value: unknown, +): PersistedEngineStateMutationIntent { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + fail("state-mutation intent must be an object"); + } + const intent = value as Record; + const expectedKeys = [ + "nonce", + "planSha256", + "projectionSha256", + "schemaVersion", + "serializedPlan", + "transactionId", + ]; + if ( + Object.keys(intent).sort().join(",") !== expectedKeys.join(",") || + intent.schemaVersion !== PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION + ) { + fail("state-mutation intent schema is unsupported"); + } + const serializedPlan = exactStateMutationPlan(intent.serializedPlan); + const planSha256 = exactSha256(intent.planSha256, "state-mutation plan digest"); + if (createHash("sha256").update(serializedPlan, "utf8").digest("hex") !== planSha256) { + fail("state-mutation plan digest does not match its serialized plan"); + } + return Object.freeze({ + schemaVersion: PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + transactionId: exactSha256(intent.transactionId, "state-mutation transaction identity"), + serializedPlan, + planSha256, + projectionSha256: exactSha256(intent.projectionSha256, "state-mutation projection digest"), + nonce: exactStateMutationNonce(intent.nonce), + }); +} + +export function serializePersistedEngineStateMutationIntent( + value: PersistedEngineStateMutationIntent, +): string { + const intent = normalizePersistedEngineStateMutationIntent(value); + const transport: Record = Object.create(null); + transport.schemaVersion = intent.schemaVersion; + transport.transactionId = intent.transactionId; + transport.serializedPlan = intent.serializedPlan; + transport.planSha256 = intent.planSha256; + transport.projectionSha256 = intent.projectionSha256; + transport.nonce = intent.nonce; + const serialized = `${JSON.stringify(transport)}\n`; + if (Buffer.byteLength(serialized, "utf8") > MAX_STATE_MUTATION_INTENT_BYTES) { + fail("serialized state-mutation intent exceeds its bounded transport"); + } + return serialized; +} + +export function parsePersistedEngineStateMutationIntent( + serialized: string, +): PersistedEngineStateMutationIntent { + if ( + serialized.length === 0 || + serialized.includes("\0") || + Buffer.byteLength(serialized, "utf8") > MAX_STATE_MUTATION_INTENT_BYTES + ) { + fail("serialized state-mutation intent is empty or too large"); + } + let parsed: unknown; + try { + parsed = JSON.parse(serialized); + } catch { + fail("serialized state-mutation intent is not valid JSON"); + } + const intent = normalizePersistedEngineStateMutationIntent(parsed); + if (serializePersistedEngineStateMutationIntent(intent) !== serialized) { + fail("serialized state-mutation intent is not canonical"); + } + return intent; +} + +function completedRecordSha256(record: PersistedEngineLifecycleRecord): string { + if (record.action !== "state-mutation" || record.phase !== "completed") { + fail("provider release receipt requires one completed state mutation"); + } + return createHash("sha256") + .update(serializePersistedEngineLifecycleRecord(record), "utf8") + .digest("hex"); +} + +function normalizeStateMutationReleaseReceipt( + value: unknown, +): PersistedEngineStateMutationReleaseReceipt { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + fail("provider release receipt must be an object"); + } + const receipt = value as Record; + if ( + Object.keys(receipt).sort().join(",") !== + "completedRecordSha256,resultSha256,schemaVersion,transactionId" || + receipt.schemaVersion !== PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION + ) { + fail("provider release receipt schema is unsupported"); + } + return Object.freeze({ + schemaVersion: PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION, + transactionId: exactSha256(receipt.transactionId, "provider release transaction identity"), + resultSha256: exactSha256(receipt.resultSha256, "provider release completion digest"), + completedRecordSha256: exactSha256( + receipt.completedRecordSha256, + "provider release completed-record digest", + ), + }); +} + +function serializeStateMutationReleaseReceipt( + value: PersistedEngineStateMutationReleaseReceipt, +): string { + const receipt = normalizeStateMutationReleaseReceipt(value); + const transport: Record = Object.create(null); + transport.schemaVersion = receipt.schemaVersion; + transport.transactionId = receipt.transactionId; + transport.resultSha256 = receipt.resultSha256; + transport.completedRecordSha256 = receipt.completedRecordSha256; + return `${JSON.stringify(transport)}\n`; +} + +function parseStateMutationReleaseReceipt( + serialized: string, +): PersistedEngineStateMutationReleaseReceipt { + let parsed: unknown; + try { + parsed = JSON.parse(serialized); + } catch { + fail("provider release receipt is not valid JSON"); + } + const receipt = normalizeStateMutationReleaseReceipt(parsed); + if (serializeStateMutationReleaseReceipt(receipt) !== serialized) { + fail("provider release receipt is not canonical"); + } + return receipt; +} + +function stateMutationIntentForTransaction( + transactionId: string, + value: unknown, +): PersistedEngineStateMutationIntent { + if ( + typeof value !== "object" || + value === null || + Array.isArray(value) || + Object.keys(value).sort().join(",") !== "nonce,planSha256,projectionSha256,serializedPlan" + ) { + fail("state-mutation intent input schema is unsupported"); + } + const intent = value as Record; + return normalizePersistedEngineStateMutationIntent({ + schemaVersion: PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + transactionId, + serializedPlan: intent.serializedPlan, + planSha256: intent.planSha256, + projectionSha256: intent.projectionSha256, + nonce: intent.nonce, + }); +} + function normalizeExecutionLease(value: unknown): PersistedEngineLifecycleExecutionLease { if (typeof value !== "object" || value === null || Array.isArray(value)) { fail("mutation execution lease must be an object"); @@ -379,7 +643,9 @@ function processIsAlive(pid: number): boolean { } function currentProcessStartIdentity(): string { - return CURRENT_PROCESS_START_IDENTITY; + return (currentProcessStartIdentityValue ??= + readMcpLockProcessIdentity(process.pid, true) ?? + `unverified-self:${String(process.pid)}:${randomUUID()}`); } function exactExecutionOwnerIsAlive(lease: PersistedEngineLifecycleExecutionLease): boolean { @@ -387,7 +653,7 @@ function exactExecutionOwnerIsAlive(lease: PersistedEngineLifecycleExecutionLeas const currentIdentity = readMcpLockProcessIdentity(lease.ownerPid, true); if (currentIdentity !== null) return currentIdentity === lease.ownerStartIdentity; return ( - lease.ownerPid !== process.pid || lease.ownerStartIdentity === CURRENT_PROCESS_START_IDENTITY + lease.ownerPid !== process.pid || lease.ownerStartIdentity === currentProcessStartIdentity() ); } @@ -427,7 +693,57 @@ function sameStableMetadata(left: fs.BigIntStats, right: fs.BigIntStats): boolea ); } -function readPrivateFile(target: string): string | null { +function repairInterruptedExclusivePublication(target: string): void { + const directory = path.dirname(target); + const targetBasename = path.basename(target); + let entries: string[]; + try { + entries = fs.readdirSync(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + for (const entry of entries) { + if (!isPublishTemporaryEntry(entry, targetBasename)) continue; + const temporary = path.join(directory, entry); + let targetMetadata: fs.BigIntStats; + let temporaryMetadata: fs.BigIntStats; + try { + targetMetadata = fs.lstatSync(target, { bigint: true }); + temporaryMetadata = fs.lstatSync(temporary, { bigint: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + if ( + targetMetadata.dev !== temporaryMetadata.dev || + targetMetadata.ino !== temporaryMetadata.ino + ) { + continue; + } + if ( + !targetMetadata.isFile() || + targetMetadata.isSymbolicLink() || + !temporaryMetadata.isFile() || + temporaryMetadata.isSymbolicLink() || + targetMetadata.uid !== currentUid() || + (targetMetadata.mode & 0o077n) !== 0n || + targetMetadata.nlink !== 2n || + temporaryMetadata.nlink !== 2n + ) { + fail("interrupted ledger publication failed ownership, mode, or link checks"); + } + try { + fs.unlinkSync(temporary); + fsyncDirectory(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + } +} + +function readPrivateFile(target: string, maxBytes = MAX_RECORD_BYTES): string | null { + repairInterruptedExclusivePublication(target); const noFollow = fs.constants.O_NOFOLLOW; if (typeof noFollow !== "number") fail("O_NOFOLLOW is unavailable for lifecycle reads"); const nonblock = typeof fs.constants.O_NONBLOCK === "number" ? fs.constants.O_NONBLOCK : 0; @@ -448,7 +764,7 @@ function readPrivateFile(target: string): string | null { before.uid !== currentUid() || (before.mode & 0o077n) !== 0n || before.size <= 0n || - before.size > BigInt(MAX_RECORD_BYTES) + before.size > BigInt(maxBytes) ) { fail("ledger file failed ownership, mode, link, or size checks"); } @@ -501,7 +817,8 @@ function publishExclusive(directory: string, target: string, serialized: string) if ((error as NodeJS.ErrnoException).code === "EEXIST") return false; throw error; } - fs.unlinkSync(temporary); + // A concurrent reader may already have repaired the post-link crash window. + fs.rmSync(temporary, { force: true }); fsyncDirectory(directory); return true; } finally { @@ -537,10 +854,22 @@ function phasePath(directory: string, phase: PersistedEngineLifecyclePhase): str return path.join(directory, `${phase}.json`); } +function stateMutationIntentPath(directory: string): string { + return path.join(directory, PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE); +} + +function stateMutationReleasePath(directory: string): string { + return path.join(directory, PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE); +} + function tombstonePath(root: string, transactionId: string): string { return path.join(root, `${exactSha256(transactionId, "transaction identity")}.retired`); } +function runtimeTargetClaimDirectory(root: string): string { + return path.join(root, RUNTIME_TARGET_CLAIM_DIRECTORY); +} + function executionLeasePath(directory: string): string { return path.join(directory, EXECUTION_LEASE_FILE); } @@ -549,6 +878,52 @@ function executionRecoveryPath(directory: string): string { return path.join(directory, EXECUTION_RECOVERY_FILE); } +function loadStateMutationIntentArtifact( + directory: string, + transactionId: string, +): PersistedEngineStateMutationIntent | null { + const serialized = readPrivateFile( + stateMutationIntentPath(directory), + MAX_STATE_MUTATION_INTENT_BYTES, + ); + if (serialized === null) return null; + const intent = parsePersistedEngineStateMutationIntent(serialized); + if (intent.transactionId !== transactionId) { + fail("state-mutation intent names another transaction"); + } + return intent; +} + +function expectedStateMutationReleaseReceipt( + record: PersistedEngineLifecycleRecord, +): PersistedEngineStateMutationReleaseReceipt { + if (record.resultSha256 === null) { + fail("provider release receipt requires the exact completion digest"); + } + return Object.freeze({ + schemaVersion: PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION, + transactionId: record.transactionId, + resultSha256: record.resultSha256, + completedRecordSha256: completedRecordSha256(record), + }); +} + +function loadStateMutationReleaseReceipt( + directory: string, + record: PersistedEngineLifecycleRecord, +): PersistedEngineStateMutationReleaseReceipt | null { + const serialized = readPrivateFile(stateMutationReleasePath(directory)); + if (serialized === null) return null; + const receipt = parseStateMutationReleaseReceipt(serialized); + const expected = expectedStateMutationReleaseReceipt(record); + if ( + serializeStateMutationReleaseReceipt(receipt) !== serializeStateMutationReleaseReceipt(expected) + ) { + fail("provider release receipt does not match the exact completed transaction"); + } + return receipt; +} + function loadExecutionLease(directory: string): PersistedEngineLifecycleExecutionLease | null { const serialized = readPrivateFile(executionLeasePath(directory)); return serialized === null ? null : parseExecutionLease(serialized); @@ -622,6 +997,25 @@ function loadPhase( return record; } +function loadStateMutationIntentFromRoot( + root: string, + transactionId: string, +): PersistedEngineStateMutationIntent | null { + const directory = transactionDirectory(root, transactionId); + let metadata: fs.Stats; + try { + metadata = fs.lstatSync(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + if (!metadata.isDirectory() || metadata.isSymbolicLink()) { + fail("transaction path must be a private real directory"); + } + verifyPrivateDirectory(directory); + return loadStateMutationIntentArtifact(directory, transactionId); +} + function loadTransaction( root: string, transactionId: string, @@ -644,22 +1038,273 @@ function loadTransaction( (entry) => entry !== EXECUTION_LEASE_FILE && entry !== EXECUTION_RECOVERY_FILE && + entry !== PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE && + entry !== PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE && !isTransactionPublishTemporaryEntry(entry) && !PHASE_FILES.some((phase) => entry === `${phase}.json`), ) ) { fail("transaction directory contains an unsupported entry"); } + const intent = loadStateMutationIntentArtifact(directory, transactionId); const prepared = loadPhase(directory, "prepared"); - if (!prepared || prepared.transactionId !== transactionId) { + if (!prepared) { + if ( + entries.some( + (entry) => + entry === EXECUTION_LEASE_FILE || + entry === EXECUTION_RECOVERY_FILE || + entry === PERSISTED_ENGINE_STATE_MUTATION_RELEASE_FILE || + PHASE_FILES.some((phase) => entry === `${phase}.json`), + ) + ) { + fail("transaction is missing its exact prepared authority"); + } + // Preparation can stop after it publishes the write-once intent or creates + // its private directory. Neither state grants lifecycle or target authority. + return null; + } + if (prepared.transactionId !== transactionId) { fail("transaction is missing its exact prepared authority"); } + if (prepared.action === "state-mutation" && intent === null) { + fail("prepared state mutation is missing its exact intent"); + } + if (prepared.action !== "state-mutation" && intent !== null) { + fail("state-mutation intent cannot authorize another lifecycle action"); + } const authorized = loadPhase(directory, "mutation-authorized"); + const established = loadPhase(directory, "fence-established"); const completed = loadPhase(directory, "completed"); - if (completed && !authorized) fail("completed transaction is missing mutation authority"); + if (established && !authorized) { + fail("established fence is missing mutation authority"); + } + if (completed && (!authorized || (prepared.action === "state-mutation" && !established))) { + fail("completed transaction is missing required mutation authority"); + } if (authorized) requireSameLifecycle(prepared, authorized); + if (established) requireSameLifecycle(prepared, established); if (completed) requireSameLifecycle(prepared, completed); - return completed ?? authorized ?? prepared; + const current = completed ?? established ?? authorized ?? prepared; + const releaseReceipt = readPrivateFile(stateMutationReleasePath(directory)); + if (releaseReceipt !== null) { + if (current.action !== "state-mutation" || current.phase !== "completed") { + fail("provider release receipt requires one completed state mutation"); + } + if (loadStateMutationReleaseReceipt(directory, current) === null) { + fail("provider release receipt disappeared during inspection"); + } + } + return current; +} + +function runtimeTarget(record: PersistedEngineLifecycleRecord): string | null { + return record.resources.find((resource) => resource.role === "target")?.runtimeId ?? null; +} + +function runtimeTargetClaimIdentity(record: PersistedEngineLifecycleRecord): string | null { + const target = runtimeTarget(record); + if (target === null) return null; + return createHash("sha256") + .update(record.engineAuthority.providerId, "utf8") + .update("\0", "utf8") + .update(target, "utf8") + .digest("hex"); +} + +function runtimeTargetClaimPath( + root: string, + record: PersistedEngineLifecycleRecord, +): string | null { + const identity = runtimeTargetClaimIdentity(record); + return identity === null ? null : path.join(runtimeTargetClaimDirectory(root), identity); +} + +function loadRuntimeTargetClaim( + root: string, + identity: string, +): PersistedEngineLifecycleRecord | null { + const serialized = readPrivateFile( + path.join(runtimeTargetClaimDirectory(root), exactSha256(identity, "target claim identity")), + ); + if (serialized === null) return null; + const record = parsePersistedEngineLifecycleRecord(serialized); + if ( + runtimeTarget(record) === null || + runtimeTargetClaimIdentity(record) !== identity || + record.phase !== "prepared" + ) { + fail("runtime target claim is malformed"); + } + return record; +} + +function removeExactRuntimeTargetClaim( + root: string, + expected: PersistedEngineLifecycleRecord, +): void { + const identity = runtimeTargetClaimIdentity(expected); + const target = runtimeTargetClaimPath(root, expected); + if (identity === null || target === null) return; + const claim = loadRuntimeTargetClaim(root, identity); + if (!claim) return; + requireSameLifecycle(expected, claim); + fs.unlinkSync(target); + fsyncDirectory(runtimeTargetClaimDirectory(root)); +} + +function hasExactRuntimeTargetClaim( + root: string, + expected: PersistedEngineLifecycleRecord, +): boolean { + const identity = runtimeTargetClaimIdentity(expected); + if (identity === null) return false; + const claim = loadRuntimeTargetClaim(root, identity); + if (!claim) return false; + requireSameLifecycle(expected, claim); + return true; +} + +function hasMatchingRuntimeTargetClaim( + root: string, + expected: PersistedEngineLifecycleRecord, +): boolean { + const identity = runtimeTargetClaimIdentity(expected); + if (identity === null) return true; + const claim = loadRuntimeTargetClaim(root, identity); + if (!claim || claim.transactionId !== expected.transactionId) return false; + requireSameLifecycle(expected, claim); + return true; +} + +function hasFinalizedStateMutationRelease( + root: string, + record: PersistedEngineLifecycleRecord, +): boolean { + if (record.action !== "state-mutation" || record.phase !== "completed") return false; + return ( + loadStateMutationReleaseReceipt(transactionDirectory(root, record.transactionId), record) !== + null + ); +} + +function acquireRuntimeTargetClaim(root: string, candidate: PersistedEngineLifecycleRecord): void { + const identity = runtimeTargetClaimIdentity(candidate); + const target = runtimeTargetClaimPath(root, candidate); + if (identity === null || target === null) return; + const claimDirectory = runtimeTargetClaimDirectory(root); + requirePrivateDirectory(claimDirectory); + const prepared = normalizePersistedEngineLifecycleRecord(immutableRecord(candidate)); + const serialized = serializePersistedEngineLifecycleRecord(prepared); + for (let attempt = 0; attempt < 3; attempt += 1) { + if (publishExclusive(claimDirectory, target, serialized)) return; + const existing = loadRuntimeTargetClaim(root, identity); + if (!existing) continue; + const existingTransaction = loadTransaction(root, existing.transactionId); + if (!existingTransaction) { + // Prepared authority is published before any claim in this protocol. + // A claim without that authority is corruption; never make a stale + // orphan decision that could unlink a concurrently recovered owner. + fail("runtime target claim is missing its prepared authority"); + } + requireSameLifecycle(existing, existingTransaction); + if (existing.transactionId === prepared.transactionId) { + requireSameLifecycle(prepared, existing); + return; + } + // A completed owner may still be finishing its claim cleanup. Competing + // creators never unlink another transaction's claim; the exact owner must + // release it while holding its execution lease. + fail("exact runtime target already has an unfinished transaction"); + } + fail("exact runtime target claim could not be acquired"); +} + +function abandonNewUnclaimedPreparedTransaction( + root: string, + expected: PersistedEngineLifecycleRecord, +): void { + const directory = transactionDirectory(root, expected.transactionId); + const current = loadTransaction(root, expected.transactionId); + if (!current) return; + requireSameLifecycle(expected, current); + if ( + current.phase !== "prepared" || + hasMatchingRuntimeTargetClaim(root, current) || + readPrivateFile(executionLeasePath(directory)) !== null || + readPrivateFile(executionRecoveryPath(directory)) !== null + ) { + return; + } + fs.rmSync(directory, { force: true, recursive: true }); + fsyncDirectory(root); +} + +function listUnfinishedTransactions(root: string): readonly PersistedEngineLifecycleRecord[] { + requirePrivateDirectory(root); + const records = new Map(); + for (const entry of fs.readdirSync(root).sort()) { + if (isRootPublishTemporaryEntry(entry)) continue; + if (entry === RUNTIME_TARGET_CLAIM_DIRECTORY) continue; + if (entry.endsWith(".retired")) { + const transactionId = exactSha256( + entry.slice(0, -".retired".length), + "retired transaction identity", + ); + const receipt = readPrivateFile(tombstonePath(root, transactionId)); + if (receipt === null || !SHA256.test(receipt.trim()) || receipt !== `${receipt.trim()}\n`) { + fail("retirement receipt is malformed"); + } + continue; + } + exactSha256(entry, "transaction directory identity"); + const record = loadTransaction(root, entry); + if (!record) continue; + if (record.phase === "completed") { + if ( + record.action === "state-mutation" && + (!hasFinalizedStateMutationRelease(root, record) || + hasMatchingRuntimeTargetClaim(root, record)) + ) { + records.set(record.transactionId, record); + } + continue; + } + if (runtimeTarget(record) === null || hasMatchingRuntimeTargetClaim(root, record)) { + records.set(record.transactionId, record); + } else if (record.phase === "prepared" && record.action === "state-mutation") { + // A prepared mutation without a claim is still authoritative. Recovery + // must reacquire the exact target before any helper replay. + records.set(record.transactionId, record); + } else { + fail("unfinished target transaction is missing its exact claim"); + } + } + const claimDirectory = runtimeTargetClaimDirectory(root); + requirePrivateDirectory(claimDirectory); + for (const entry of fs.readdirSync(claimDirectory).sort()) { + if (isPublishTemporaryEntry(entry, entry.slice(1, 65))) continue; + const claim = loadRuntimeTargetClaim(root, entry); + if (!claim) fail("runtime target claim disappeared during inspection"); + const current = loadTransaction(root, claim.transactionId); + if (current) requireSameLifecycle(claim, current); + if ( + !current || + current.phase !== "completed" || + (current.action === "state-mutation" && hasExactRuntimeTargetClaim(root, current)) + ) { + records.set(claim.transactionId, current ?? claim); + } + } + return Object.freeze( + [...records.values()].sort((left, right) => + left.transactionId < right.transactionId + ? -1 + : left.transactionId > right.transactionId + ? 1 + : 0, + ), + ); } function publishPhase( @@ -676,41 +1321,157 @@ function publishPhase( fail(`${record.phase} authority already exists with different content`); } -export function createFilePersistedEngineLifecycleStore( - stateDir: string, -): PersistedEngineLifecycleStore { - const root = path.join(stateDir, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY); - requirePrivateDirectory(root); - return Object.freeze({ - load(transactionId: string) { +function exactRetirementExists(root: string, transactionId: string, resultSha256: string): boolean { + const receipt = readPrivateFile(tombstonePath(root, transactionId)); + if (receipt === null) return false; + if (receipt !== `${exactSha256(resultSha256, "completion result digest")}\n`) { + fail("retirement receipt digest changed"); + } + return true; +} + +function recoverExecutionArtifactsForRetirement(directory: string, transactionId: string): void { + for (let attempt = 0; attempt < 3; attempt += 1) { + const lease = loadExecutionLease(directory); + const existingRecovery = loadExecutionRecovery(directory); + if (!lease && !existingRecovery) return; + if (existingRecovery) { + if (existingRecovery.transactionId !== transactionId) { + fail("mutation execution recovery names another transaction"); + } + if (exactExecutionOwnerIsAlive(existingRecovery)) { + fail("retirement cannot interrupt live mutation execution recovery"); + } + removeExactExecutionRecovery(directory, existingRecovery); + continue; + } + if (!lease) continue; + if (lease.transactionId !== transactionId) { + fail("mutation execution lease names another transaction"); + } + if (exactExecutionOwnerIsAlive(lease)) { + fail("retirement requires released mutation execution ownership"); + } + const recovery = normalizeExecutionLease({ + schemaVersion: PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION, + transactionId, + ownerId: randomUUID(), + ownerPid: process.pid, + ownerStartIdentity: currentProcessStartIdentity(), + }); + if ( + !publishExclusive( + directory, + executionRecoveryPath(directory), + serializeExecutionLease(recovery), + ) + ) { + continue; + } + try { + const abandoned = loadExecutionLease(directory); + if (abandoned && exactExecutionOwnerIsAlive(abandoned)) { + fail("mutation execution owner became live during retirement recovery"); + } + if (abandoned) removeExactExecutionLease(directory, abandoned); + } finally { + const marker = loadExecutionRecovery(directory); + if (marker && serializeExecutionLease(marker) === serializeExecutionLease(recovery)) { + removeExactExecutionRecovery(directory, recovery); + } + } + } + fail("retirement could not recover abandoned mutation execution ownership"); +} + +function retireCompletedTransaction( + root: string, + transactionId: string, + resultSha256: string, +): void { + const result = exactSha256(resultSha256, "completion result digest"); + requirePrivateDirectory(root); + const directory = transactionDirectory(root, transactionId); + const existingTombstone = exactRetirementExists(root, transactionId, result); + if (existingTombstone) { + const remaining = loadTransaction(root, transactionId); + if (remaining !== null) { + if (remaining.phase !== "completed" || remaining.resultSha256 !== result) { + fail("retirement tombstone does not match the remaining transaction"); + } + if ( + remaining.action === "state-mutation" && + (!hasFinalizedStateMutationRelease(root, remaining) || + hasMatchingRuntimeTargetClaim(root, remaining)) + ) { + fail("retirement tombstone precedes provider fence release"); + } + recoverExecutionArtifactsForRetirement(directory, transactionId); + fs.rmSync(directory, { force: true, recursive: true }); + fsyncDirectory(root); + } + return; + } + const current = loadTransaction(root, transactionId); + if (!current || current.phase !== "completed" || current.resultSha256 !== result) { + fail("retirement requires the exact completed receipt"); + } + if (current.action === "state-mutation" && !hasFinalizedStateMutationRelease(root, current)) { + fail("state-mutation retirement requires a finalized provider release receipt"); + } + if (runtimeTarget(current) !== null && hasMatchingRuntimeTargetClaim(root, current)) { + if (current.action === "state-mutation") { + fail("state-mutation retirement requires released provider fence authority"); + } + fail("retirement requires the owning mutation to release its exact runtime target claim"); + } + recoverExecutionArtifactsForRetirement(directory, transactionId); + const tombstone = tombstonePath(root, transactionId); + if (!publishExclusive(root, tombstone, `${result}\n`)) { + exactRetirementExists(root, transactionId, result); + } + fs.rmSync(directory, { force: true, recursive: true }); + fsyncDirectory(root); +} + +export function createFilePersistedEngineLifecycleStore( + stateDir: string, +): PersistedEngineLifecycleStore { + const root = path.join(stateDir, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY); + requirePrivateDirectory(root); + return Object.freeze({ + load(transactionId: string) { requirePrivateDirectory(root); return loadTransaction(root, transactionId); }, - listUnfinished() { + loadStateMutationIntent(transactionId: string) { requirePrivateDirectory(root); - const records: PersistedEngineLifecycleRecord[] = []; - for (const entry of fs.readdirSync(root).sort()) { - if (isRootPublishTemporaryEntry(entry)) continue; - if (entry.endsWith(".retired")) { - const transactionId = exactSha256( - entry.slice(0, -".retired".length), - "retired transaction identity", - ); - const receipt = readPrivateFile(tombstonePath(root, transactionId)); - if ( - receipt === null || - !SHA256.test(receipt.trim()) || - receipt !== `${receipt.trim()}\n` - ) { - fail("retirement receipt is malformed"); - } - continue; - } - exactSha256(entry, "transaction directory identity"); - const record = loadTransaction(root, entry); - if (record && record.phase !== "completed") records.push(record); + return loadStateMutationIntentFromRoot(root, transactionId); + }, + recordStateMutationIntent(value: PersistedEngineStateMutationIntent) { + const intent = normalizePersistedEngineStateMutationIntent(value); + requirePrivateDirectory(root); + if (readPrivateFile(tombstonePath(root, intent.transactionId)) !== null) { + fail("retired transaction identity cannot be reused"); } - return Object.freeze(records); + const current = loadTransaction(root, intent.transactionId); + if (current && current.action !== "state-mutation") { + fail("state-mutation intent cannot authorize another lifecycle action"); + } + const directory = transactionDirectory(root, intent.transactionId); + requirePrivateDirectory(directory); + const serialized = serializePersistedEngineStateMutationIntent(intent); + if (publishExclusive(directory, stateMutationIntentPath(directory), serialized)) { + return intent; + } + const existing = loadStateMutationIntentArtifact(directory, intent.transactionId); + if (existing && serializePersistedEngineStateMutationIntent(existing) === serialized) { + return existing; + } + fail("state-mutation intent already exists with different content"); + }, + listUnfinished() { + return listUnfinishedTransactions(root); }, create(value: PersistedEngineLifecycleRecord) { const record = normalizePersistedEngineLifecycleRecord(value); @@ -721,16 +1482,40 @@ export function createFilePersistedEngineLifecycleStore( if (readPrivateFile(tombstonePath(root, record.transactionId)) !== null) { fail("retired transaction identity cannot be reused"); } + const intent = loadStateMutationIntentFromRoot(root, record.transactionId); + if (record.action === "state-mutation" && intent === null) { + fail("state-mutation preparation requires its exact durable intent"); + } + if (record.action !== "state-mutation" && intent !== null) { + fail("state-mutation intent cannot authorize another lifecycle action"); + } const existing = loadTransaction(root, record.transactionId); if (existing) { requireSameLifecycle(record, existing); + if (existing.phase !== "completed") acquireRuntimeTargetClaim(root, record); return existing; } - return publishPhase(root, record); + const published = publishPhase(root, record); + // Publish prepared authority first. Authorization remains impossible + // until this exact transaction wins the target claim, and an interrupted + // creator can never leave a claim that races its own later publication. + try { + acquireRuntimeTargetClaim(root, published); + } catch (error) { + // The caller still owns the per-sandbox transition lock. A candidate + // that never won its target claim cannot authorize helper execution + // and must not remain as a conservative orphan. + abandonNewUnclaimedPreparedTransaction(root, published); + throw error; + } + return published; }, authorizeMutation(transactionId: string) { const current = loadTransaction(root, transactionId); if (!current) fail("mutation authorization requires prepared authority"); + if (!hasMatchingRuntimeTargetClaim(root, current)) { + fail("mutation authorization requires the exact runtime target claim"); + } if (current.phase === "mutation-authorized") return current; if (current.phase !== "prepared") fail(`mutation is not allowed from ${current.phase}`); return publishPhase( @@ -741,9 +1526,71 @@ export function createFilePersistedEngineLifecycleStore( }), ); }, + assertStateMutationTargetClaim(transactionId: string) { + const current = loadTransaction(root, transactionId); + if ( + !current || + current.action !== "state-mutation" || + !hasExactRuntimeTargetClaim(root, current) + ) { + fail("active state mutation requires the exact runtime target claim"); + } + return current; + }, + establishStateMutationFence(lease: PersistedEngineLifecycleExecutionLease) { + const execution = normalizeExecutionLease(lease); + const directory = transactionDirectory(root, execution.transactionId); + requireExactExecutionLease(directory, execution); + const current = loadTransaction(root, execution.transactionId); + if (!current || current.action !== "state-mutation") { + fail("external fence establishment requires state-mutation authority"); + } + if (!hasExactRuntimeTargetClaim(root, current)) { + fail("external fence establishment requires the exact runtime target claim"); + } + if (current.phase === "fence-established") return current; + if (current.phase !== "mutation-authorized") { + fail(`external fence establishment is not allowed from ${current.phase}`); + } + return publishPhase( + root, + normalizePersistedEngineLifecycleRecord({ + ...current, + phase: "fence-established", + }), + ); + }, acquireMutationExecution(transactionId: string) { const current = loadTransaction(root, transactionId); - if (!current || current.phase !== "mutation-authorized") { + const releaseFinalized = current ? hasFinalizedStateMutationRelease(root, current) : false; + if ( + current?.action === "state-mutation" && + (current.phase === "prepared" || (current.phase === "completed" && !releaseFinalized)) && + !hasMatchingRuntimeTargetClaim(root, current) + ) { + acquireRuntimeTargetClaim(root, current); + } + if ( + current && + current.phase !== "completed" && + !hasMatchingRuntimeTargetClaim(root, current) + ) { + fail("mutation execution requires the exact runtime target claim"); + } + const pendingStateMutationRelease = + current?.action === "state-mutation" && + current.phase === "completed" && + hasMatchingRuntimeTargetClaim(root, current); + const preparedStateMutation = + current?.action === "state-mutation" && current.phase === "prepared"; + if ( + !current || + (current.phase === "completed" && releaseFinalized && !pendingStateMutationRelease) || + (!preparedStateMutation && + current.phase !== "mutation-authorized" && + current.phase !== "fence-established" && + !pendingStateMutationRelease) + ) { fail("mutation execution requires durable mutation authority"); } const directory = transactionDirectory(root, transactionId); @@ -819,7 +1666,28 @@ export function createFilePersistedEngineLifecycleStore( assertMutationExecution(lease: PersistedEngineLifecycleExecutionLease) { const expected = normalizeExecutionLease(lease); const current = loadTransaction(root, expected.transactionId); - if (!current || current.phase !== "mutation-authorized") { + const releaseFinalized = current ? hasFinalizedStateMutationRelease(root, current) : false; + if ( + current && + current.phase !== "completed" && + !hasMatchingRuntimeTargetClaim(root, current) + ) { + fail("mutation execution requires the exact runtime target claim"); + } + const pendingStateMutationRelease = + current?.action === "state-mutation" && + current.phase === "completed" && + hasMatchingRuntimeTargetClaim(root, current); + const preparedStateMutation = + current?.action === "state-mutation" && current.phase === "prepared"; + if ( + !current || + (current.phase === "completed" && releaseFinalized && !pendingStateMutationRelease) || + (!preparedStateMutation && + current.phase !== "mutation-authorized" && + current.phase !== "fence-established" && + !pendingStateMutationRelease) + ) { fail("mutation execution authority is no longer active"); } requireExactExecutionLease(transactionDirectory(root, expected.transactionId), expected); @@ -837,14 +1705,19 @@ export function createFilePersistedEngineLifecycleStore( const result = exactSha256(resultSha256, "completion result digest"); const current = loadTransaction(root, execution.transactionId); if (!current) fail("completion requires durable mutation authority"); + if (current.phase !== "completed" && !hasMatchingRuntimeTargetClaim(root, current)) { + fail("completion requires the exact runtime target claim"); + } if (current.phase === "completed") { if (current.resultSha256 === result) return current; fail("completion result digest changed"); } - if (current.phase !== "mutation-authorized") { + const requiredPhase = + current.action === "state-mutation" ? "fence-established" : "mutation-authorized"; + if (current.phase !== requiredPhase) { fail(`completion is not allowed from ${current.phase}`); } - return publishPhase( + const completed = publishPhase( root, normalizePersistedEngineLifecycleRecord({ ...current, @@ -852,41 +1725,91 @@ export function createFilePersistedEngineLifecycleStore( resultSha256: result, }), ); + if (completed.action !== "state-mutation") { + removeExactRuntimeTargetClaim(root, completed); + } + return completed; }, - retire(transactionId: string, resultSha256: string) { + finalizeStateMutationRelease( + lease: PersistedEngineLifecycleExecutionLease, + resultSha256: string, + ) { + const execution = normalizeExecutionLease(lease); + const directory = transactionDirectory(root, execution.transactionId); + requireExactExecutionLease(directory, execution); const result = exactSha256(resultSha256, "completion result digest"); - requirePrivateDirectory(root); - const directory = transactionDirectory(root, transactionId); + const current = loadTransaction(root, execution.transactionId); if ( - readPrivateFile(executionLeasePath(directory)) !== null || - readPrivateFile(executionRecoveryPath(directory)) !== null + !current || + current.action !== "state-mutation" || + current.phase !== "completed" || + current.resultSha256 !== result ) { - fail("retirement requires released mutation execution ownership"); + fail("state-mutation release requires the exact completed receipt"); } - const tombstone = tombstonePath(root, transactionId); - const existingTombstone = readPrivateFile(tombstone); - if (existingTombstone !== null) { - if (existingTombstone !== `${result}\n`) fail("retirement receipt digest changed"); - const remaining = loadTransaction(root, transactionId); - if (remaining !== null) { - if (remaining.phase !== "completed" || remaining.resultSha256 !== result) { - fail("retirement tombstone does not match the remaining transaction"); - } - fs.rmSync(transactionDirectory(root, transactionId), { force: true, recursive: true }); - fsyncDirectory(root); + const existingReceipt = loadStateMutationReleaseReceipt(directory, current); + if (existingReceipt === null && !hasExactRuntimeTargetClaim(root, current)) { + fail("state-mutation release target claim is missing"); + } + const receipt = expectedStateMutationReleaseReceipt(current); + const serialized = serializeStateMutationReleaseReceipt(receipt); + if ( + existingReceipt === null && + !publishExclusive(directory, stateMutationReleasePath(directory), serialized) + ) { + const raced = loadStateMutationReleaseReceipt(directory, current); + if (!raced || serializeStateMutationReleaseReceipt(raced) !== serialized) { + fail("provider release receipt changed during publication"); } - return; } + if (hasMatchingRuntimeTargetClaim(root, current)) { + removeExactRuntimeTargetClaim(root, current); + } + return current; + }, + isStateMutationReleaseFinalized(transactionId: string, resultSha256: string) { + const result = exactSha256(resultSha256, "completion result digest"); const current = loadTransaction(root, transactionId); - if (!current || current.phase !== "completed" || current.resultSha256 !== result) { - fail("retirement requires the exact completed receipt"); + if ( + !current || + current.action !== "state-mutation" || + current.phase !== "completed" || + current.resultSha256 !== result + ) { + fail("provider release status requires the exact completed receipt"); } - if (!publishExclusive(root, tombstone, `${result}\n`)) { - const raced = readPrivateFile(tombstone); - if (raced !== `${result}\n`) fail("retirement receipt digest changed"); + return hasFinalizedStateMutationRelease(root, current); + }, + retire(transactionId: string, resultSha256: string) { + retireCompletedTransaction(root, transactionId, resultSha256); + }, + retireReleasedStateMutations(sandboxName: string) { + const exactSandboxName = exactName(sandboxName, "sandbox name"); + requirePrivateDirectory(root); + for (const entry of fs.readdirSync(root).sort()) { + if ( + entry === RUNTIME_TARGET_CLAIM_DIRECTORY || + entry.endsWith(".retired") || + isRootPublishTemporaryEntry(entry) + ) { + continue; + } + exactSha256(entry, "transaction directory identity"); + const current = loadTransaction(root, entry); + if ( + current?.action === "state-mutation" && + current.phase === "completed" && + current.sandboxName === exactSandboxName && + hasFinalizedStateMutationRelease(root, current) && + !hasMatchingRuntimeTargetClaim(root, current) + ) { + retireCompletedTransaction(root, current.transactionId, current.resultSha256 as string); + } } - fs.rmSync(transactionDirectory(root, transactionId), { force: true, recursive: true }); - fsyncDirectory(root); + }, + isRetired(transactionId: string, resultSha256: string) { + requirePrivateDirectory(root); + return exactRetirementExists(root, transactionId, resultSha256); }, }); } @@ -937,7 +1860,47 @@ function expectedRecord( export function preparePersistedEngineLifecycle( input: PreparePersistedEngineLifecycleInput, ): PersistedEngineLifecycleRecord { - return input.lifecycleStore.create(expectedRecord(input)); + const record = expectedRecord(input); + if (record.action === "state-mutation") { + if (input.stateMutationIntent === undefined) { + fail("state-mutation preparation requires its exact intent"); + } + input.lifecycleStore.recordStateMutationIntent( + stateMutationIntentForTransaction(record.transactionId, input.stateMutationIntent), + ); + } else if (input.stateMutationIntent !== undefined) { + fail("state-mutation intent cannot authorize another lifecycle action"); + } + return input.lifecycleStore.create(record); +} + +/** + * Read-only gate for direct container access while a provider owns an exact + * state-mutation target. The file store returns a completed transaction only + * while its provider fence still retains the exact-target claim. + */ +export function hasActivePersistedEngineStateMutationTarget( + lifecycleStore: PersistedEngineLifecycleStore, + sandboxName: string, + runtimeId?: string, +): boolean { + const exactSandboxName = exactName(sandboxName, "sandbox name"); + if (runtimeId !== undefined && !RUNTIME_ID.test(runtimeId)) { + fail("runtime identity is malformed"); + } + const exactRuntimeId = runtimeId; + return lifecycleStore + .listUnfinished() + .some( + (record) => + record.action === "state-mutation" && + record.sandboxName === exactSandboxName && + record.resources.some( + (resource) => + resource.role === "target" && + (exactRuntimeId === undefined || resource.runtimeId === exactRuntimeId), + ), + ); } function requireExpectedLifecycle( @@ -957,6 +1920,28 @@ function requireExpectedLifecycle( return current; } +/** + * Load the exact replay intent only after the lifecycle and engine authority + * still match the durable state-mutation transaction. + */ +export function loadPersistedEngineStateMutationIntent( + input: PersistedEngineLifecycleExecutionInput, +): PersistedEngineStateMutationIntent { + if (input.action !== "state-mutation") { + throw new Error("Persisted state mutation requires the state-mutation lifecycle action."); + } + const current = requireExpectedLifecycle(input); + const intent = input.lifecycleStore.loadStateMutationIntent(current.transactionId); + if (!intent) { + throw new Error("Persisted state mutation intent is missing."); + } + const normalized = normalizePersistedEngineStateMutationIntent(intent); + if (normalized.transactionId !== current.transactionId) { + throw new Error("Persisted state mutation intent names another transaction."); + } + return normalized; +} + function exactArguments( command: PersistedEngineLifecycleExactCommand, runtimeId: string, @@ -1006,13 +1991,14 @@ function authorizedScope( role: PersistedEngineLifecycleResourceRole, buildCommand: (runtimeId: string) => PersistedEngineLifecycleExactCommand, timeoutMs?: number, + commandInput?: Buffer, ): ContainerEngineCommandResult => { const resource = record.resources.find((candidate) => candidate.role === role); if (!resource) throw new Error(`Persisted lifecycle has no exact ${role} runtime authority.`); const args = exactArguments(buildCommand(resource.runtimeId), resource.runtimeId); const guard = () => { const current = requireExpectedLifecycle(input); - if (current.phase !== "mutation-authorized") { + if (current.phase !== record.phase) { throw new Error("Persisted lifecycle mutation authority is no longer active."); } input.lifecycleStore.assertMutationExecution(lease); @@ -1023,7 +2009,7 @@ function authorizedScope( try { result = host ? input.engine.captureHost(args, timeoutMs) - : input.engine.capture(args, timeoutMs); + : input.engine.capture(args, timeoutMs, commandInput); } catch (error) { failure = error; } @@ -1041,7 +2027,8 @@ function authorizedScope( role: PersistedEngineLifecycleResourceRole, buildCommand: (runtimeId: string) => PersistedEngineLifecycleExactCommand, timeoutMs?: number, - ) => capture(false, role, buildCommand, timeoutMs), + commandInput?: Buffer, + ) => capture(false, role, buildCommand, timeoutMs, commandInput), captureHostExact: ( role: PersistedEngineLifecycleResourceRole, buildCommand: (runtimeId: string) => PersistedEngineLifecycleExactCommand, @@ -1055,7 +2042,7 @@ function authorizedScope( * A thrown callback leaves mutation-authorized state intact for the next * process; success durably publishes the caller's result receipt. */ -export async function executePersistedEngineLifecycle( +async function executePersistedEngineLifecycleCompletion( input: PersistedEngineLifecycleExecutionInput, mutate: ( scope: AuthorizedPersistedEngineLifecycle, @@ -1100,3 +2087,277 @@ export async function executePersistedEngineLifecycle( } } } + +export async function executePersistedEngineLifecycle( + input: PersistedEngineLifecycleExecutionInput, + mutate: ( + scope: AuthorizedPersistedEngineLifecycle, + ) => + | Promise> + | PersistedEngineLifecycleMutationResult, +): Promise<{ + readonly record: PersistedEngineLifecycleRecord; + readonly value: T; +}> { + if (input.action === "state-mutation") { + throw new Error( + "Persisted state mutation must remain active until explicit activation completion.", + ); + } + return executePersistedEngineLifecycleCompletion(input, mutate); +} + +/** + * Assert that one exact provider-owned state mutation remains durably active. + * This check is read-only so a restarted controller can reconstruct the fence + * without publishing another lifecycle phase or acquiring execution ownership. + */ +export function assertActivePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, +): PersistedEngineLifecycleRecord { + if (input.action !== "state-mutation") { + throw new Error("Persisted state mutation requires the state-mutation lifecycle action."); + } + const current = requireExpectedLifecycle(input); + if (current.phase !== "fence-established") { + throw new Error("Persisted state mutation fence is not established."); + } + input.lifecycleStore.assertStateMutationTargetClaim(input.transactionId); + return current; +} + +type PersistedEngineStateMutationResult = { + readonly record: PersistedEngineLifecycleRecord; + readonly value: T; +}; + +function isPromiseLike(value: unknown): value is PromiseLike { + return ( + ((typeof value === "object" && value !== null) || typeof value === "function") && + typeof (value as { then?: unknown }).then === "function" + ); +} + +function releaseExecutionLeaseIgnoringCleanupRace( + input: PersistedEngineLifecycleExecutionInput, + lease: PersistedEngineLifecycleExecutionLease, +): void { + try { + input.lifecycleStore.releaseMutationExecution(lease); + } catch { + // A recovered owner may race cleanup. The exact durable phase and target + // claim remain authoritative independently of process-owned execution. + } +} + +function withStateMutationExecutionLease( + input: PersistedEngineLifecycleExecutionInput, + lease: PersistedEngineLifecycleExecutionLease, + run: () => T | Promise, +): T | Promise { + try { + const value = run(); + if (isPromiseLike(value)) { + return Promise.resolve(value).finally(() => { + releaseExecutionLeaseIgnoringCleanupRace(input, lease); + }); + } + releaseExecutionLeaseIgnoringCleanupRace(input, lease); + return value; + } catch (error) { + releaseExecutionLeaseIgnoringCleanupRace(input, lease); + throw error; + } +} + +/** + * Establish one provider-owned external fence while the durable transaction is + * still prepared. Only after the callback returns validated marker evidence do + * we publish mutation-authorized and fence-established under the same exact + * process lease. Synchronous providers receive a synchronous result; an async + * callback retains the lease until its promise settles. + */ +export function executePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + mutate: (scope: AuthorizedPersistedEngineLifecycle) => T, +): PersistedEngineStateMutationResult; +export function executePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + mutate: (scope: AuthorizedPersistedEngineLifecycle) => Promise, +): Promise>; +export function executePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + mutate: (scope: AuthorizedPersistedEngineLifecycle) => Promise | T, +): PersistedEngineStateMutationResult | Promise> { + if (input.action !== "state-mutation") { + throw new Error("Persisted state mutation requires the state-mutation lifecycle action."); + } + const current = requireExpectedLifecycle(input); + if (current.phase === "completed") { + throw new Error("Persisted lifecycle transaction is already completed."); + } + if (current.phase === "fence-established") { + throw new Error("Persisted state mutation fence is already established."); + } + if (current.phase !== "prepared" && current.phase !== "mutation-authorized") { + throw new Error(`Persisted state mutation cannot establish a fence from ${current.phase}.`); + } + const lease = input.lifecycleStore.acquireMutationExecution(input.transactionId); + return withStateMutationExecutionLease(input, lease, () => { + const outcome = mutate(authorizedScope(input, current, lease)); + const publishFence = (value: T): PersistedEngineStateMutationResult => { + const after = requireExpectedLifecycle(input); + if (after.phase !== current.phase) { + throw new Error("Persisted state mutation authority changed before fence establishment."); + } + input.lifecycleStore.assertMutationExecution(lease); + const authorized = + after.phase === "prepared" + ? input.lifecycleStore.authorizeMutation(input.transactionId) + : after; + if (authorized.phase !== "mutation-authorized") { + throw new Error("Persisted state mutation did not publish exact mutation authority."); + } + input.lifecycleStore.assertMutationExecution(lease); + const established = input.lifecycleStore.establishStateMutationFence(lease); + return Object.freeze({ record: established, value }); + }; + if (isPromiseLike(outcome)) return Promise.resolve(outcome).then(publishFence); + return publishFence(outcome); + }); +} + +/** + * Run final activation and publish completion only while the same durable + * state-mutation authority and one exact execution lease remain active. + */ +export function completePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + activate: ( + scope: AuthorizedPersistedEngineLifecycle, + ) => PersistedEngineLifecycleMutationResult, + release: ( + scope: AuthorizedPersistedEngineLifecycle, + completed: PersistedEngineLifecycleRecord, + ) => void, +): PersistedEngineStateMutationResult; +export function completePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + activate: ( + scope: AuthorizedPersistedEngineLifecycle, + ) => + | Promise> + | PersistedEngineLifecycleMutationResult, + release: ( + scope: AuthorizedPersistedEngineLifecycle, + completed: PersistedEngineLifecycleRecord, + ) => Promise | void, +): PersistedEngineStateMutationResult | Promise>; +export function completePersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + activate: ( + scope: AuthorizedPersistedEngineLifecycle, + ) => + | Promise> + | PersistedEngineLifecycleMutationResult, + release: ( + scope: AuthorizedPersistedEngineLifecycle, + completed: PersistedEngineLifecycleRecord, + ) => Promise | void, +): PersistedEngineStateMutationResult | Promise> { + if (input.action !== "state-mutation") { + throw new Error("Persisted state mutation requires the state-mutation lifecycle action."); + } + const current = requireExpectedLifecycle(input); + if (current.phase === "completed") { + throw new Error("Persisted lifecycle transaction is already completed."); + } + if (current.phase !== "fence-established") { + throw new Error("Persisted state mutation completion requires an established fence."); + } + const lease = input.lifecycleStore.acquireMutationExecution(input.transactionId); + return withStateMutationExecutionLease(input, lease, () => { + const activated = activate(authorizedScope(input, current, lease)); + const completeAndRelease = ( + result: PersistedEngineLifecycleMutationResult, + ): PersistedEngineStateMutationResult | Promise> => { + if ( + typeof result !== "object" || + result === null || + Array.isArray(result) || + Object.keys(result).sort().join(",") !== "resultSha256,value" + ) { + throw new Error("Persisted lifecycle mutation returned an invalid completion result."); + } + const resultSha256 = exactSha256(result.resultSha256, "completion result digest"); + const value = result.value; + const after = requireExpectedLifecycle(input); + if (after.phase !== "fence-established") { + throw new Error("Persisted state mutation fence changed before completion."); + } + input.lifecycleStore.assertMutationExecution(lease); + const completed = input.lifecycleStore.complete(lease, resultSha256); + const released = release(authorizedScope(input, completed, lease), completed); + const finalize = (): PersistedEngineStateMutationResult => { + input.lifecycleStore.assertMutationExecution(lease); + input.lifecycleStore.finalizeStateMutationRelease(lease, resultSha256); + return Object.freeze({ record: completed, value }); + }; + return isPromiseLike(released) ? Promise.resolve(released).then(finalize) : finalize(); + }; + return isPromiseLike>(activated) + ? Promise.resolve(activated).then(completeAndRelease) + : completeAndRelease(activated); + }); +} + +/** + * Finish provider-fence release after a controller exited between durable host + * completion and the provider's nonce-bound release. Activation is never run + * twice: the exact completion digest is supplied from the persisted receipt. + */ +export function releaseCompletedPersistedEngineStateMutation( + input: PersistedEngineLifecycleExecutionInput, + release: ( + scope: AuthorizedPersistedEngineLifecycle, + completed: PersistedEngineLifecycleRecord, + ) => Promise | T, +): + | PersistedEngineStateMutationResult + | Promise> { + if (input.action !== "state-mutation") { + throw new Error("Persisted state mutation requires the state-mutation lifecycle action."); + } + const current = requireExpectedLifecycle(input); + if (current.phase !== "completed" || current.resultSha256 === null) { + throw new Error("Persisted state mutation release requires a completed activation receipt."); + } + const lease = input.lifecycleStore.acquireMutationExecution(input.transactionId); + return withStateMutationExecutionLease(input, lease, () => { + if ( + input.lifecycleStore.isStateMutationReleaseFinalized( + current.transactionId, + current.resultSha256 as string, + ) + ) { + input.lifecycleStore.assertMutationExecution(lease); + const finalized = input.lifecycleStore.finalizeStateMutationRelease( + lease, + current.resultSha256 as string, + ); + return Object.freeze({ record: finalized, value: undefined }); + } + const released = release(authorizedScope(input, current, lease), current); + const finalize = (value: T): PersistedEngineStateMutationResult => { + input.lifecycleStore.assertMutationExecution(lease); + const finalized = input.lifecycleStore.finalizeStateMutationRelease( + lease, + current.resultSha256 as string, + ); + return Object.freeze({ record: finalized, value }); + }; + return isPromiseLike(released) + ? Promise.resolve(released).then(finalize) + : finalize(released); + }); +} diff --git a/src/lib/onboard/runtime-provider/registry.ts b/src/lib/onboard/runtime-provider/registry.ts index 2f561d55097..3908e621ef5 100644 --- a/src/lib/onboard/runtime-provider/registry.ts +++ b/src/lib/onboard/runtime-provider/registry.ts @@ -417,7 +417,15 @@ function validateStateMutationSurface(providerId: string, surface: Record { + const surface = bundle.stateMutation; + if (surface.supported !== true) { + throw new RuntimeProviderSelectionError( + `Runtime provider '${bundle.identity.id}' has no state-mutation implementation: ${surface.reason}`, + ); + } + return surface; +} + export type RuntimeProviderDestructiveCleanupAuthority = { readonly provider: RuntimeProviderBundle & { readonly cleanup: Extract; diff --git a/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts b/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts index cc4f4c9a380..92f92e1ac89 100644 --- a/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts +++ b/src/lib/onboard/runtime-provider/runtime-provider-contract.test.ts @@ -41,6 +41,7 @@ import { RuntimeProviderRegistrationError, RuntimeProviderSelectionError, requireRuntimeProviderHostLocalInferenceOperation, + requireRuntimeProviderStateMutationSurface, resolveRuntimeProviderBundle, } from "./registry"; @@ -125,6 +126,7 @@ describe("RuntimeProviderBundle registry contract", () => { "hostLocalInference", "lifecycle", "mutationAuthority", + "stateMutation", "bootstrap", "snapshot", "recovery", @@ -134,6 +136,10 @@ describe("RuntimeProviderBundle registry contract", () => { expect(bundle[surface].providerId, `${providerId}.${surface}`).toBe(providerId); } expect(bundle.bootstrap).toMatchObject({ supported: providerId === "docker" }); + expect(bundle.stateMutation).toMatchObject({ + supported: providerId === "docker", + ...(providerId === "docker" ? { contractVersion: 2 } : {}), + }); expect(bundle.snapshot).toMatchObject( providerId === "docker" ? { @@ -159,6 +165,12 @@ describe("RuntimeProviderBundle registry contract", () => { expect(CURRENT_RUNTIME_PROVIDER_BUNDLES.kubernetes?.hostLocalInference).toMatchObject({ supported: false, }); + expect( + requireRuntimeProviderStateMutationSurface(CURRENT_RUNTIME_PROVIDER_BUNDLES.docker!), + ).toMatchObject({ providerId: "docker", supported: true, contractVersion: 2 }); + expect(() => + requireRuntimeProviderStateMutationSurface(CURRENT_RUNTIME_PROVIDER_BUNDLES.kubernetes!), + ).toThrow(/no state-mutation implementation/u); }); it("registers the production Docker bootstrap surface through the same bundle registry", () => { @@ -321,6 +333,7 @@ describe("RuntimeProviderBundle registry contract", () => { "hostLocalInference", "lifecycle", "mutationAuthority", + "stateMutation", "bootstrap", "snapshot", "recovery", @@ -404,7 +417,7 @@ describe("RuntimeProviderBundle registry contract", () => { (bundle: RuntimeProviderBundle) => ({ ...bundle.stateMutation, supported: true, - contractVersion: 1, + contractVersion: 2, }), ], [ @@ -459,6 +472,34 @@ describe("RuntimeProviderBundle registry contract", () => { ).toThrow(RuntimeProviderRegistrationError); }); + it.each([ + "publish", + "rollback", + "release", + ] as const)("rejects state-mutation v2 without %s", (operation) => { + const bundle = mxcBundle(); + const supported = { + providerId: "mxc", + supported: true, + contractVersion: 2, + acquire: vi.fn(), + assertFenced: vi.fn(), + publish: vi.fn(), + rollback: vi.fn(), + activate: vi.fn(), + release: vi.fn(), + recover: vi.fn(), + }; + const incomplete = { ...supported } as Record; + Reflect.deleteProperty(incomplete, operation); + + expect(() => + createRuntimeProviderBundleRegistry([ + ["mxc", replaceSurface(bundle, "stateMutation", incomplete)], + ]), + ).toThrow(new RegExp(`stateMutation\\.${operation} must be a function`, "u")); + }); + it("rejects a lifecycle surface without provider-owned post-start verification", () => { const bundle = mxcBundle(); expectSupportedSurface(bundle.lifecycle); diff --git a/src/lib/onboard/runtime-provider/state-mutation.test.ts b/src/lib/onboard/runtime-provider/state-mutation.test.ts index 88a3b408446..519b39ee75b 100644 --- a/src/lib/onboard/runtime-provider/state-mutation.test.ts +++ b/src/lib/onboard/runtime-provider/state-mutation.test.ts @@ -2,45 +2,287 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; +import { requireProtectionTransitionPlan } from "../../../../test/helpers/runtime-provider-state-mutation-test-helpers"; -import { prepareRuntimeProviderStateMutationPlan } from "./state-mutation"; +import { + prepareAgentDefinitionProtectionTransitionPlan, + prepareRuntimeProviderStateMutationPlan, +} from "./state-mutation"; const PROJECTION_SHA256 = "a".repeat(64); function plan() { return { - schemaVersion: 1, + schemaVersion: 2, intent: "restore", stateRoot: "/sandbox/.hermes", selectors: [ - { kind: "path", path: "scripts" }, { kind: "path", path: "cron" }, + { kind: "path", path: "scripts" }, { kind: "prefix", prefix: "workspace-" }, ], projectionSha256: PROJECTION_SHA256, }; } +function protectionTransitionPlan() { + return { + ...plan(), + intent: "protection-transition", + target: "locked", + rollback: "mutable", + stateLockPlan: { + version: 1, + readOnlyRoots: ["scripts"], + confidentialRoots: ["cron"], + readOnlyPrefixes: ["workspace-"], + confidentialPrefixes: [], + writableSubpaths: [], + }, + }; +} + describe("runtime provider state mutation plan", () => { + it("compiles the complete AgentDefinition Shields projection into a bounded plan (#7744)", () => { + const prepared = prepareAgentDefinitionProtectionTransitionPlan( + { + name: "hermes", + configPaths: { + dir: "/sandbox/.hermes", + configFile: "config.yaml", + envFile: ".env", + format: "yaml", + shieldsFiles: [".env"], + }, + stateLockPlan: { + version: 1, + readOnlyRoots: ["skills", "hooks", "profiles"], + confidentialRoots: ["pairing"], + readOnlyPrefixes: ["workspace-"], + confidentialPrefixes: [], + writableSubpaths: ["profiles/dashboard-home"], + }, + }, + "locked", + "mutable", + ); + + expect(prepared.plan).toEqual({ + schemaVersion: 2, + intent: "protection-transition", + target: "locked", + rollback: "mutable", + stateRoot: "/sandbox/.hermes", + selectors: [ + { kind: "path", path: ".config-hash" }, + { kind: "path", path: ".env" }, + { kind: "path", path: "config.yaml" }, + { kind: "path", path: "hooks" }, + { kind: "path", path: "pairing" }, + { kind: "path", path: "profiles" }, + { kind: "path", path: "skills" }, + { kind: "prefix", prefix: "workspace-" }, + ], + stateLockPlan: { + version: 1, + readOnlyRoots: ["hooks", "profiles", "skills"], + confidentialRoots: ["pairing"], + readOnlyPrefixes: ["workspace-"], + confidentialPrefixes: [], + writableSubpaths: ["profiles/dashboard-home"], + }, + projectionSha256: expect.stringMatching(/^[a-f0-9]{64}$/u), + }); + }); + + it("binds writable exceptions into the projection digest (#7744)", () => { + const agent = { + name: "hermes", + configPaths: { + dir: "/sandbox/.hermes", + configFile: "config.yaml", + envFile: ".env", + format: "yaml", + shieldsFiles: [".env"], + }, + stateLockPlan: { + version: 1 as const, + readOnlyRoots: ["profiles"], + confidentialRoots: [], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: ["profiles/dashboard-home"], + }, + }; + const first = prepareAgentDefinitionProtectionTransitionPlan(agent, "locked", "mutable"); + const second = prepareAgentDefinitionProtectionTransitionPlan( + { + ...agent, + stateLockPlan: { ...agent.stateLockPlan, writableSubpaths: [] }, + }, + "locked", + "mutable", + ); + + expect(second.plan.selectors).toEqual(first.plan.selectors); + const firstPlan = requireProtectionTransitionPlan(first.plan); + const secondPlan = requireProtectionTransitionPlan(second.plan); + expect(secondPlan.stateLockPlan.writableSubpaths).not.toEqual( + firstPlan.stateLockPlan.writableSubpaths, + ); + expect(second.projectionSha256).not.toBe(first.projectionSha256); + expect(second.planSha256).not.toBe(first.planSha256); + }); + + it("includes an AgentDefinition environment file even when it is not duplicated as a shields file", () => { + const prepared = prepareAgentDefinitionProtectionTransitionPlan( + { + name: "langchain-deepagents-code", + configPaths: { + dir: "/sandbox/.deepagents", + configFile: "config.toml", + envFile: ".env", + format: "toml", + shieldsFiles: [], + }, + stateLockPlan: { + version: 1, + readOnlyRoots: [], + confidentialRoots: [], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: [], + }, + }, + "locked", + "mutable", + ); + + expect(prepared.plan.selectors).toEqual([ + { kind: "path", path: ".config-hash" }, + { kind: "path", path: ".env" }, + { kind: "path", path: "config.toml" }, + ]); + expect(prepared.plan.intent).toBe("protection-transition"); + expect(requireProtectionTransitionPlan(prepared.plan).stateLockPlan.writableSubpaths).toEqual( + [], + ); + }); + + it("rejects a noncanonical writable exception in the AgentDefinition projection", () => { + expect(() => + prepareAgentDefinitionProtectionTransitionPlan( + { + name: "hermes", + configPaths: { + dir: "/sandbox/.hermes", + configFile: "config.yaml", + envFile: ".env", + format: "yaml", + shieldsFiles: [".env"], + }, + stateLockPlan: { + version: 1, + readOnlyRoots: [], + confidentialRoots: [], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: ["profiles/../config.yaml"], + }, + }, + "locked", + "mutable", + ), + ).toThrow( + "AgentDefinition state lock plan writable subpaths 0 must be a canonical relative path", + ); + }); + + it("does not let inherited JSON hooks replace the AgentDefinition projection digest", () => { + const agent = { + name: "hermes", + configPaths: { + dir: "/sandbox/.hermes", + configFile: "config.yaml", + envFile: ".env", + format: "yaml", + shieldsFiles: [".env"], + }, + stateLockPlan: { + version: 1 as const, + readOnlyRoots: ["profiles"], + confidentialRoots: [], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: ["profiles/dashboard-home"], + }, + }; + const baseline = prepareAgentDefinitionProtectionTransitionPlan(agent, "locked", "mutable"); + const objectToJson = Object.getOwnPropertyDescriptor(Object.prototype, "toJSON"); + const arrayToJson = Object.getOwnPropertyDescriptor(Array.prototype, "toJSON"); + let polluted: ReturnType | undefined; + + try { + Object.defineProperty(Object.prototype, "toJSON", { + configurable: true, + value: () => "polluted-object", + }); + Object.defineProperty(Array.prototype, "toJSON", { + configurable: true, + value: () => ["polluted-array"], + }); + polluted = prepareAgentDefinitionProtectionTransitionPlan(agent, "locked", "mutable"); + } finally { + objectToJson === undefined + ? Reflect.deleteProperty(Object.prototype, "toJSON") + : Object.defineProperty(Object.prototype, "toJSON", objectToJson); + arrayToJson === undefined + ? Reflect.deleteProperty(Array.prototype, "toJSON") + : Object.defineProperty(Array.prototype, "toJSON", arrayToJson); + } + + expect(polluted?.projectionSha256).toBe(baseline.projectionSha256); + expect(polluted?.planSha256).toBe(baseline.planSha256); + }); + it("binds a bounded scope to the AgentDefinition projection without copying it (#7744)", () => { const source = plan(); const prepared = prepareRuntimeProviderStateMutationPlan(source); expect(prepared.plan).toEqual(source); + expect(JSON.parse(prepared.serializedPlan)).toEqual(source); expect(prepared.planSha256).toMatch(/^[a-f0-9]{64}$/u); expect(prepared.projectionSha256).toBe(PROJECTION_SHA256); expect(Object.isFrozen(prepared)).toBe(true); expect(Object.isFrozen(prepared.plan)).toBe(true); expect(Object.isFrozen(prepared.plan.selectors)).toBe(true); expect(Object.isFrozen(prepared.plan.selectors[0])).toBe(true); + expect(Object.hasOwn(JSON.parse(prepared.serializedPlan), "stateLockPlan")).toBe(false); + expect(Object.hasOwn(JSON.parse(prepared.serializedPlan), "writableSubpaths")).toBe(false); expect(prepared.plan).not.toBe(source); }); + it("canonicalizes selector order before computing the provider digest (#7744)", () => { + const canonical = prepareRuntimeProviderStateMutationPlan(plan()); + const reordered = prepareRuntimeProviderStateMutationPlan({ + ...plan(), + selectors: [...plan().selectors].reverse(), + }); + + expect(reordered.plan.selectors).toEqual(canonical.plan.selectors); + expect(reordered.serializedPlan).toBe(canonical.serializedPlan); + expect(reordered.planSha256).toBe(canonical.planSha256); + }); + it("keeps the plan digest sensitive to intent, scope, and projection authority (#7744)", () => { const restore = prepareRuntimeProviderStateMutationPlan(plan()); - const protectionTransition = prepareRuntimeProviderStateMutationPlan({ - ...plan(), - intent: "protection-transition", + const protectionTransition = prepareRuntimeProviderStateMutationPlan( + protectionTransitionPlan(), + ); + const reversedTransition = prepareRuntimeProviderStateMutationPlan({ + ...protectionTransitionPlan(), + target: "mutable", + rollback: "locked", }); const changedProjection = prepareRuntimeProviderStateMutationPlan({ ...plan(), @@ -50,13 +292,254 @@ describe("runtime provider state mutation plan", () => { ...plan(), selectors: [{ kind: "path", path: "scripts" }], }); + const changedWritableException = prepareRuntimeProviderStateMutationPlan({ + ...protectionTransitionPlan(), + stateLockPlan: { + ...protectionTransitionPlan().stateLockPlan, + writableSubpaths: ["scripts/generated"], + }, + }); expect(protectionTransition.planSha256).not.toBe(restore.planSha256); + expect(reversedTransition.planSha256).not.toBe(protectionTransition.planSha256); expect(changedProjection.planSha256).not.toBe(restore.planSha256); expect(changedScope.planSha256).not.toBe(restore.planSha256); + expect(changedWritableException.planSha256).not.toBe(protectionTransition.planSha256); expect(changedProjection.projectionSha256).toBe("b".repeat(64)); }); + it("keeps protection transitions distinct from restore plans (#7744)", () => { + const source = protectionTransitionPlan(); + const protectionTransition = prepareRuntimeProviderStateMutationPlan(source); + + expect(protectionTransition.plan).toEqual(protectionTransitionPlan()); + expect(Object.isFrozen(protectionTransition.plan)).toBe(true); + expect(protectionTransition.plan.intent).toBe("protection-transition"); + const protectionPlan = requireProtectionTransitionPlan(protectionTransition.plan); + expect(protectionPlan.target).toBe("locked"); + expect(protectionPlan.rollback).toBe("mutable"); + expect(Object.isFrozen(protectionPlan.stateLockPlan)).toBe(true); + expect(Object.isFrozen(protectionPlan.stateLockPlan.readOnlyRoots)).toBe(true); + expect(Object.isFrozen(protectionPlan.stateLockPlan.writableSubpaths)).toBe(true); + source.stateLockPlan.readOnlyRoots[0] = "changed-after-prepare"; + expect(protectionPlan.stateLockPlan.readOnlyRoots).toEqual(["scripts"]); + }); + + it.each([ + [ + "a protection transition without a target", + () => { + const { target: _target, ...value } = protectionTransitionPlan(); + return value; + }, + /fields are unsupported/u, + ], + [ + "a protection transition without a rollback posture", + () => { + const { rollback: _rollback, ...value } = protectionTransitionPlan(); + return value; + }, + /fields are unsupported/u, + ], + [ + "a protection transition without a state-lock policy", + () => { + const { stateLockPlan: _stateLockPlan, ...value } = protectionTransitionPlan(); + return value; + }, + /fields are unsupported/u, + ], + [ + "an unsupported protection target", + () => ({ ...protectionTransitionPlan(), target: "sealed" }), + /target must be exactly locked or mutable/u, + ], + [ + "an unsupported protection rollback posture", + () => ({ ...protectionTransitionPlan(), rollback: "restore" }), + /rollback must be exactly locked or mutable/u, + ], + [ + "identical target and rollback postures", + () => ({ ...protectionTransitionPlan(), rollback: "locked" }), + /target and rollback postures must differ/u, + ], + [ + "a restore target posture", + () => ({ ...plan(), target: "locked" }), + /fields are unsupported/u, + ], + [ + "a restore rollback posture", + () => ({ ...plan(), rollback: "mutable" }), + /fields are unsupported/u, + ], + [ + "the prior schema version", + () => ({ ...plan(), schemaVersion: 1 }), + /version is unsupported/u, + ], + [ + "a restore state-lock policy", + () => ({ ...plan(), stateLockPlan: protectionTransitionPlan().stateLockPlan }), + /fields are unsupported/u, + ], + [ + "a legacy top-level writable exception", + () => ({ ...plan(), writableSubpaths: [] }), + /fields are unsupported/u, + ], + [ + "a legacy top-level writable exception on a protection transition", + () => ({ ...protectionTransitionPlan(), writableSubpaths: [] }), + /fields are unsupported/u, + ], + [ + "a state-lock policy with a missing field", + () => { + const base = protectionTransitionPlan(); + const { confidentialPrefixes: _confidentialPrefixes, ...stateLockPlan } = + base.stateLockPlan; + return { ...base, stateLockPlan }; + }, + /fields are unsupported/u, + ], + [ + "a state-lock policy with an unknown field", + () => { + const base = protectionTransitionPlan(); + return { ...base, stateLockPlan: { ...base.stateLockPlan, source: "ambient" } }; + }, + /fields are unsupported/u, + ], + [ + "a state-lock policy with a prior version", + () => { + const base = protectionTransitionPlan(); + return { ...base, stateLockPlan: { ...base.stateLockPlan, version: 0 } }; + }, + /version is unsupported/u, + ], + [ + "a protection policy outside the selected scope", + () => ({ + ...protectionTransitionPlan(), + stateLockPlan: { + ...protectionTransitionPlan().stateLockPlan, + readOnlyRoots: ["scripts", "other"], + }, + }), + /represented by exact selectors/u, + ], + [ + "a duplicate writable exception", + () => ({ + ...protectionTransitionPlan(), + stateLockPlan: { + ...protectionTransitionPlan().stateLockPlan, + writableSubpaths: ["scripts/generated", "scripts/generated"], + }, + }), + /must not contain duplicates/u, + ], + [ + "a writable exception beneath a confidential root", + () => ({ + ...protectionTransitionPlan(), + stateLockPlan: { + ...protectionTransitionPlan().stateLockPlan, + writableSubpaths: ["cron/generated"], + }, + }), + /beneath a read-only root/u, + ], + ])("rejects %s (#7744)", (_label, value, expected) => { + expect(() => prepareRuntimeProviderStateMutationPlan(value())).toThrow(expected); + }); + + it.each([ + ["a one-component writable path", ["scripts"], /beneath a declared top-level root/u], + ["a partial wildcard component", ["scripts/run*/output"], /only as a complete path component/u], + ["a final wildcard component", ["scripts/*"], /may not end with a wildcard/u], + [ + "overlapping wildcard paths", + ["scripts/*/runs", "scripts/main/runs/output"], + /must not overlap/u, + ], + ])("rejects %s in the nested state-lock grammar (#7744)", (_label, paths, expected) => { + expect(() => + prepareRuntimeProviderStateMutationPlan({ + ...protectionTransitionPlan(), + stateLockPlan: { + ...protectionTransitionPlan().stateLockPlan, + writableSubpaths: paths, + }, + }), + ).toThrow(expected); + }); + + it("accepts an OpenClaw-style wildcard writable exception (#7744)", () => { + const base = protectionTransitionPlan(); + const prepared = prepareRuntimeProviderStateMutationPlan({ + ...base, + selectors: [...base.selectors, { kind: "path", path: "agents" }], + stateLockPlan: { + ...base.stateLockPlan, + readOnlyRoots: ["agents", "scripts"], + writableSubpaths: ["agents/*/sessions"], + }, + }); + + expect(prepared.plan.intent).toBe("protection-transition"); + expect(requireProtectionTransitionPlan(prepared.plan).stateLockPlan.writableSubpaths).toEqual([ + "agents/*/sessions", + ]); + }); + + it.each([ + [ + "one root in both policy classes", + { + readOnlyRoots: ["scripts"], + confidentialRoots: ["scripts"], + }, + /assigns one root more than once/u, + ], + [ + "one prefix in both policy classes", + { + readOnlyPrefixes: ["workspace-"], + confidentialPrefixes: ["workspace-"], + }, + /assigns one prefix more than once/u, + ], + [ + "overlapping root and prefix policies", + { + readOnlyRoots: ["scripts", "workspace-main"], + readOnlyPrefixes: ["workspace-"], + }, + /root and prefix policies must not overlap/u, + ], + [ + "overlapping prefixes", + { + readOnlyPrefixes: ["workspace-"], + confidentialPrefixes: ["workspace-main"], + }, + /prefix policies must not overlap/u, + ], + ])("rejects %s in the nested state-lock policy (#7744)", (_label, override, expected) => { + const base = protectionTransitionPlan(); + expect(() => + prepareRuntimeProviderStateMutationPlan({ + ...base, + stateLockPlan: { ...base.stateLockPlan, ...override }, + }), + ).toThrow(expected); + }); + it("does not let inherited JSON hooks change the digest or size limit (#7744)", () => { const baseline = prepareRuntimeProviderStateMutationPlan(plan()); const objectToJson = Object.getOwnPropertyDescriptor(Object.prototype, "toJSON"); @@ -119,6 +602,24 @@ describe("runtime provider state mutation plan", () => { expect(() => prepareRuntimeProviderStateMutationPlan(accessorSelectors)).toThrow( /fixed data properties/u, ); + + const accessorStateLockPlan = protectionTransitionPlan(); + Object.defineProperty(accessorStateLockPlan.stateLockPlan, "readOnlyRoots", { + enumerable: true, + get: () => ["scripts"], + }); + expect(() => prepareRuntimeProviderStateMutationPlan(accessorStateLockPlan)).toThrow( + /fixed data properties/u, + ); + + const accessorStateLockArray = protectionTransitionPlan(); + Object.defineProperty(accessorStateLockArray.stateLockPlan.readOnlyRoots, "0", { + enumerable: true, + get: () => "scripts", + }); + expect(() => prepareRuntimeProviderStateMutationPlan(accessorStateLockArray)).toThrow( + /fixed data properties/u, + ); }); it.each([ diff --git a/src/lib/onboard/runtime-provider/state-mutation.ts b/src/lib/onboard/runtime-provider/state-mutation.ts index acc77cfa857..c9f07c833cc 100644 --- a/src/lib/onboard/runtime-provider/state-mutation.ts +++ b/src/lib/onboard/runtime-provider/state-mutation.ts @@ -4,11 +4,14 @@ import { createHash } from "node:crypto"; import path from "node:path"; +import type { AgentDefinition, AgentStateLockPlan } from "../../agent/definition-types"; import { RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION, type RuntimeProviderPreparedStateMutationPlan, type RuntimeProviderStateMutationPlan, + type RuntimeProviderStateMutationProtectionPosture, type RuntimeProviderStateMutationSelector, + type RuntimeProviderStateMutationStateLockPlan, } from "./contract"; const MAX_PLAN_BYTES = 64 * 1024; @@ -16,9 +19,14 @@ const MAX_STATE_ROOT_BYTES = 4096; const MAX_SELECTORS = 256; const MAX_RELATIVE_PATH_BYTES = 512; const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u; -const PREFIX_PATTERN = /^[A-Za-z0-9._-]{1,128}$/u; +const TOP_LEVEL_NAME_PATTERN = /^[A-Za-z0-9._-]+$/u; const SHA256_PATTERN = /^[a-f0-9]{64}$/u; -const INTENTS = new Set(["protection-transition", "restore"]); +const PROTECTION_POSTURES = new Set(["locked", "mutable"]); + +export type RuntimeProviderProtectionTransitionAgent = Pick< + AgentDefinition, + "name" | "configPaths" | "stateLockPlan" +>; function fail(message: string): never { throw new Error(`Runtime provider state mutation plan is invalid: ${message}`); @@ -143,6 +151,46 @@ function canonicalStateRoot(value: unknown): string { return candidate; } +function canonicalPrefix(value: unknown, label: string): string { + const prefix = boundedString(value, label, MAX_RELATIVE_PATH_BYTES); + if (prefix === "." || prefix === ".." || !TOP_LEVEL_NAME_PATTERN.test(prefix)) { + fail(`${label} is not canonical`); + } + return prefix; +} + +function canonicalTopLevelName(value: unknown, label: string): string { + const name = boundedString(value, label, MAX_RELATIVE_PATH_BYTES); + if (name === "." || name === ".." || !TOP_LEVEL_NAME_PATTERN.test(name)) { + fail(`${label} must contain one top-level name using ASCII letters, digits, '.', '_', or '-'`); + } + return name; +} + +function canonicalWritableSubpath(value: unknown, label: string): string { + const candidate = canonicalRelativePath(value, label); + const components = candidate.split("/"); + if (components.length < 2) { + fail(`${label} must be beneath a declared top-level root`); + } + if (components.some((component) => component.includes("*") && component !== "*")) { + fail(`${label} may use '*' only as a complete path component`); + } + if (components.at(-1) === "*") { + fail(`${label} may not end with a wildcard component`); + } + return candidate; +} + +function writablePatternsOverlap(first: string, second: string): boolean { + const firstComponents = first.split("/"); + const secondComponents = second.split("/"); + return firstComponents.every((left, index) => { + const right = secondComponents[index]; + return right === undefined || left === "*" || right === "*" || left === right; + }); +} + function normalizeSelector(value: unknown, index: number): RuntimeProviderStateMutationSelector { const selector = snapshotRecord(value, `selector ${String(index)}`); if (selector.kind === "path") { @@ -154,15 +202,26 @@ function normalizeSelector(value: unknown, index: number): RuntimeProviderStateM } if (selector.kind === "prefix") { requireExactKeys(selector, ["kind", "prefix"], `selector ${String(index)}`); - const prefix = boundedString(selector.prefix, `selector ${String(index)} prefix`, 128); - if (prefix === "." || prefix === ".." || !PREFIX_PATTERN.test(prefix)) { - fail(`selector ${String(index)} prefix is not canonical`); - } + const prefix = canonicalPrefix(selector.prefix, `selector ${String(index)} prefix`); return Object.freeze({ kind: "prefix", prefix }); } fail(`selector ${String(index)} kind is unsupported`); } +function selectorIdentity(selector: RuntimeProviderStateMutationSelector): string { + return selector.kind === "path" ? `path:${selector.path}` : `prefix:${selector.prefix}`; +} + +function protectionPosture( + value: unknown, + label: string, +): RuntimeProviderStateMutationProtectionPosture { + if (!PROTECTION_POSTURES.has(value as string)) { + fail(`${label} must be exactly locked or mutable`); + } + return value as RuntimeProviderStateMutationProtectionPosture; +} + function serializePlan(plan: RuntimeProviderStateMutationPlan): string { const selectors: Array> = plan.selectors.map((selector) => { const transport: Record = Object.create(null); @@ -176,6 +235,11 @@ function serializePlan(plan: RuntimeProviderStateMutationPlan): string { const transport: Record = Object.create(null); transport.schemaVersion = plan.schemaVersion; transport.intent = plan.intent; + if (plan.intent === "protection-transition") { + transport.target = plan.target; + transport.rollback = plan.rollback; + transport.stateLockPlan = stateLockPlanTransport(plan.stateLockPlan); + } transport.stateRoot = plan.stateRoot; transport.selectors = selectors; transport.projectionSha256 = plan.projectionSha256; @@ -186,47 +250,339 @@ function sha256(value: string): string { return createHash("sha256").update(value, "utf8").digest("hex"); } +function compareUtf8(left: string, right: string): number { + return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")); +} + +function prototypeFreeStringArray(values: readonly string[]): string[] { + const copy = [...values]; + Object.setPrototypeOf(copy, null); + return copy; +} + +function stateLockPlanTransport( + stateLockPlan: RuntimeProviderStateMutationStateLockPlan, +): Record { + const transport: Record = Object.create(null); + transport.version = stateLockPlan.version; + transport.readOnlyRoots = prototypeFreeStringArray(stateLockPlan.readOnlyRoots); + transport.confidentialRoots = prototypeFreeStringArray(stateLockPlan.confidentialRoots); + transport.readOnlyPrefixes = prototypeFreeStringArray(stateLockPlan.readOnlyPrefixes); + transport.confidentialPrefixes = prototypeFreeStringArray(stateLockPlan.confidentialPrefixes); + transport.writableSubpaths = prototypeFreeStringArray(stateLockPlan.writableSubpaths); + return transport; +} + +function serializeAgentDefinitionProtectionProjection( + agentName: string, + config: { + readonly dir: string; + readonly configFile: string; + readonly envFile: string | null; + readonly shieldsFiles: readonly string[]; + }, + stateLockPlan: RuntimeProviderStateMutationStateLockPlan, +): string { + const configTransport: Record = Object.create(null); + configTransport.dir = config.dir; + configTransport.configFile = config.configFile; + configTransport.envFile = config.envFile; + configTransport.shieldsFiles = prototypeFreeStringArray(config.shieldsFiles); + + const projectionTransport: Record = Object.create(null); + projectionTransport.agentName = agentName; + projectionTransport.config = configTransport; + projectionTransport.stateLockPlan = stateLockPlanTransport(stateLockPlan); + return JSON.stringify(projectionTransport); +} + +function exactProjectionStrings(values: readonly string[], label: string): string[] { + if (!Array.isArray(values) || values.some((value) => typeof value !== "string")) { + fail(`AgentDefinition ${label} must be a string array`); + } + return [...values]; +} + +function normalizeStateLockStringArray( + value: unknown, + label: string, + normalize: (entry: unknown, label: string) => string, +): readonly string[] { + const entries = snapshotBoundedArray(value, label, MAX_SELECTORS) + .map((entry, index) => normalize(entry, `${label} ${String(index)}`)) + .sort(compareUtf8); + if (new Set(entries).size !== entries.length) { + fail(`${label} must not contain duplicates`); + } + return Object.freeze(entries); +} + +function normalizeStateLockPlan( + value: unknown, + label: string, +): RuntimeProviderStateMutationStateLockPlan { + const input = snapshotRecord(value, label); + requireExactKeys( + input, + [ + "confidentialPrefixes", + "confidentialRoots", + "readOnlyPrefixes", + "readOnlyRoots", + "version", + "writableSubpaths", + ], + label, + ); + if (input.version !== 1) fail(`${label} version is unsupported`); + + const readOnlyRoots = normalizeStateLockStringArray( + input.readOnlyRoots, + `${label} read-only roots`, + canonicalTopLevelName, + ); + const confidentialRoots = normalizeStateLockStringArray( + input.confidentialRoots, + `${label} confidential roots`, + canonicalTopLevelName, + ); + const readOnlyPrefixes = normalizeStateLockStringArray( + input.readOnlyPrefixes, + `${label} read-only prefixes`, + canonicalPrefix, + ); + const confidentialPrefixes = normalizeStateLockStringArray( + input.confidentialPrefixes, + `${label} confidential prefixes`, + canonicalPrefix, + ); + const writableSubpaths = normalizeStateLockStringArray( + input.writableSubpaths, + `${label} writable subpaths`, + canonicalWritableSubpath, + ); + + const roots = [...readOnlyRoots, ...confidentialRoots]; + if (new Set(roots).size !== roots.length) { + fail(`${label} assigns one root more than once`); + } + const prefixes = [...readOnlyPrefixes, ...confidentialPrefixes]; + if (new Set(prefixes).size !== prefixes.length) { + fail(`${label} assigns one prefix more than once`); + } + if (roots.some((root) => prefixes.some((prefix) => root.startsWith(prefix)))) { + fail(`${label} root and prefix policies must not overlap`); + } + for (let index = 0; index < prefixes.length; index += 1) { + if ( + prefixes + .slice(index + 1) + .some((other) => prefixes[index].startsWith(other) || other.startsWith(prefixes[index])) + ) { + fail(`${label} prefix policies must not overlap`); + } + } + if ( + writableSubpaths.some((writable) => !readOnlyRoots.includes(writable.split("/", 1)[0] ?? "")) + ) { + fail(`${label} writable subpaths must be beneath a read-only root`); + } + for (let index = 0; index < writableSubpaths.length; index += 1) { + if ( + writableSubpaths + .slice(index + 1) + .some((other) => writablePatternsOverlap(writableSubpaths[index], other)) + ) { + fail(`${label} writable subpaths must not overlap`); + } + } + + return Object.freeze({ + version: 1, + readOnlyRoots, + confidentialRoots, + readOnlyPrefixes, + confidentialPrefixes, + writableSubpaths, + }); +} + +function normalizedStateLockProjection( + plan: AgentStateLockPlan, +): RuntimeProviderStateMutationStateLockPlan { + return normalizeStateLockPlan(plan, "AgentDefinition state lock plan"); +} + +function requireStateLockPlanScope( + plan: RuntimeProviderStateMutationStateLockPlan, + selectors: readonly RuntimeProviderStateMutationSelector[], +): void { + const identities = new Set( + selectors.map((selector) => + selector.kind === "path" ? `path:${selector.path}` : `prefix:${selector.prefix}`, + ), + ); + const required = [ + ...plan.readOnlyRoots.map((root) => `path:${root}`), + ...plan.confidentialRoots.map((root) => `path:${root}`), + ...plan.readOnlyPrefixes.map((prefix) => `prefix:${prefix}`), + ...plan.confidentialPrefixes.map((prefix) => `prefix:${prefix}`), + ]; + if (required.some((identity) => !identities.has(identity))) { + fail("state lock plan policy must be represented by exact selectors"); + } +} + +/** + * Compile the selected AgentDefinition protection projection into the bounded + * provider plan. The nested state-lock policy gives a fixed helper the exact + * recursive semantics; the projection digest also binds the selected agent + * name, config paths, and normalized policy. + */ +export function prepareAgentDefinitionProtectionTransitionPlan( + agent: RuntimeProviderProtectionTransitionAgent, + target: RuntimeProviderStateMutationProtectionPosture, + rollback: RuntimeProviderStateMutationProtectionPosture, +): RuntimeProviderPreparedStateMutationPlan { + const config = agent.configPaths; + const stateLockPlan = normalizedStateLockProjection(agent.stateLockPlan); + const projection = { + agentName: boundedString(agent.name, "AgentDefinition name", 128), + config: { + dir: canonicalStateRoot(config.dir), + configFile: canonicalRelativePath(config.configFile, "AgentDefinition config file"), + envFile: + config.envFile === null + ? null + : canonicalRelativePath(config.envFile, "AgentDefinition environment file"), + shieldsFiles: exactProjectionStrings(config.shieldsFiles, "config shields files").map( + (value, index) => + canonicalRelativePath(value, `AgentDefinition shields file ${String(index)}`), + ), + }, + stateLockPlan, + } as const; + const paths = [ + projection.config.configFile, + ".config-hash", + ...(projection.config.envFile === null ? [] : [projection.config.envFile]), + ...projection.config.shieldsFiles, + ]; + const selectors: RuntimeProviderStateMutationSelector[] = [ + ...paths.map((entry) => ({ kind: "path" as const, path: entry })), + ...stateLockPlan.readOnlyRoots.map((entry) => ({ kind: "path" as const, path: entry })), + ...stateLockPlan.confidentialRoots.map((entry) => ({ kind: "path" as const, path: entry })), + ...stateLockPlan.readOnlyPrefixes.map((entry) => ({ kind: "prefix" as const, prefix: entry })), + ...stateLockPlan.confidentialPrefixes.map((entry) => ({ + kind: "prefix" as const, + prefix: entry, + })), + ]; + const uniqueSelectors = new Map(); + for (const selector of selectors) { + const identity = + selector.kind === "path" ? `path:${selector.path}` : `prefix:${selector.prefix}`; + uniqueSelectors.set(identity, selector); + } + const orderedSelectors = [...uniqueSelectors] + .sort(([left], [right]) => compareUtf8(left, right)) + .map(([, selector]) => selector); + return prepareRuntimeProviderStateMutationPlan({ + schemaVersion: RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION, + intent: "protection-transition", + target, + rollback, + stateRoot: projection.config.dir, + selectors: orderedSelectors, + stateLockPlan, + projectionSha256: sha256( + serializeAgentDefinitionProtectionProjection( + projection.agentName, + projection.config, + stateLockPlan, + ), + ), + }); +} + /** Validate, canonicalize, clone, freeze, and digest an untrusted state plan. */ export function prepareRuntimeProviderStateMutationPlan( value: unknown, ): RuntimeProviderPreparedStateMutationPlan { const input = snapshotRecord(value, "plan"); - requireExactKeys( - input, - ["intent", "projectionSha256", "schemaVersion", "selectors", "stateRoot"], - "plan", - ); if (input.schemaVersion !== RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION) { fail("plan schema version is unsupported"); } - if (!INTENTS.has(input.intent as string)) fail("plan intent is unsupported"); + if (input.intent === "protection-transition") { + requireExactKeys( + input, + [ + "intent", + "projectionSha256", + "rollback", + "schemaVersion", + "selectors", + "stateLockPlan", + "stateRoot", + "target", + ], + "plan", + ); + } else if (input.intent === "restore") { + requireExactKeys( + input, + ["intent", "projectionSha256", "schemaVersion", "selectors", "stateRoot"], + "plan", + ); + } else { + fail("plan intent is unsupported"); + } const selectorInputs = snapshotBoundedArray(input.selectors, "selectors", MAX_SELECTORS); if (selectorInputs.length === 0) { fail("selectors must be one non-empty bounded array"); } - const selectors = selectorInputs.map(normalizeSelector); - const identities = selectors.map((selector) => - selector.kind === "path" ? `path:${selector.path}` : `prefix:${selector.prefix}`, - ); + const selectors = selectorInputs + .map(normalizeSelector) + .sort((left, right) => compareUtf8(selectorIdentity(left), selectorIdentity(right))); + const identities = selectors.map(selectorIdentity); if (new Set(identities).size !== identities.length) { fail("selectors must not repeat a path or prefix"); } if (typeof input.projectionSha256 !== "string" || !SHA256_PATTERN.test(input.projectionSha256)) { fail("AgentDefinition projection digest must be lowercase SHA-256"); } - const plan = Object.freeze({ + const common = { schemaVersion: RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION, - intent: input.intent as RuntimeProviderStateMutationPlan["intent"], stateRoot: canonicalStateRoot(input.stateRoot), selectors: Object.freeze(selectors), projectionSha256: input.projectionSha256, - }); + } as const; + let plan: RuntimeProviderStateMutationPlan; + if (input.intent === "protection-transition") { + const stateLockPlan = normalizeStateLockPlan(input.stateLockPlan, "state lock plan"); + requireStateLockPlanScope(stateLockPlan, selectors); + const target = protectionPosture(input.target, "protection-transition target"); + const rollback = protectionPosture(input.rollback, "protection-transition rollback"); + if (target === rollback) { + fail("protection-transition target and rollback postures must differ"); + } + plan = Object.freeze({ + ...common, + intent: "protection-transition", + target, + rollback, + stateLockPlan, + }); + } else { + plan = Object.freeze({ ...common, intent: "restore" }); + } const serializedPlan = serializePlan(plan); if (Buffer.byteLength(serializedPlan, "utf8") > MAX_PLAN_BYTES) { fail("canonical plan exceeds its bounded transport"); } return Object.freeze({ plan, + serializedPlan, planSha256: sha256(serializedPlan), projectionSha256: plan.projectionSha256, }); diff --git a/src/lib/onboard/sandbox-create-launch.ts b/src/lib/onboard/sandbox-create-launch.ts index 563904cd0e0..c9389a275be 100644 --- a/src/lib/onboard/sandbox-create-launch.ts +++ b/src/lib/onboard/sandbox-create-launch.ts @@ -26,6 +26,12 @@ import { type OpenshellShellCommand = (args: string[]) => string; type OpenshellArgv = (args: string[]) => string[]; +export const OPENSHELL_SANDBOX_SUPERVISOR_ARGV = Object.freeze([ + "/opt/openshell/bin/openshell-sandbox", + "--workdir", + "/sandbox", +] as const); + // These non-secret scheduler controls are intentionally forwarded for bounded // live-test and operator tuning. Keep this as an exact allowlist: the host's // broader NEMOCLAW_* environment must not become sandbox runtime input. diff --git a/src/lib/sandbox/agent-config.ts b/src/lib/sandbox/agent-config.ts index 8bfed324527..67316c87faf 100644 --- a/src/lib/sandbox/agent-config.ts +++ b/src/lib/sandbox/agent-config.ts @@ -2,7 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; -import type { AgentStateLockPlan } from "../agent/definition-types"; +import type { AgentDefinition, AgentStateLockPlan } from "../agent/definition-types"; +import type { SandboxEntry } from "../state/registry/types"; const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/; const SANDBOX_CONFIG_ROOT = "/sandbox/"; @@ -49,6 +50,35 @@ function defaultDependencies(): AgentConfigDependencies { return { getSandbox: registry.getSandbox, loadAgent: agentDefs.loadAgent }; } +export interface RegisteredSandboxAgentAuthority { + readonly sandbox: SandboxEntry; + readonly agent: AgentDefinition; +} + +/** Resolve one exact registry entry together with its current manifest authority. */ +export function resolveRegisteredSandboxAgentAuthority( + sandboxName: string, +): RegisteredSandboxAgentAuthority { + const registry: typeof import("../state/registry") = require("../state/registry"); + const sandbox = registry.getSandbox(sandboxName); + if (!sandbox || sandbox.name !== sandboxName || !sandbox.agent) { + throw new Error(`Sandbox '${sandboxName}' has no exact registered agent-definition authority`); + } + const agent = resolveCurrentAgentDefinition(sandbox.agent); + if (agent.name !== sandbox.agent) { + throw new Error( + `Sandbox '${sandboxName}' agent-definition authority changed during resolution`, + ); + } + return Object.freeze({ sandbox, agent }); +} + +/** Load the current manifest without exposing the high-fan-in definition facade. */ +export function resolveCurrentAgentDefinition(agentName: string): AgentDefinition { + const agentDefs: typeof import("../agent/defs") = require("../agent/defs"); + return agentDefs.loadAgent(agentName); +} + export function resolveAgentStateLockContract( agentName: string, loadAgent: AgentConfigDependencies["loadAgent"] = defaultDependencies().loadAgent, diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index f342964d077..36062a8d0d5 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -51,6 +51,7 @@ const { const { privilegedSandboxExecArgv, resolveDirectSandboxContainer, + withPrivilegedSandboxExecutionLease, }: typeof import("./privileged-exec") = require("./privileged-exec"); const { buildHermesUpstreamHeader, @@ -182,25 +183,44 @@ function privilegedSandboxExec( opts: { input?: string | Buffer; timeout?: number } = {}, ): string { const hasInput = opts.input !== undefined; - return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, hasInput, true), { - input: opts.input, - stdio: hasInput ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"], - timeout: opts.timeout ?? 30000, - }); + return withPrivilegedSandboxExecutionLease( + sandboxName, + "sandbox config privileged execution", + () => + 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, expectedContainerId?: string) { return { run: (cmd: string[], input?: string) => { - let argv: string[]; try { - argv = privilegedSandboxExecArgv( - sandboxName, - cmd, - input !== undefined, - true, - expectedContainerId, - ); + return withPrivilegedSandboxExecutionLease(sandboxName, "OpenClaw config guard", () => { + const argv = privilegedSandboxExecArgv( + sandboxName, + cmd, + input !== undefined, + true, + expectedContainerId, + ); + const result = dockerSpawnSync(argv, { + 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 } : {}), + }; + }); } catch (error) { return { status: null, @@ -210,19 +230,6 @@ function openClawConfigGuardExec(sandboxName: string, expectedContainerId?: stri error: error instanceof Error ? error.message : String(error), }; } - const result = dockerSpawnSync(argv, { - 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 } : {}), - }; }, }; } @@ -1520,8 +1527,8 @@ export { recomputeSandboxConfigHash, resolveAgentConfig, restartSandboxAgentAfterConfigSet, - rewriteConfigUrlsWithDnsPinning, restoreHermesDashboardConfig, + rewriteConfigUrlsWithDnsPinning, seedHermesDashboardConfig, setDotpath, validateConfigDotpath, diff --git a/src/lib/sandbox/privileged-exec-exclusion.test.ts b/src/lib/sandbox/privileged-exec-exclusion.test.ts new file mode 100644 index 00000000000..c96f2a95c8d --- /dev/null +++ b/src/lib/sandbox/privileged-exec-exclusion.test.ts @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type ChildProcess, 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, vi } from "vitest"; +import { + createOrdinaryExecReleaseSleeper, + releaseAndStopChild, + waitForChildExit, +} from "../../../test/helpers/privileged-exec-test-helpers"; + +import { + createFilePersistedEngineLifecycleStore, + PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, +} from "../onboard/runtime-provider/persisted-engine-lifecycle"; +import { ShieldsTransitionLockManager } from "../shields/transition-lock"; + +const roots: string[] = []; +const waitBuffer = new Int32Array(new SharedArrayBuffer(4)); +const tsxLoaderPath = import.meta.resolve("tsx"); + +function temporaryStateDir(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-direct-exec-exclusion-")); + roots.push(root); + return root; +} + +function childEnvironment(stateDir: string): NodeJS.ProcessEnv { + const isolatedHome = path.join(stateDir, "home"); + fs.mkdirSync(isolatedHome, { recursive: true }); + return { + ...process.env, + HOME: isolatedHome, + NEMOCLAW_TEST_BASE_HOME: isolatedHome, + NEMOCLAW_TEST_STATE_DIR: stateDir, + VITEST: "true", + }; +} + +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { force: true, recursive: true }); +}); + +describe("privileged direct-execution exclusion", () => { + it("retries release-marker creation after a transient write failure", () => { + const stateDir = temporaryStateDir(); + const releaseDir = path.join(stateDir, "late-release-dir"); + const releasePath = path.join(releaseDir, "ordinary.release"); + const ordinaryExecRelease = createOrdinaryExecReleaseSleeper(releasePath, waitBuffer); + + expect(() => ordinaryExecRelease.sleep(1)).toThrow(expect.objectContaining({ code: "ENOENT" })); + expect(ordinaryExecRelease.wasReleased()).toBe(false); + + fs.mkdirSync(releaseDir); + expect(() => ordinaryExecRelease.sleep(1)).not.toThrow(); + expect(ordinaryExecRelease.wasReleased()).toBe(true); + expect(fs.readFileSync(releasePath, "utf8")).toBe("release"); + }); + + it("stops the child even when release-marker creation fails", async () => { + const stateDir = temporaryStateDir(); + const releasePath = path.join(stateDir, "missing", "ordinary.release"); + const child = { + exitCode: null, + kill: vi.fn(), + } as unknown as ChildProcess; + vi.mocked(child.kill).mockImplementation(() => { + Object.defineProperty(child, "exitCode", { configurable: true, value: 137 }); + return true; + }); + + await expect(releaseAndStopChild(child, releasePath)).rejects.toMatchObject({ code: "ENOENT" }); + expect(child.kill).toHaveBeenCalledOnce(); + expect(child.kill).toHaveBeenCalledWith("SIGKILL"); + }); + + it.runIf(process.platform !== "win32")( + "does not follow a dangling release-marker symlink during child cleanup", + async () => { + const stateDir = temporaryStateDir(); + const releasePath = path.join(stateDir, "ordinary.release"); + const targetPath = path.join(stateDir, "symlink-target"); + fs.symlinkSync(targetPath, releasePath); + + await releaseAndStopChild({ exitCode: 0 } as ChildProcess, releasePath); + + expect(fs.lstatSync(releasePath).isSymbolicLink()).toBe(true); + expect(fs.existsSync(targetPath)).toBe(false); + }, + ); + + it("drains an in-flight exec before provider fencing and rejects the next exec before spawn", async () => { + const stateDir = temporaryStateDir(); + const readyPath = path.join(stateDir, "ordinary.ready"); + const releasePath = path.join(stateDir, "ordinary.release"); + const lateSpawnPath = path.join(stateDir, "late.spawned"); + const helperPath = path.join(import.meta.dirname, "privileged-exec.ts"); + const environment = childEnvironment(stateDir); + const holderScript = [ + `const fs=require("node:fs")`, + `const {withPrivilegedSandboxExecutionLease}=require(${JSON.stringify(helperPath)})`, + `const [ready,release]=process.argv.slice(1)`, + `const waitBuffer=new Int32Array(new SharedArrayBuffer(4))`, + `withPrivilegedSandboxExecutionLease("alpha","ordinary exec in flight",()=>{fs.writeFileSync(ready,"ready");const deadline=Date.now()+10000;while(!fs.existsSync(release)){if(Date.now()>=deadline)throw new Error("release handshake timed out");Atomics.wait(waitBuffer,0,0,10)}})`, + ].join(";"); + const holder = spawn( + process.execPath, + ["--import", tsxLoaderPath, "-e", holderScript, readyPath, releasePath], + { env: environment, stdio: ["ignore", "ignore", "pipe"] }, + ); + const holderStderr: Buffer[] = []; + holder.stderr?.on("data", (chunk: Buffer) => holderStderr.push(chunk)); + + try { + await vi.waitFor( + () => { + expect(fs.existsSync(readyPath)).toBe(true); + }, + { interval: 10, timeout: 5_000 }, + ); + + const lifecycleStore = createFilePersistedEngineLifecycleStore(stateDir); + const ordinaryExecRelease = createOrdinaryExecReleaseSleeper(releasePath, waitBuffer); + const providerLock = new ShieldsTransitionLockManager({ + stateDir, + sleep: ordinaryExecRelease.sleep, + }); + const transactionId = "a".repeat(64); + const serializedPlan = '{"schemaVersion":1,"intent":"protection-transition"}'; + + providerLock.withShieldsTransitionLock( + "alpha", + "Docker runtime-provider state mutation acquire", + () => { + lifecycleStore.recordStateMutationIntent({ + schemaVersion: PERSISTED_ENGINE_STATE_MUTATION_INTENT_SCHEMA_VERSION, + transactionId, + serializedPlan, + planSha256: createHash("sha256").update(serializedPlan, "utf8").digest("hex"), + projectionSha256: "d".repeat(64), + nonce: "e".repeat(64), + }); + lifecycleStore.create({ + schemaVersion: PERSISTED_ENGINE_LIFECYCLE_SCHEMA_VERSION, + transactionId, + action: "state-mutation", + phase: "prepared", + sandboxName: "alpha", + resources: [{ role: "target", runtimeId: "runtime-alpha" }], + runtimeStateSha256: "b".repeat(64), + engineAuthority: { + schemaVersion: 1, + providerId: "docker", + operation: "sandbox-lifecycle", + engineId: "docker", + authorityId: "docker:test", + bindingSha256: "c".repeat(64), + }, + resultSha256: null, + }); + lifecycleStore.authorizeMutation(transactionId); + const lease = lifecycleStore.acquireMutationExecution(transactionId); + try { + lifecycleStore.establishStateMutationFence(lease); + } finally { + lifecycleStore.releaseMutationExecution(lease); + } + }, + { pollIntervalMs: 10, waitTimeoutMs: 5_000 }, + ); + + expect(ordinaryExecRelease.wasReleased()).toBe(true); + expect(lifecycleStore.load(transactionId)?.phase).toBe("fence-established"); + expect(await waitForChildExit(holder)).toBe(0); + expect(Buffer.concat(holderStderr).toString("utf8")).toBe(""); + + const lateScript = [ + `const fs=require("node:fs")`, + `const {withPrivilegedSandboxExecutionLease}=require(${JSON.stringify(helperPath)})`, + `const marker=process.argv[1]`, + `try{withPrivilegedSandboxExecutionLease("alpha","late ordinary exec",()=>fs.writeFileSync(marker,"spawned"));process.exitCode=2}catch(error){process.stderr.write(error instanceof Error?error.message:String(error))}`, + ].join(";"); + const late = spawnSync( + process.execPath, + ["--import", tsxLoaderPath, "-e", lateScript, lateSpawnPath], + { encoding: "utf8", env: environment }, + ); + + expect(late.status, late.stderr).toBe(0); + expect(late.stderr).toMatch(/state mutation owns direct-container execution/i); + expect(fs.existsSync(lateSpawnPath)).toBe(false); + } finally { + await releaseAndStopChild(holder, releasePath); + } + }, 15_000); +}); diff --git a/src/lib/sandbox/privileged-exec.test.ts b/src/lib/sandbox/privileged-exec.test.ts index 1526547ed94..f6d520d4ef7 100644 --- a/src/lib/sandbox/privileged-exec.test.ts +++ b/src/lib/sandbox/privileged-exec.test.ts @@ -1,8 +1,12 @@ // 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 { describe, expect, it, vi } from "vitest"; +import { createPersistedLifecycleStoreOrThrow } from "../../../test/helpers/privileged-exec-test-helpers"; // The shared source hook preserves the writable CommonJS cache used by these mocks. const require = createRequire(import.meta.url); @@ -12,6 +16,11 @@ const dockerRunPath = require.resolve("../adapters/docker/run"); const portableLifecyclePath = require.resolve("../onboard/experimental/portable-demo-lifecycle"); const registryPath = require.resolve("../state/registry"); const lifecycleGenerationPath = require.resolve("../state/registry/lifecycle-generation"); +const persistedLifecyclePath = require.resolve( + "../onboard/runtime-provider/persisted-engine-lifecycle", +); +const statePathsPath = require.resolve("../state/paths"); +const transitionLockPath = require.resolve("../shields/transition-lock"); const { containerNameMatchesSandbox, selectDirectSandboxContainer } = require(helperPath); function restoreRequireCacheEntry(modulePath: string, priorEntry: unknown): void { @@ -42,6 +51,12 @@ function withPrivilegedExecMocks( registryGeneration?: string; }, ) => { assertRuntimeAuthority: () => void; containerId: string; dockerHost: string } | null; + stateMutationGate?: { + readonly active: boolean; + readonly stateDir: string; + readonly storeError?: Error; + }; + withShieldsTransitionLock?: (sandboxName: string, operation: string, fn: () => T) => T; }, run: (helper: typeof import("./privileged-exec")) => T, ): T { @@ -50,6 +65,9 @@ function withPrivilegedExecMocks( const priorPortableLifecycle = require.cache[portableLifecyclePath]; const priorRegistry = require.cache[registryPath]; const priorLifecycleGeneration = require.cache[lifecycleGenerationPath]; + const priorPersistedLifecycle = require.cache[persistedLifecyclePath]; + const priorStatePaths = require.cache[statePathsPath]; + const priorTransitionLock = require.cache[transitionLockPath]; delete require.cache[helperPath]; requireCache[dockerRunPath] = { @@ -85,6 +103,36 @@ function withPrivilegedExecMocks( deps.compareAndSetLegacySandboxLifecycleGeneration ?? (() => false), }, } as any; + requireCache[persistedLifecyclePath] = { + id: persistedLifecyclePath, + filename: persistedLifecyclePath, + loaded: true, + exports: { + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY: "runtime-provider-lifecycle", + createFilePersistedEngineLifecycleStore: () => + createPersistedLifecycleStoreOrThrow(deps.stateMutationGate), + hasActivePersistedEngineStateMutationTarget: () => deps.stateMutationGate?.active ?? false, + }, + } as any; + requireCache[statePathsPath] = { + id: statePathsPath, + filename: statePathsPath, + loaded: true, + exports: { + resolveNemoclawStateDir: () => deps.stateMutationGate?.stateDir ?? "/nonexistent", + }, + } as any; + requireCache[transitionLockPath] = { + id: transitionLockPath, + filename: transitionLockPath, + loaded: true, + exports: { + resolveShieldsStateDir: () => deps.stateMutationGate?.stateDir ?? "/nonexistent", + withShieldsTransitionLock: + deps.withShieldsTransitionLock ?? + ((_sandboxName: string, _operation: string, fn: () => T): T => fn()), + }, + } as any; try { return run(require(helperPath)); @@ -94,6 +142,9 @@ function withPrivilegedExecMocks( restoreRequireCacheEntry(portableLifecyclePath, priorPortableLifecycle); restoreRequireCacheEntry(registryPath, priorRegistry); restoreRequireCacheEntry(lifecycleGenerationPath, priorLifecycleGeneration); + restoreRequireCacheEntry(persistedLifecyclePath, priorPersistedLifecycle); + restoreRequireCacheEntry(statePathsPath, priorStatePaths); + restoreRequireCacheEntry(transitionLockPath, priorTransitionLock); } } @@ -184,6 +235,109 @@ describe("privileged sandbox exec routing", () => { ); }); + it("rejects every ordinary direct exec while a provider target claim is active", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-direct-exec-gate-")); + fs.mkdirSync(path.join(stateDir, "runtime-provider-lifecycle")); + let dockerPsCalls = 0; + try { + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "docker" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: () => { + dockerPsCalls += 1; + return "immutable-alpha-id\topenshell-alpha\n"; + }, + stateMutationGate: { active: true, stateDir }, + }, + ({ privilegedSandboxExecArgv }) => { + expect(() => privilegedSandboxExecArgv("alpha", ["sh", "-c", "write"])).toThrow( + /state mutation owns direct-container execution.*provider fence is released/i, + ); + }, + ); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + expect(dockerPsCalls).toBe(0); + }); + + it("fails closed when a present lifecycle ledger cannot be validated", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-direct-exec-invalid-gate-")); + fs.symlinkSync( + path.join(stateDir, "missing-ledger-target"), + path.join(stateDir, "runtime-provider-lifecycle"), + ); + let dockerPsCalls = 0; + try { + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "docker" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: () => { + dockerPsCalls += 1; + return "immutable-alpha-id\topenshell-alpha\n"; + }, + stateMutationGate: { + active: false, + stateDir, + storeError: new Error("lifecycle ledger is present but invalid"), + }, + }, + ({ privilegedSandboxExecArgv }) => { + expect(() => privilegedSandboxExecArgv("alpha", ["id"])).toThrow( + /lifecycle ledger is present but invalid/u, + ); + }, + ); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + expect(dockerPsCalls).toBe(0); + }); + + it("holds the shared exclusion across target check and the complete exec callback", () => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-direct-exec-lease-")); + fs.mkdirSync(path.join(stateDir, "runtime-provider-lifecycle")); + const events: string[] = []; + let lockHeld = false; + try { + withPrivilegedExecMocks( + { + getSandbox: () => ({ name: "alpha", openshellDriver: "docker" }), + listSandboxes: () => ({ sandboxes: [{ name: "alpha" }], defaultSandbox: "alpha" }), + dockerCapture: () => "immutable-alpha-id\topenshell-alpha\n", + stateMutationGate: { active: false, stateDir }, + withShieldsTransitionLock: (sandboxName, operation, fn) => { + events.push(`lock:${sandboxName}:${operation}`); + lockHeld = true; + try { + return fn(); + } finally { + events.push("unlock"); + lockHeld = false; + } + }, + }, + ({ withPrivilegedSandboxExecutionLease }) => { + const result = withPrivilegedSandboxExecutionLease("alpha", "test subprocess", () => { + expect(lockHeld).toBe(true); + events.push("spawn-and-wait"); + return "complete"; + }); + expect(result).toBe("complete"); + }, + ); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } + expect(events).toEqual([ + "lock:alpha:privileged direct-container execution: test subprocess", + "spawn-and-wait", + "unlock", + ]); + }); + it("uses the receipt-owned Podman socket when the default Docker daemon has no container (#8584)", () => { let dockerPsCalls = 0; const assertRuntimeAuthority = vi.fn(); diff --git a/src/lib/sandbox/privileged-exec.ts b/src/lib/sandbox/privileged-exec.ts index da53f5baf5e..1ea9e8f5d45 100644 --- a/src/lib/sandbox/privileged-exec.ts +++ b/src/lib/sandbox/privileged-exec.ts @@ -1,9 +1,18 @@ // 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 { dockerCapture } from "../adapters/docker/run"; import { resolveSandboxContainerOwner } from "../domain/sandbox/container-owner"; import { resolvePortableDemoPrivilegedExecTarget } from "../onboard/experimental/portable-demo-lifecycle"; +import { + createFilePersistedEngineLifecycleStore, + hasActivePersistedEngineStateMutationTarget, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, +} from "../onboard/runtime-provider/persisted-engine-lifecycle"; +import { resolveShieldsStateDir, withShieldsTransitionLock } from "../shields/transition-lock"; import * as registry from "../state/registry"; import { compareAndSetLegacySandboxLifecycleGeneration } from "../state/registry/lifecycle-generation"; @@ -197,6 +206,46 @@ function unsupportedDirectDriverError(sandboxName: string, driver: string): Erro ); } +function assertNoActiveStateMutationTarget(sandboxName: string): void { + const stateDir = resolveShieldsStateDir(); + const lifecycleDirectory = path.join(stateDir, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY); + try { + fs.lstatSync(lifecycleDirectory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + const lifecycleStore = createFilePersistedEngineLifecycleStore(stateDir); + if (hasActivePersistedEngineStateMutationTarget(lifecycleStore, sandboxName)) { + throw new Error( + `Runtime provider state mutation owns direct-container execution for sandbox '${sandboxName}'; retry after the provider fence is released.`, + ); + } +} + +/** + * Serialize one ordinary direct-container execution against provider fence + * acquisition. The callback must include both argv resolution and the complete + * synchronous Docker subprocess lifetime. Taking the lock before checking the + * durable target claim closes the check/acquire/exec race: an older exec drains + * before the provider can publish its fence, while a later exec observes the + * claim and is rejected before it can spawn. + */ +function withPrivilegedSandboxExecutionLease( + sandboxName: string, + operation: string, + fn: () => T, +): T { + return withShieldsTransitionLock( + sandboxName, + `privileged direct-container execution: ${operation}`, + () => { + assertNoActiveStateMutationTarget(sandboxName); + return fn(); + }, + ); +} + function resolveDirectSandboxContainer(sandboxName: string, driver: string | null): string { const selected = findDirectSandboxContainer(sandboxName); if (selected) return selected; @@ -216,6 +265,7 @@ function privilegedSandboxExecArgv( if (driver !== null && driver !== "docker" && driver !== "vm") { throw unsupportedDirectDriverError(sandboxName, driver); } + assertNoActiveStateMutationTarget(sandboxName); const portableTarget = driver === "docker" ? resolvePortableDemoPrivilegedExecTarget(sandboxName, { @@ -281,4 +331,5 @@ export { privilegedSandboxExecArgv, resolveDirectSandboxContainer, selectDirectSandboxContainer, + withPrivilegedSandboxExecutionLease, }; diff --git a/src/lib/shields/flow.test.ts b/src/lib/shields/flow.test.ts index bb66585d15a..c60d36f0811 100644 --- a/src/lib/shields/flow.test.ts +++ b/src/lib/shields/flow.test.ts @@ -14,6 +14,7 @@ import { managedMcpPolicy, managedMcpSandbox, type ShieldsFlowHarnessOptions, + writeShieldsTimerAuthorizationProof, } from "../../../test/helpers/shields-flow-harness"; const requireDist = createRequire(import.meta.url); @@ -28,21 +29,10 @@ function createHarness(options: ShieldsFlowHarnessOptions = {}) { return createShieldsFlowHarness(requireDist, tmpDir, options); } -function expectStagedDriverNeutralRecovery( - errorSpy: MockInstance, - sandboxName: string, - cliName = "nemoclaw", -): string { - const output = errorSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain( - `Recovery: confirm the sandbox is running and ready, then retry \`${cliName} ${sandboxName} shields up\`.`, - ); - expect(output).toContain( - `If the retry still fails, rebuild a known-good baseline with \`${cliName} ${sandboxName} rebuild --yes\`.`, - ); - expect(output).not.toMatch(/kubectl/i); - return output; -} +const timerAuthorityFixtures: ReadonlyArray void]> = [ + ["missing", () => undefined], + ["malformed", (markerPath) => fs.writeFileSync(markerPath, "{not-json")], +]; function writeExpiredShieldsFixture( processToken: string, @@ -111,15 +101,14 @@ describe("shields command flow", () => { delete require.cache[requireDist.resolve("../cli/branding.js")]; }); - it("shieldsDown captures policy, unlocks config, saves state, and skips timer on request", { + it("shieldsDown captures policy, unlocks config, saves state, and authorizes a timer", { timeout: 30_000, }, () => { - const harness = createHarness(); + const harness = createHarness({ confirmOpenClawInodeFlags: true }); harness.shieldsDown("openclaw", { timeout: "5m", reason: "coverage", - skipTimer: true, throwOnError: true, }); @@ -134,7 +123,7 @@ describe("shields command flow", () => { expect(fs.existsSync(state.shieldsPolicySnapshotPath)).toBe(true); expect(harness.isShieldsDown("openclaw")).toBe(true); expect(harness.logSpy.mock.calls.flat().join("\n")).toContain( - "Config unlocked for openclaw (no auto-lockdown timer", + "Config unlocked for openclaw (auto-lockdown in: 5m)", ); }); @@ -156,7 +145,6 @@ describe("shields command flow", () => { harness.shieldsDown("openclaw", { timeout: "5m", reason: "managed MCP transition coverage", - skipTimer: true, throwOnError: true, }); @@ -169,6 +157,65 @@ describe("shields command flow", () => { expect(applied.network_policies).not.toHaveProperty("restrictive_baseline"); }); + it("isolates same-millisecond policy snapshots and cleanup across sandboxes", () => { + const fixedNow = Date.now(); + vi.spyOn(Date, "now").mockReturnValue(fixedNow); + const harness = createHarness({ confirmOpenClawInodeFlags: true }); + const alphaToken = "a".repeat(32); + const betaToken = "b".repeat(32); + const alphaPolicy = "version: 1\nnetwork_policies:\n alpha: {}\n"; + const betaPolicy = "version: 1\nnetwork_policies:\n beta: {}\n"; + harness.runCaptureSpy.mockReturnValue(alphaPolicy); + + harness.shieldsDown("alpha", { + timeout: "5m", + reason: "same millisecond alpha", + processToken: alphaToken, + throwOnError: true, + }); + + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const alphaState = JSON.parse( + fs.readFileSync(path.join(stateDir, "shields-alpha.json"), "utf-8"), + ); + harness.shieldsUp("alpha", { throwOnError: true }); + harness.runCaptureSpy.mockReturnValue("version: 1\nnetwork_policies:\n alpha_second: {}\n"); + harness.shieldsDown("alpha", { + timeout: "5m", + reason: "reused alpha token", + processToken: alphaToken, + throwOnError: true, + }); + const reusedAlphaState = JSON.parse( + fs.readFileSync(path.join(stateDir, "shields-alpha.json"), "utf-8"), + ); + expect(reusedAlphaState.shieldsPolicySnapshotPath).not.toBe( + alphaState.shieldsPolicySnapshotPath, + ); + expect(fs.existsSync(alphaState.shieldsPolicySnapshotPath)).toBe(true); + + harness.runCaptureSpy.mockReturnValue(betaPolicy); + expect(() => + harness.shieldsDown("beta", { + timeout: "5m", + reason: "same millisecond beta", + policy: "missing-beta-policy", + processToken: betaToken, + throwOnError: true, + }), + ).toThrow(/unknown policy/iu); + + expect(alphaState.shieldsPolicySnapshotPath).not.toBe( + reusedAlphaState.shieldsPolicySnapshotPath, + ); + expect(fs.readFileSync(alphaState.shieldsPolicySnapshotPath, "utf-8")).toBe(alphaPolicy); + expect( + fs + .readdirSync(stateDir) + .some((entry) => entry.startsWith(`policy-snapshot-beta-${betaToken}-`)), + ).toBe(false); + }); + it("cleans the staged managed MCP policy when timer startup fails", () => { const alpha = managedMcpPolicy("alpha"); const harness = createHarness({ @@ -214,7 +261,6 @@ describe("shields command flow", () => { harness.shieldsDown("openclaw", { timeout: "5m", reason: "cleanup coverage", - skipTimer: true, throwOnError: true, }), ).toThrow(/EISDIR|directory/i); @@ -418,6 +464,18 @@ describe("shields command flow", () => { 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"); + const timerControl = requireDist("./timer-control.js") as typeof import("./timer-control.js"); + vi.spyOn(timerControl, "isProcessAlive").mockReturnValue(true); + vi.spyOn(timerControl, "readProcessStartIdentity").mockReturnValue("live-timer-start"); + vi.spyOn(timerControl, "verifyTimerMarkerIdentity").mockReturnValue({ verified: true }); + vi.spyOn(timerControl, "killTimer").mockReturnValue({ + authorityRevoked: true, + markerFound: true, + markerPid: 999_999, + wasAlive: true, + terminated: true, + warnings: [], + }); fs.writeFileSync( path.join(stateDir, `shields-${sandboxName}.json`), JSON.stringify({ @@ -437,8 +495,10 @@ describe("shields command flow", () => { snapshotPath, restoreAt: new Date(Date.now() + 60_000).toISOString(), processToken, + timerProcessStartIdentity: "live-timer-start", }), ); + writeShieldsTimerAuthorizationProof(requireDist, sandboxName); let observedOwner: Record | null = null; const harness = createHarness({ @@ -975,26 +1035,36 @@ describe("shields command flow", () => { }); }); - it("shields down removes the permissive runtime temp directory when the auto-restore timer fails (#7964)", () => { - const tempRoot = os.tmpdir(); - const permissiveRuntimeDirs = () => - fs.readdirSync(tempRoot).filter((name) => name.startsWith("nemoclaw-permissive-runtime-")); - const before = permissiveRuntimeDirs(); - // shieldsDown builds the temp policy before it forks the auto-restore timer, - // so the fork mock observes the runtime-policy directory mid-transition. That - // proves the test exercises real temp-policy creation, not only the absence - // of a leak. - let runtimeDirsDuringFork: string[] = []; - // A real `openshell policy get --base` carries filesystem_policy paths, so the - // permissive merge writes a temp policy file instead of returning the static - // base path. That is the state that makes the leak reachable. + it("releases a stale timer token before publishing a fresh DOWN generation", () => { + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const sandboxName = "openclaw"; + const staleToken = "8".repeat(32); + const freshToken = "7".repeat(32); + const snapshotPath = path.join(stateDir, "stale-policy-snapshot.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: false, updatedAt: new Date().toISOString() }), + ); + fs.writeFileSync( + path.join(stateDir, `shields-timer-${sandboxName}.json`), + JSON.stringify({ + pid: 4242, + sandboxName, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken: staleToken, + }), + ); + let ownerDuringFork: Record | null = null; const harness = createHarness({ - livePolicyYaml: - "version: 1\nfilesystem_policy:\n read_write:\n - /proc\n read_only:\n - /opt/hermes\n", + initialOpenClawPosture: "locked", fork: () => { - runtimeDirsDuringFork = permissiveRuntimeDirs(); + ownerDuringFork = JSON.parse(fs.readFileSync(lockPath, "utf-8")); return { - pid: 0, + pid: 4343, disconnect: vi.fn(), unref: vi.fn(), send: vi.fn(() => true), @@ -1003,311 +1073,196 @@ describe("shields command flow", () => { }, }); - expect(() => - harness.shieldsDown("openclaw", { - timeout: "5m", - reason: "temp cleanup coverage", - throwOnError: true, - }), - ).toThrow("Cannot start auto-restore timer"); - // One runtime-policy directory existed during the transition, and none - // remains after the failed shields down. - expect(runtimeDirsDuringFork.length).toBe(before.length + 1); - expect(permissiveRuntimeDirs()).toEqual(before); + harness.shieldsDown(sandboxName, { + timeout: "5m", + reason: "stale generation handoff coverage", + processToken: freshToken, + throwOnError: true, + }); + + expect(ownerDuringFork).toMatchObject({ takeoverToken: freshToken }); + expect(ownerDuringFork).not.toMatchObject({ takeoverToken: staleToken }); + expect( + JSON.parse( + fs.readFileSync(path.join(stateDir, `shields-timer-${sandboxName}.json`), "utf-8"), + ), + ).toMatchObject({ processToken: freshToken }); }); - it.skipIf(process.platform === "win32")( - "atomically replaces a timer marker symlink without modifying its target", - () => { - const stateDir = path.join(tmpDir, ".nemoclaw", "state"); - const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); - const markerTargetPath = path.join(stateDir, "operator-owned-marker.json"); - const markerTarget = "operator-owned marker contents"; - fs.mkdirSync(stateDir, { recursive: true }); - fs.writeFileSync(markerTargetPath, markerTarget); - const originalRename = fs.renameSync.bind(fs); - const plantMarkerSymlink = () => fs.symlinkSync(markerTargetPath, markerPath); - const publicationRoutes = new Map void>([[markerPath, plantMarkerSymlink]]); - const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { - (publicationRoutes.get(String(destination)) ?? (() => undefined))(); - originalRename(source, destination); - }); - const harness = createHarness({ - fork: () => ({ - pid: 4242, - disconnect: vi.fn(), - unref: vi.fn(), - send: vi.fn(() => true), - kill: vi.fn(() => true), - }), - }); + it("fails before policy mutation when the fresh timer dies before authorization proof", () => { + const harness = createHarness({ + timerAuthorizationOutcome: "dies-before-proof", + fork: () => ({ + pid: 4545, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => true), + kill: vi.fn(() => true), + }), + }); + expect(() => harness.shieldsDown("openclaw", { timeout: "5m", - reason: "marker publication coverage", + reason: "timer authorization failure", throwOnError: true, - }); + }), + ).toThrow(/authorization proof/u); - expect(renameSpy).toHaveBeenCalledWith(expect.stringContaining(".tmp"), markerPath); - const markerFd = fs.openSync(markerPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); - try { - expect(fs.fstatSync(markerFd).isFile()).toBe(true); - expect(JSON.parse(fs.readFileSync(markerFd, "utf-8"))).toMatchObject({ - pid: 4242, - sandboxName: "openclaw", - }); - } finally { - fs.closeSync(markerFd); - } - expect(fs.readFileSync(markerTargetPath, "utf-8")).toBe(markerTarget); - }, - ); + expect(harness.runSpy).not.toHaveBeenCalled(); + expect(harness.auditSpy).not.toHaveBeenCalledWith( + expect.objectContaining({ action: "shields_down" }), + ); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + expect(fs.existsSync(path.join(stateDir, "shields-openclaw.json"))).toBe(false); + expect( + fs.readdirSync(stateDir).some((entry) => entry.startsWith("shields-transition-openclaw-")), + ).toBe(false); + expect( + fs + .readdirSync(stateDir) + .some((entry) => entry.startsWith("shields-timer-authorization-openclaw-")), + ).toBe(false); + }); - it("shieldsUp refuses to mark lockdown active when the saved restrictive policy snapshot is missing", () => { - const harness = createHarness(); + it("rolls back when the authorized fresh timer dies before active commit", () => { const stateDir = path.join(tmpDir, ".nemoclaw", "state"); fs.mkdirSync(stateDir, { recursive: true }); fs.writeFileSync( path.join(stateDir, "shields-openclaw.json"), - JSON.stringify({ - shieldsDown: true, - shieldsDownAt: new Date(Date.now() - 120_000).toISOString(), - shieldsDownTimeout: 300, - shieldsDownReason: "coverage", - shieldsDownPolicy: "permissive", - shieldsPolicySnapshotPath: path.join(stateDir, "missing-snapshot.yaml"), - }), + JSON.stringify({ shieldsDown: false, updatedAt: new Date().toISOString() }), ); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - "Saved policy snapshot is missing", - ); - }); - - it("reports staged driver-neutral recovery when shields-down rollback cannot re-lock (#6126)", () => { - const harness = createHarness({ failOpenClawGuardActions: ["unlock", "lock"] }); - - expect(() => - harness.shieldsDown("openclaw", { - timeout: "5m", - reason: "recovery-hint coverage", - skipTimer: true, - throwOnError: true, + const harness = createHarness({ + confirmOpenClawInodeFlags: true, + initialOpenClawPosture: "locked", + timerDiesAfterUnlock: true, + fork: () => ({ + pid: 4646, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => true), + kill: vi.fn(() => true), }), - ).toThrow(/startup-not-ready/); - - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); - expect(output).toContain("Rolling back — restoring policy from snapshot"); - expect(output).toContain("Config remains unlocked — manual intervention required"); - }); - - it("keeps the host attached beyond failed-startup recovery's container timeout (#8304)", () => { - const harness = createHarness({ failOpenClawGuardActions: ["preflight"] }); + }); expect(() => harness.shieldsDown("openclaw", { timeout: "5m", - reason: "failed-startup timeout coverage", - skipTimer: true, + reason: "timer died before active", throwOnError: true, }), - ).not.toThrow(); + ).toThrow(/live future auto-restore timer authority/u); - const recovery = harness.dockerSpawnCalls.find(({ args }) => - args.includes("unlock-failed-startup"), - ); - expect(recovery?.args).toEqual( - expect.arrayContaining(["timeout", "--kill-after=5s", "25m", "unlock-failed-startup"]), + expect(harness.getOpenClawPosture()).toBe("locked"); + expect( + JSON.parse( + fs.readFileSync(path.join(tmpDir, ".nemoclaw", "state", "shields-openclaw.json"), "utf-8"), + ), + ).toMatchObject({ shieldsDown: false }); + expect(harness.auditSpy).not.toHaveBeenCalledWith( + expect.objectContaining({ action: "shields_down" }), ); - expect(recovery?.timeout).toBe(26 * 60 * 1000); }); - it("reports staged driver-neutral recovery when snapshot restoration fails (#6126)", () => { - const harness = createHarness({ run: () => ({ status: 1 }) }); + it("restores lockdown instead of trusting a dead future timer marker", () => { + const harness = createHarness({ confirmOpenClawInodeFlags: true }); const stateDir = path.join(tmpDir, ".nemoclaw", "state"); - const snapshotPath = path.join(stateDir, "policy-snapshot-failed-restore.yaml"); + const snapshotPath = path.join(stateDir, "policy-snapshot-dead-future-timer.yaml"); + const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); + const processToken = "6".repeat(32); fs.mkdirSync(stateDir, { recursive: true }); - fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); fs.writeFileSync( path.join(stateDir, "shields-openclaw.json"), JSON.stringify({ shieldsDown: true, shieldsDownAt: new Date().toISOString(), shieldsDownTimeout: 300, - shieldsDownReason: "recovery-hint coverage", + shieldsDownReason: "dead future timer", shieldsDownPolicy: "permissive", shieldsPolicySnapshotPath: snapshotPath, }), ); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - "policy restore exited with status 1", - ); - - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); - expect(output).toContain("Config remains unlocked — manual intervention required"); - }); - - it("reports staged driver-neutral recovery when the initial config lock fails (#6126)", () => { - const harness = createHarness({ failOpenClawGuardActions: ["lock"] }); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /startup-not-ready/, - ); - - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); - expect(output).toContain( - "Warning: OpenClaw lock rollback could not restore the trusted posture", - ); - expect(output).not.toContain("CRITICAL: OpenClaw lock rollback"); - expect(output).not.toContain( - "OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox", - ); - }); - - it("uses the invoked nemohermes alias in staged recovery commands (#6126)", () => { - const harness = createHarness({ - failOpenClawGuardActions: ["lock"], - invokedAs: "nemohermes", - }); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /startup-not-ready/, - ); - - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw", "nemohermes"); - expect(output).not.toContain("`nemoclaw openclaw shields up`"); - expect(output).not.toContain("`nemoclaw openclaw rebuild --yes`"); - }); - - it("reports staged recovery when a stopped sandbox prevents config relock (#6126)", () => { - const harness = createHarness({ directSandboxUnavailable: true }); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /No running direct OpenShell sandbox container found/, - ); - - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); - expect(output).toContain( - "Warning: OpenClaw lock rollback could not restore the trusted posture", - ); - expect(output).not.toContain("CRITICAL: OpenClaw lock rollback"); - }); - - it("retains critical recovery for non-transient OpenClaw rollback failures (#6126)", () => { - const harness = createHarness({ - failOpenClawGuardActions: ["lock"], - openClawGuardFailure: { - code: "unsafe-config-path", - path: "/sandbox/.openclaw/openclaw.json", - detail: "canonical config path is not a safe regular file", - }, - }); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /unsafe-config-path/, - ); - - const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain( - "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", - ); - expect(output).not.toContain( - "Warning: OpenClaw lock rollback could not restore the trusted posture", - ); - }); - - it("retains critical recovery for structural startup-not-ready diagnostics (#6126)", () => { - const harness = createHarness({ - failOpenClawGuardActions: ["lock"], - openClawGuardFailure: { - code: "startup-not-ready", - path: "/run/nemoclaw/openclaw-config-ready.json", - detail: "installed config guard requires NemoClaw PID 1", - }, - }); - - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /requires NemoClaw PID 1/, - ); - - const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain( - "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", - ); - expect(output).not.toContain( - "Warning: OpenClaw lock rollback could not restore the trusted posture", + fs.writeFileSync( + markerPath, + JSON.stringify({ + pid: 2_147_483_647, + sandboxName: "openclaw", + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + timerProcessStartIdentity: "dead-timer-start", + agentName: "openclaw", + configPath: "/sandbox/.openclaw/openclaw.json", + configDir: "/sandbox/.openclaw", + }), ); - }); - - it("retains critical recovery when a transient diagnostic is followed by another issue (#6126)", () => { - const harness = createHarness({ - failOpenClawGuardActions: ["lock"], - openClawGuardFailures: [ - { - code: "startup-not-ready", - path: "/run/nemoclaw/openclaw-config-ready.json", - detail: "OpenClaw startup is not ready for host config mutations", - }, - { - code: "unsafe-config-path", - path: "/sandbox/.openclaw/openclaw.json", - detail: "canonical config path is not a safe regular file", - }, - ], - }); - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /unsafe-config-path/, - ); + harness.shieldsStatus("openclaw"); - const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain( - "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", - ); - expect(output).not.toContain( - "Warning: OpenClaw lock rollback could not restore the trusted posture", + expect( + JSON.parse(fs.readFileSync(path.join(stateDir, "shields-openclaw.json"), "utf-8")), + ).toMatchObject({ shieldsDown: false, shieldsDownAt: null }); + expect(fs.existsSync(markerPath)).toBe(false); + expect(harness.runSpy).toHaveBeenCalledWith( + ["openshell", "policy", "set"], + expect.objectContaining({ ignoreError: true }), ); + expect(harness.logSpy).toHaveBeenCalledWith(" Shields: UP (lockdown active)"); }); - it("reports staged driver-neutral recovery when drift remediation cannot re-lock (#6126)", () => { - const harness = createHarness({ failOpenClawGuardActions: ["lock"] }); + it.each( + timerAuthorityFixtures, + )("restores lockdown when DOWN timer authority is %s", (markerState, writeMarker) => { + const harness = createHarness({ confirmOpenClawInodeFlags: true }); const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, `policy-snapshot-${markerState}-timer.yaml`); + const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); fs.writeFileSync( path.join(stateDir, "shields-openclaw.json"), JSON.stringify({ - shieldsDown: false, - chattrApplied: false, - fileHashes: { - "/sandbox/.openclaw/openclaw.json": "a".repeat(64), - "/sandbox/.openclaw/.config-hash": "a".repeat(64), - }, + shieldsDown: true, + shieldsDownAt: new Date().toISOString(), + shieldsDownTimeout: 300, + shieldsDownReason: `${markerState} timer marker`, + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, }), ); + writeMarker(markerPath); - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /startup-not-ready/, - ); + harness.shieldsStatus("openclaw"); - const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); - expect(output).toContain("Config remains drifted — manual intervention required"); + expect( + JSON.parse(fs.readFileSync(path.join(stateDir, "shields-openclaw.json"), "utf-8")), + ).toMatchObject({ shieldsDown: false, shieldsDownAt: null }); + expect(fs.existsSync(markerPath)).toBe(false); + expect(harness.runSpy).toHaveBeenCalledWith( + ["openshell", "policy", "set"], + expect.objectContaining({ ignoreError: true }), + ); }); - it("retains the bounded auto-restore owner when manual shields-up fails", () => { - const harness = createHarness(); + it("restores lockdown when a future marker PID has the wrong timer command identity", () => { + const harness = createHarness({ confirmOpenClawInodeFlags: true }); + const timerControl = requireDist("./timer-control.js") as typeof import("./timer-control.js"); const stateDir = path.join(tmpDir, ".nemoclaw", "state"); - const snapshotPath = path.join(stateDir, "policy-snapshot-relock-failure.yaml"); + const snapshotPath = path.join(stateDir, "policy-snapshot-wrong-timer-command.yaml"); const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); + const processToken = "5".repeat(32); + const startIdentity = timerControl.readProcessStartIdentity(process.pid); + expect(startIdentity).toBeTypeOf("string"); fs.mkdirSync(stateDir, { recursive: true }); - fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies: {}\n"); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n test: {}\n"); fs.writeFileSync( path.join(stateDir, "shields-openclaw.json"), JSON.stringify({ shieldsDown: true, shieldsDownAt: new Date().toISOString(), - shieldsDownTimeout: 1800, - shieldsDownReason: "rebuild", + shieldsDownTimeout: 300, + shieldsDownReason: "wrong timer command", shieldsDownPolicy: "permissive", shieldsPolicySnapshotPath: snapshotPath, }), @@ -1315,26 +1270,27 @@ describe("shields command flow", () => { fs.writeFileSync( markerPath, JSON.stringify({ - pid: 4242, + pid: process.pid, sandboxName: "openclaw", snapshotPath, restoreAt: new Date(Date.now() + 60_000).toISOString(), - processToken: "timer-token", - allowLegacyHermesProtocol: false, + processToken, + timerProcessStartIdentity: startIdentity, + agentName: "openclaw", + configPath: "/sandbox/.openclaw/openclaw.json", + configDir: "/sandbox/.openclaw", }), ); - const killSpy = vi.spyOn(process, "kill").mockReturnValue(true); + const killSpy = vi.spyOn(process, "kill"); - expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( - /Config not locked/, - ); + harness.shieldsStatus("openclaw"); - 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); + JSON.parse(fs.readFileSync(path.join(stateDir, "shields-openclaw.json"), "utf-8")), + ).toMatchObject({ shieldsDown: false, shieldsDownAt: null }); + expect(fs.existsSync(markerPath)).toBe(false); + expect(killSpy).not.toHaveBeenCalledWith(process.pid, "SIGTERM"); + expect(killSpy).not.toHaveBeenCalledWith(process.pid, "SIGKILL"); }); it("shieldsStatus contains an expired timer whose transition owner exited", () => { diff --git a/src/lib/shields/hermes-runtime-state-mutation.test.ts b/src/lib/shields/hermes-runtime-state-mutation.test.ts new file mode 100644 index 00000000000..a87a86e619a --- /dev/null +++ b/src/lib/shields/hermes-runtime-state-mutation.test.ts @@ -0,0 +1,741 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import { describe, expect, it } from "vitest"; +import { createHermesTransitionFailureController } from "../../../test/helpers/hermes-runtime-state-mutation-test-helpers"; +import { testTimeout } from "../../../test/helpers/timeouts"; + +import { loadAgent } from "../agent/defs"; +import { + CURRENT_RUNTIME_PROVIDER_BUNDLES, + type RuntimeProviderBundleRegistry, + type RuntimeProviderPreparedStateMutationPlan, + type RuntimeProviderStateMutationActivationProof, + type RuntimeProviderStateMutationContext, + type RuntimeProviderStateMutationFence, +} from "../onboard/runtime-provider/access"; +import { RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION } from "../onboard/runtime-provider/contract"; +import type { SandboxEntry } from "../state/registry"; +import { + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY, + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_METADATA, + runHermesRuntimeProviderStateMutation, + supportsHermesRuntimeProviderStateMutation, +} from "./hermes-runtime-state-mutation"; + +const sandbox: SandboxEntry = { + name: "hermes", + agent: "hermes", + openshellDriver: "docker", + lifecycleGeneration: "generation-1", + workload: { + schemaVersion: 1, + kind: "managed-image", + reference: "ghcr.io/nvidia/nemoclaw/hermes@sha256:abc", + platform: "linux/amd64", + release: "test", + sourceRevision: "a".repeat(40), + sourceCohort: "test", + capabilityContractVersion: 1, + startupProfileContractVersion: 1, + encodedProfile: "e30", + startupProfileSha256: "b".repeat(64), + credentialProxyReplayRequired: true, + shared: true, + }, +}; + +const hermesAgent = loadAgent("hermes"); +const configTarget = { + agentName: hermesAgent.name, + configPath: path.posix.join(hermesAgent.configPaths.dir, hermesAgent.configPaths.configFile), + configDir: hermesAgent.configPaths.dir, + configFile: hermesAgent.configPaths.configFile, + format: hermesAgent.configPaths.format, + sensitiveFiles: [ + path.posix.join(hermesAgent.configPaths.dir, ".config-hash"), + ...hermesAgent.configPaths.shieldsFiles.map((entry) => + path.posix.join(hermesAgent.configPaths.dir, entry), + ), + ], + stateLockPlan: hermesAgent.stateLockPlan, + stateLockPlanInImage: hermesAgent.stateLockPlanInImage, +}; + +const fence: RuntimeProviderStateMutationFence = { + schemaVersion: 1, + intent: "protection-transition", + phase: "fenced", + providerId: "docker", + sandboxName: "hermes", + transactionId: "1".repeat(64), + lifecycleGeneration: "generation-1", + runtimeId: "2".repeat(64), + runtimeStateSha256: "3".repeat(64), + engineBindingSha256: "4".repeat(64), + stateRoot: "/sandbox/.hermes", + mountNamespaceId: "mnt:[123]", + stateRootDevice: "4", + stateRootInode: "5", + planSha256: "6".repeat(64), + projectionSha256: "7".repeat(64), + target: "locked", + rollback: "mutable", + nonce: "8".repeat(64), + providerHandle: `docker-state-mutation-v1:${"1".repeat(64)}:${"9".repeat(64)}`, +}; + +const mutableFence: RuntimeProviderStateMutationFence = { + ...fence, + target: "mutable", + rollback: "locked", +}; + +const proof: RuntimeProviderStateMutationActivationProof = { + schemaVersion: 1, + providerId: "docker", + sandboxName: "hermes", + lifecycleGeneration: "generation-1", + runtimeId: "2".repeat(64), + nonce: "8".repeat(64), + configurationGeneration: "a".repeat(64), + listenerIdentity: "tcp:18642:pid:321:start:654", + healthSha256: "b".repeat(64), + providerHandle: `docker-state-mutation-activation-v1:${"1".repeat(64)}:${"c".repeat(64)}`, +}; + +type SurfaceOverrides = Partial<{ + acquire: ( + input: RuntimeProviderStateMutationContext & { + readonly plan: RuntimeProviderPreparedStateMutationPlan; + }, + ) => RuntimeProviderStateMutationFence; + assertFenced: ( + input: RuntimeProviderStateMutationContext, + value: RuntimeProviderStateMutationFence, + ) => void; + publish: ( + input: RuntimeProviderStateMutationContext, + value: RuntimeProviderStateMutationFence, + ) => void; + rollback: ( + input: RuntimeProviderStateMutationContext, + value: RuntimeProviderStateMutationFence, + ) => void; + activate: ( + input: RuntimeProviderStateMutationContext, + value: RuntimeProviderStateMutationFence, + ) => RuntimeProviderStateMutationActivationProof; + release: ( + input: RuntimeProviderStateMutationContext, + value: RuntimeProviderStateMutationFence, + activation: RuntimeProviderStateMutationActivationProof, + digest: string, + ) => void; + recover: (input: RuntimeProviderStateMutationContext) => RuntimeProviderStateMutationFence | null; +}>; + +function providers(overrides: SurfaceOverrides = {}): RuntimeProviderBundleRegistry { + const docker = CURRENT_RUNTIME_PROVIDER_BUNDLES.docker!; + return { + docker: { + ...docker, + stateMutation: { + providerId: "docker", + supported: true, + contractVersion: RUNTIME_PROVIDER_STATE_MUTATION_CONTRACT_VERSION, + acquire: overrides.acquire ?? (() => fence), + assertFenced: overrides.assertFenced ?? (() => undefined), + publish: overrides.publish ?? (() => undefined), + rollback: overrides.rollback ?? (() => undefined), + activate: overrides.activate ?? (() => proof), + release: overrides.release ?? (() => undefined), + recover: overrides.recover ?? (() => null), + }, + }, + }; +} + +function run( + runtimeProviders: RuntimeProviderBundleRegistry, + targetPosture: "locked" | "mutable" = "locked", + rollback: "locked" | "mutable" = "mutable", + targetConfig = configTarget, +) { + return runHermesRuntimeProviderStateMutation({ + environment: { HOME: "/tmp/test-home" }, + sandbox, + sandboxName: sandbox.name, + configTarget: targetConfig, + target: targetPosture, + rollback, + providers: runtimeProviders, + }); +} + +describe("Hermes runtime-provider state mutation consumer", () => { + it( + "resolves the current Docker provider when the caller does not inject a registry", + () => { + expect( + supportsHermesRuntimeProviderStateMutation(sandbox, { + content: HERMES_RUNTIME_STATE_MUTATION_CAPABILITY, + metadata: HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_METADATA, + }), + ).toBe(true); + }, + testTimeout(30_000), + ); + + it("selects only an exact current managed Hermes Docker image capability", () => { + const capability = { + content: HERMES_RUNTIME_STATE_MUTATION_CAPABILITY, + metadata: HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_METADATA, + }; + expect(supportsHermesRuntimeProviderStateMutation(sandbox, capability, providers())).toBe(true); + expect( + supportsHermesRuntimeProviderStateMutation( + { ...sandbox, workload: undefined }, + capability, + providers(), + ), + ).toBe(false); + expect( + supportsHermesRuntimeProviderStateMutation( + sandbox, + { ...capability, metadata: "644 0 0 1 regular file" }, + providers(), + ), + ).toBe(false); + expect( + supportsHermesRuntimeProviderStateMutation( + sandbox, + { ...capability, content: `${capability.content} ` }, + providers(), + ), + ).toBe(false); + }); + + it("publishes and activates the exact AgentDefinition plan before durable release", () => { + const calls: string[] = []; + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + let completionDigest = ""; + const result = run( + providers({ + recover: () => { + calls.push("recover"); + return null; + }, + acquire: (input) => { + calls.push("acquire"); + acquiredPlan = input.plan; + return fence; + }, + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: (_context, _fence, _proof, digest) => { + calls.push("release"); + completionDigest = digest; + }, + }), + ); + + expect(calls).toEqual([ + "recover", + "acquire", + "assert", + "publish", + "assert", + "activate", + "release", + ]); + expect(acquiredPlan?.plan).toMatchObject({ + intent: "protection-transition", + stateRoot: "/sandbox/.hermes", + target: "locked", + rollback: "mutable", + }); + expect(acquiredPlan?.serializedPlan).not.toMatch(/command|callback|executable/u); + expect(completionDigest).toMatch(/^[0-9a-f]{64}$/u); + expect(result).toEqual({ fence, proof }); + }); + + it.each([ + ["locked", "mutable", fence], + ["mutable", "locked", mutableFence], + ] as const)("executes a same-%s transition with a synthetic %s rollback", (target, expectedRollback, acquiredFence) => { + const calls: string[] = []; + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + const result = run( + providers({ + recover: () => { + calls.push("recover"); + return null; + }, + acquire: (input) => { + calls.push("acquire"); + acquiredPlan = input.plan; + return acquiredFence; + }, + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + }), + target, + target, + ); + + expect(acquiredPlan?.plan).toMatchObject({ target, rollback: expectedRollback }); + expect(calls).toEqual([ + "recover", + "acquire", + "assert", + "publish", + "assert", + "activate", + "release", + ]); + expect(result).toEqual({ fence: acquiredFence, proof }); + }); + + it.each([ + "publication", + "verification", + "activation", + ] as const)("rolls a same-mutable transition back to locked after %s failure", (failureStage) => { + const calls: string[] = []; + const failure = new Error(`${failureStage} failed`); + const failureController = createHermesTransitionFailureController(failureStage, failure, { + failOnlyFirstActivation: true, + }); + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + + expect(() => + run( + providers({ + acquire: (input) => { + calls.push("acquire"); + acquiredPlan = input.plan; + return mutableFence; + }, + assertFenced: () => { + calls.push("assert"); + failureController.afterAssertion(); + }, + publish: () => { + calls.push("publish"); + failureController.afterPublication(); + }, + rollback: (_context, value) => { + calls.push("rollback"); + expect(value).toMatchObject({ target: "mutable", rollback: "locked" }); + }, + activate: () => { + calls.push("activate"); + failureController.beforeActivation(); + return proof; + }, + release: () => calls.push("release"), + }), + "mutable", + "mutable", + ), + ).toThrow(failure); + + expect(acquiredPlan?.plan).toMatchObject({ target: "mutable", rollback: "locked" }); + expect(calls.filter((call) => call === "rollback")).toHaveLength(1); + expect(calls.at(-1)).toBe("release"); + }); + + it.each([ + "publication", + "verification", + "activation", + ] as const)("retains a same-locked restrictive fence after %s failure", (failureStage) => { + const calls: string[] = []; + const failure = new Error(`${failureStage} failed`); + const failureController = createHermesTransitionFailureController(failureStage, failure); + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + + expect(() => + run( + providers({ + acquire: (input) => { + calls.push("acquire"); + acquiredPlan = input.plan; + return fence; + }, + assertFenced: () => { + calls.push("assert"); + failureController.afterAssertion(); + }, + publish: () => { + calls.push("publish"); + failureController.afterPublication(); + }, + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + failureController.beforeActivation(); + return proof; + }, + release: () => calls.push("release"), + }), + "locked", + "locked", + ), + ).toThrow(failure); + + expect(acquiredPlan?.plan).toMatchObject({ target: "locked", rollback: "mutable" }); + expect(calls).not.toContain("rollback"); + expect(calls).not.toContain("release"); + }); + + it("rolls back and releases a recovered prior fence before acquiring a new one", () => { + const calls: string[] = []; + const recoveries = [mutableFence, null]; + run( + providers({ + recover: () => { + calls.push("recover"); + return recoveries.shift() ?? null; + }, + assertFenced: () => calls.push("assert"), + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + acquire: () => { + calls.push("acquire"); + return fence; + }, + publish: () => calls.push("publish"), + }), + ); + + expect(calls.slice(0, 6)).toEqual([ + "recover", + "assert", + "rollback", + "assert", + "activate", + "release", + ]); + expect(calls[6]).toBe("acquire"); + }); + + it("preserves locked containment while retaining exclusion after lock publication fails", () => { + const calls: string[] = []; + const failure = new Error("publisher rejected target"); + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + expect(() => + run( + providers({ + acquire: (input) => { + acquiredPlan = input.plan; + return fence; + }, + assertFenced: () => calls.push("assert"), + publish: () => { + calls.push("publish"); + throw failure; + }, + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + }), + ), + ).toThrow(failure); + expect(calls).toEqual(["assert", "publish"]); + expect(acquiredPlan?.plan).toMatchObject({ target: "locked", rollback: "mutable" }); + }); + + it("preserves locked containment when the first fence assertion fails", () => { + const calls: string[] = []; + const failure = new Error("fence assertion transport failed"); + expect(() => + run( + providers({ + assertFenced: () => { + calls.push("assert"); + throw failure; + }, + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + }), + ), + ).toThrow(failure); + expect(calls).toEqual(["assert"]); + }); + + it("keeps the prior locked posture as the unlock rollback", () => { + let acquiredPlan: RuntimeProviderPreparedStateMutationPlan | undefined; + run( + providers({ + acquire: (input) => { + acquiredPlan = input.plan; + return mutableFence; + }, + }), + "mutable", + "locked", + ); + expect(acquiredPlan?.plan).toMatchObject({ target: "mutable", rollback: "locked" }); + }); + + it("retains the locked fence without rollback when activation fails", () => { + const calls: string[] = []; + const failure = new Error("locked gateway activation failed"); + expect(() => + run( + providers({ + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + activate: () => { + calls.push("activate"); + throw failure; + }, + rollback: () => calls.push("rollback"), + release: () => calls.push("release"), + }), + ), + ).toThrow(failure); + expect(calls).toEqual(["assert", "publish", "assert", "activate"]); + }); + + it("recovers an acquire transport failure and rolls back the exact discovered fence", () => { + const calls: string[] = []; + const primary = new Error("acquire transport closed"); + let recoverCount = 0; + expect(() => + run( + providers({ + acquire: () => { + calls.push("acquire"); + throw primary; + }, + recover: () => { + calls.push("recover"); + recoverCount += 1; + return recoverCount === 1 ? null : mutableFence; + }, + assertFenced: () => calls.push("assert"), + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + }), + ), + ).toThrow(primary); + expect(calls).toEqual([ + "recover", + "acquire", + "recover", + "assert", + "rollback", + "assert", + "activate", + "release", + ]); + }); + + it("completes a recovered locked acquire before surfacing the lost response", () => { + const calls: string[] = []; + const primary = new Error("locked acquire response lost"); + let recoverCount = 0; + expect(() => + run( + providers({ + acquire: () => { + calls.push("acquire"); + throw primary; + }, + recover: () => { + calls.push("recover"); + recoverCount += 1; + return recoverCount === 1 ? null : fence; + }, + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + }), + ), + ).toThrow(primary); + expect(calls).toEqual([ + "recover", + "acquire", + "recover", + "assert", + "publish", + "assert", + "activate", + "release", + ]); + expect(calls).not.toContain("rollback"); + }); + + it("finishes an ambiguous release through provider recovery without republishing", () => { + const calls: string[] = []; + let recoverCount = 0; + run( + providers({ + recover: () => { + calls.push("recover"); + recoverCount += 1; + return null; + }, + acquire: () => fence, + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => { + calls.push("release"); + throw new Error("response lost after release"); + }, + }), + ); + expect(recoverCount).toBe(2); + expect(calls.filter((entry) => entry === "publish")).toHaveLength(1); + expect(calls.at(-1)).toBe("recover"); + }); + + it.each([ + ["schema authority", { schemaVersion: 2 }], + ["runtime authority", { runtimeStateSha256: "d".repeat(64) }], + ["engine authority", { engineBindingSha256: "d".repeat(64) }], + ["mount authority", { mountNamespaceId: "mnt:[999]" }], + ["state-root scope", { stateRoot: "/sandbox/.hermes-other" }], + ["state-root identity", { stateRootInode: "99" }], + ["plan authority", { projectionSha256: "d".repeat(64) }], + ])("rejects %s drift in a recovered release fence", (_label, mutation) => { + let recoveryCount = 0; + expect(() => + run( + providers({ + recover: () => { + recoveryCount += 1; + return recoveryCount === 1 + ? null + : ({ + ...fence, + ...mutation, + phase: "activation-proven", + } as RuntimeProviderStateMutationFence); + }, + release: () => { + throw new Error("release response lost"); + }, + }), + ), + ).toThrow(/different state-mutation fence/u); + }); + + it("rejects a recovered release fence that has not retained activation proof", () => { + let recoveryCount = 0; + expect(() => + run( + providers({ + recover: () => { + recoveryCount += 1; + return recoveryCount === 1 ? null : { ...fence, phase: "published" }; + }, + release: () => { + throw new Error("release response lost"); + }, + }), + ), + ).toThrow(/different state-mutation fence/u); + }); + + it("keeps the fence active and reports both failures when rollback cannot complete", () => { + const failure = new Error("activation failed"); + expect(() => + run( + providers({ + acquire: () => mutableFence, + activate: () => { + throw failure; + }, + rollback: () => { + throw new Error("rollback blocked"); + }, + }), + "mutable", + "locked", + ), + ).toThrow(/activation failed.*retained.*rollback blocked/iu); + }); + + it("recovers a retained fence before rejecting a stale config target without acquiring", () => { + const calls: string[] = []; + const recoveries = [{ ...fence, phase: "published" as const }, null]; + expect(() => + run( + providers({ + recover: () => { + calls.push("recover"); + return recoveries.shift() ?? null; + }, + assertFenced: () => calls.push("assert"), + publish: () => calls.push("publish"), + rollback: () => calls.push("rollback"), + activate: () => { + calls.push("activate"); + return proof; + }, + release: () => calls.push("release"), + acquire: () => { + calls.push("acquire"); + return fence; + }, + }), + "locked", + "mutable", + { ...configTarget, configPath: "/sandbox/.hermes/old-config.yaml" }, + ), + ).toThrow(/no longer matches the current AgentDefinition config projection/u); + expect(calls).toEqual(["recover", "assert", "activate", "release"]); + expect(calls).not.toContain("rollback"); + expect(calls).not.toContain("publish"); + expect(calls).not.toContain("acquire"); + }); + + it("refuses to release a retained locked transition whose mutable rollback was published", () => { + expect(() => + run( + providers({ + recover: () => ({ ...fence, phase: "rolled-back" }), + }), + ), + ).toThrow(/already published its mutable rollback.*refusing to release mutable state/iu); + }); +}); diff --git a/src/lib/shields/hermes-runtime-state-mutation.ts b/src/lib/shields/hermes-runtime-state-mutation.ts new file mode 100644 index 00000000000..edb5feb1001 --- /dev/null +++ b/src/lib/shields/hermes-runtime-state-mutation.ts @@ -0,0 +1,392 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { isDeepStrictEqual } from "node:util"; +import type { AgentDefinition, AgentStateLockPlan } from "../agent/definition-types"; +import type { + RuntimeProviderBundleRegistry, + RuntimeProviderStateMutationActivationProof, + RuntimeProviderStateMutationContext, + RuntimeProviderStateMutationFence, + RuntimeProviderStateMutationProtectionPosture, + RuntimeProviderStateMutationSurface, +} from "../onboard/runtime-provider/contract"; +import { + createFilePersistedEngineLifecycleStore, + hasActivePersistedEngineStateMutationTarget, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, +} from "../onboard/runtime-provider/persisted-engine-lifecycle"; +import { requireRuntimeProviderBundleForSandbox } from "../onboard/runtime-provider/registry"; +import { prepareAgentDefinitionProtectionTransitionPlan } from "../onboard/runtime-provider/state-mutation"; +import { resolveCurrentAgentDefinition } from "../sandbox/agent-config"; +import type { SandboxEntry } from "../state/registry/types"; + +export const HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PATH = + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json"; + +export const HERMES_RUNTIME_STATE_MUTATION_CAPABILITY = + '{"schemaVersion":1,"protocol":"nemoclaw-runtime-state-mutation-publisher-v1","agent":"hermes","providerId":"docker","stateRoot":"/sandbox/.hermes","planSchemaVersion":2,"entrypoint":"/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"}'; + +export const HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_METADATA = "444 0 0 1 regular file"; + +type SupportedStateMutationSurface = Extract< + RuntimeProviderStateMutationSurface, + { readonly supported: true } +>; + +export interface HermesRuntimeStateMutationCapabilityInspection { + readonly content: string; + readonly metadata: string; +} + +export interface HermesRuntimeStateMutationResult { + readonly fence: RuntimeProviderStateMutationFence; + readonly proof: RuntimeProviderStateMutationActivationProof; +} + +export interface HermesRuntimeStateMutationConfigTarget { + readonly agentName?: string; + readonly configPath: string; + readonly configDir: string; + readonly configFile?: string; + readonly format?: string; + readonly sensitiveFiles?: readonly string[]; + readonly stateLockPlan?: AgentStateLockPlan; + readonly stateLockPlanInImage: boolean; +} + +export interface HermesRuntimeStateMutationInput { + readonly environment: NodeJS.ProcessEnv; + readonly sandbox: SandboxEntry; + readonly sandboxName: string; + readonly configTarget: HermesRuntimeStateMutationConfigTarget; + readonly target: RuntimeProviderStateMutationProtectionPosture; + readonly rollback: RuntimeProviderStateMutationProtectionPosture; + readonly providers?: RuntimeProviderBundleRegistry; +} + +function currentRuntimeProviderBundles(): RuntimeProviderBundleRegistry { + return ( + require("../onboard/runtime-provider/current") as typeof import("../onboard/runtime-provider/current") + ).CURRENT_RUNTIME_PROVIDER_BUNDLES; +} + +function errorMessage(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} + +function combinedFailure(primary: unknown, recovery: unknown): Error { + return new Error( + `${errorMessage(primary)} Recovery of the retained runtime state-mutation fence failed: ${errorMessage(recovery)}`, + { cause: primary }, + ); +} + +function completionDigest( + outcome: "target-published" | "rollback-published" | "recovery-rollback-published", + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, +): string { + return createHash("sha256") + .update( + JSON.stringify({ + schemaVersion: 1, + outcome, + intent: fence.intent, + target: fence.target, + rollback: fence.rollback, + providerId: fence.providerId, + sandboxName: fence.sandboxName, + transactionId: fence.transactionId, + lifecycleGeneration: fence.lifecycleGeneration, + runtimeId: fence.runtimeId, + planSha256: fence.planSha256, + projectionSha256: fence.projectionSha256, + nonce: fence.nonce, + configurationGeneration: proof.configurationGeneration, + listenerIdentity: proof.listenerIdentity, + healthSha256: proof.healthSha256, + activationProviderHandle: proof.providerHandle, + }), + "utf8", + ) + .digest("hex"); +} + +function exactFence( + expected: RuntimeProviderStateMutationFence, + actual: RuntimeProviderStateMutationFence, +): RuntimeProviderStateMutationFence { + const immutableFields: ReadonlyArray = [ + "schemaVersion", + "intent", + "providerId", + "sandboxName", + "transactionId", + "lifecycleGeneration", + "runtimeId", + "runtimeStateSha256", + "engineBindingSha256", + "stateRoot", + "mountNamespaceId", + "stateRootDevice", + "stateRootInode", + "planSha256", + "projectionSha256", + "target", + "rollback", + "nonce", + "providerHandle", + ]; + if ( + actual.phase !== "activation-proven" || + immutableFields.some((field) => actual[field] !== expected[field]) + ) { + throw new Error("Runtime provider recovery returned a different state-mutation fence."); + } + return actual; +} + +function rollbackAndRelease( + surface: SupportedStateMutationSurface, + context: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + outcome: "rollback-published" | "recovery-rollback-published", +): void { + surface.assertFenced(context, fence); + surface.rollback(context, fence); + surface.assertFenced(context, fence); + const proof = surface.activate(context, fence); + surface.release(context, fence, proof, completionDigest(outcome, fence, proof)); +} + +function recoverPriorMutation( + surface: SupportedStateMutationSurface, + context: RuntimeProviderStateMutationContext, +): void { + const recovered = surface.recover(context); + if (recovered === null) return; + recoverRetainedMutation(surface, context, recovered); +} + +function recoverRetainedMutation( + surface: SupportedStateMutationSurface, + context: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, +): void { + if (fence.intent !== "protection-transition" || fence.target !== "locked") { + rollbackAndRelease(surface, context, fence, "recovery-rollback-published"); + return; + } + if (fence.phase === "rolled-back") { + throw new Error( + "A retained Hermes lock fence already published its mutable rollback; refusing to release mutable state.", + ); + } + surface.assertFenced(context, fence); + if (fence.phase === "fenced") { + surface.publish(context, fence); + surface.assertFenced(context, fence); + } + const proof = surface.activate(context, fence); + releaseTarget(surface, context, fence, proof); +} + +function recoverAcquireFailure( + surface: SupportedStateMutationSurface, + context: RuntimeProviderStateMutationContext, + primary: unknown, +): never { + try { + const recovered = surface.recover(context); + if (recovered !== null) { + recoverRetainedMutation(surface, context, recovered); + } + } catch (recoveryError) { + throw combinedFailure(primary, recoveryError); + } + throw primary; +} + +function exactStringArray( + actual: readonly string[] | undefined, + expected: readonly string[], +): boolean { + return ( + Array.isArray(actual) && + actual.length === expected.length && + actual.every((entry, index) => entry === expected[index]) + ); +} + +function assertCurrentHermesConfigTarget( + target: HermesRuntimeStateMutationConfigTarget, + agent: AgentDefinition, +): void { + const config = agent.configPaths; + const configPath = path.posix.join(config.dir, config.configFile); + const sensitiveFiles = [ + path.posix.join(config.dir, ".config-hash"), + ...config.shieldsFiles.map((entry) => path.posix.join(config.dir, entry)), + ]; + if ( + target.agentName !== agent.name || + target.configDir !== config.dir || + target.configPath !== configPath || + target.configFile !== config.configFile || + target.format !== config.format || + !exactStringArray(target.sensitiveFiles, sensitiveFiles) || + target.stateLockPlanInImage !== agent.stateLockPlanInImage || + !isDeepStrictEqual(target.stateLockPlan, agent.stateLockPlan) + ) { + throw new Error( + "Hermes runtime-provider state mutation target no longer matches the current AgentDefinition config projection.", + ); + } +} + +/** Read-only retained-claim probe for the named Hermes Shields consumer. */ +export function hasActiveHermesRuntimeProviderStateMutation( + sandboxName: string, + stateDir: string, +): boolean { + const lifecycleDirectory = path.join(stateDir, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY); + try { + fs.lstatSync(lifecycleDirectory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + return hasActivePersistedEngineStateMutationTarget( + createFilePersistedEngineLifecycleStore(stateDir), + sandboxName, + ); +} + +function releaseTarget( + surface: SupportedStateMutationSurface, + context: RuntimeProviderStateMutationContext, + fence: RuntimeProviderStateMutationFence, + proof: RuntimeProviderStateMutationActivationProof, +): void { + const digest = completionDigest("target-published", fence, proof); + try { + surface.release(context, fence, proof, digest); + return; + } catch (releaseError) { + try { + const recovered = surface.recover(context); + if (recovered === null) return; + surface.release(context, exactFence(fence, recovered), proof, digest); + return; + } catch (recoveryError) { + throw combinedFailure(releaseError, recoveryError); + } + } +} + +/** + * Select the new protocol only for a current managed Hermes Docker image. The + * fixed helper validates the same capability again after the durable runtime + * claim is acquired, so this compatibility probe never grants authority. + */ +export function supportsHermesRuntimeProviderStateMutation( + sandbox: SandboxEntry | null, + capability: HermesRuntimeStateMutationCapabilityInspection | null, + providers: RuntimeProviderBundleRegistry = currentRuntimeProviderBundles(), +): boolean { + if ( + sandbox?.agent !== "hermes" || + sandbox.openshellDriver?.trim().toLowerCase() !== "docker" || + sandbox.workload?.kind !== "managed-image" || + !sandbox.lifecycleGeneration || + capability?.content !== HERMES_RUNTIME_STATE_MUTATION_CAPABILITY || + capability.metadata !== HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_METADATA + ) { + return false; + } + const provider = requireRuntimeProviderBundleForSandbox(sandbox, providers); + return provider.identity.id === "docker" && provider.stateMutation.supported === true; +} + +/** Execute one complete Hermes protection transition under the Docker provider fence. */ +export function runHermesRuntimeProviderStateMutation( + input: HermesRuntimeStateMutationInput, +): HermesRuntimeStateMutationResult | null { + const agent = resolveCurrentAgentDefinition("hermes"); + const provider = requireRuntimeProviderBundleForSandbox( + input.sandbox, + input.providers ?? currentRuntimeProviderBundles(), + ); + const surface = provider.stateMutation; + if (provider.identity.id !== "docker" || surface.supported !== true) { + throw new Error( + `Runtime provider '${provider.identity.id}' does not support Hermes state mutation.`, + ); + } + const context: RuntimeProviderStateMutationContext = { + environment: input.environment, + sandbox: input.sandbox, + sandboxName: input.sandboxName, + }; + + recoverPriorMutation(surface, context); + assertCurrentHermesConfigTarget(input.configTarget, agent); + const rollback = + input.target === input.rollback + ? input.target === "locked" + ? "mutable" + : "locked" + : input.rollback; + const plan = prepareAgentDefinitionProtectionTransitionPlan(agent, input.target, rollback); + + let fence: RuntimeProviderStateMutationFence; + try { + fence = surface.acquire({ ...context, plan }); + } catch (error) { + return recoverAcquireFailure(surface, context, error); + } + + try { + surface.assertFenced(context, fence); + } catch (error) { + if (input.target === "locked") throw error; + try { + rollbackAndRelease(surface, context, fence, "rollback-published"); + } catch (rollbackError) { + throw combinedFailure(error, rollbackError); + } + throw error; + } + + try { + surface.publish(context, fence); + surface.assertFenced(context, fence); + } catch (error) { + if (input.target === "locked") throw error; + try { + rollbackAndRelease(surface, context, fence, "rollback-published"); + } catch (rollbackError) { + throw combinedFailure(error, rollbackError); + } + throw error; + } + + let proof: RuntimeProviderStateMutationActivationProof; + try { + proof = surface.activate(context, fence); + } catch (error) { + if (input.target === "locked") throw error; + try { + rollbackAndRelease(surface, context, fence, "rollback-published"); + } catch (rollbackError) { + throw combinedFailure(error, rollbackError); + } + throw error; + } + releaseTarget(surface, context, fence, proof); + return Object.freeze({ fence, proof }); +} diff --git a/src/lib/shields/index.test.ts b/src/lib/shields/index.test.ts index 794c3feccaa..13258a9cc67 100644 --- a/src/lib/shields/index.test.ts +++ b/src/lib/shields/index.test.ts @@ -485,7 +485,7 @@ describe("shields — unit logic", () => { ); } - it("shieldsStatus attempts inline recovery for expired marker when timer PID is dead", async () => { + it("shieldsStatus attempts inline recovery for an expired timer marker", async () => { const sandboxName = "openclaw"; const configPath = "/sandbox/.openclaw/openclaw.json"; const hashPath = "/sandbox/.openclaw/.config-hash"; @@ -547,9 +547,9 @@ describe("shields — unit logic", () => { shieldsStatus(sandboxName); - expect(processKillSpy).toHaveBeenCalledWith(4242, 0); + expect(processKillSpy).not.toHaveBeenCalled(); expect(errorSpy).toHaveBeenCalledWith( - " Warning: auto-restore timer marker is expired and the timer process is not the recorded shields timer; attempting inline restore.", + " Warning: auto-restore timer authority is expired, invalid, or no longer live; attempting inline restore.", ); expect(logSpy).toHaveBeenCalledWith(" Shields: DOWN (temporarily unlocked)"); }); @@ -706,7 +706,7 @@ describe("shields — unit logic", () => { expect(createTempDirectory).not.toHaveBeenCalled(); }); - it("shieldsStatus warns and stays DOWN when inline recovery fails", async () => { + it("shieldsStatus warns and stays DOWN when the restrictive snapshot is missing", async () => { const sandboxName = "openclaw"; const missingSnapshotPath = path.join(stateDir(), "missing-snapshot.yaml"); writeState(sandboxName, { @@ -742,10 +742,7 @@ describe("shields — unit logic", () => { expect(logSpy).toHaveBeenCalledWith(" Shields: DOWN (temporarily unlocked)"); expect(errorSpy).toHaveBeenCalledWith( - " Recovery warning: inline auto-restore failed; shields remain DOWN.", - ); - expect(errorSpy).toHaveBeenCalledWith( - ` Recovery warning: run \`nemoclaw ${sandboxName} shields up\` manually.`, + " Recovery warning: DOWN state has no usable timer authority or restrictive policy snapshot.", ); expect(fs.existsSync(path.join(stateDir(), `shields-timer-${sandboxName}.json`))).toBe(true); }); @@ -853,7 +850,7 @@ describe("shields — unit logic", () => { shieldsStatus(sandboxName); expect(errorSpy).toHaveBeenCalledWith( - " Warning: auto-restore timer marker is expired and the timer process is not the recorded shields timer; attempting inline restore.", + " Warning: auto-restore timer authority is expired, invalid, or no longer live; attempting inline restore.", ); expect(logSpy).toHaveBeenCalledWith(" Shields: DOWN (temporarily unlocked)"); }); diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index 99fdf735d16..3e60ee675f7 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -24,7 +24,7 @@ import { run, runCapture, validateName } from "../runner"; const fs = require("fs"); const path = require("path"); const { fork } = require("child_process"); -const { randomBytes } = require("crypto"); +const { createHash, randomBytes } = require("crypto"); const { CLI_NAME }: typeof import("../cli/branding") = require("../cli/branding"); const { isObjectRecord }: typeof import("../core/json-types") = require("../core/json-types"); const { @@ -34,6 +34,7 @@ const { const { isDirectSandboxFallbackUnavailableError, privilegedSandboxExecArgv, + withPrivilegedSandboxExecutionLease, }: typeof import("../sandbox/privileged-exec") = require("../sandbox/privileged-exec"); const { buildPolicyGetCommand, @@ -46,6 +47,7 @@ const { timerMarkerPath, readTimerMarker, clearTimerMarker, + hasExactTimerAuthorizationProof, isProcessAlive, readProcessStartIdentity, processInspectionDeadlineAfter, @@ -53,10 +55,10 @@ const { verifyTimerMarkerIdentity, killTimer, } = require("./timer-control"); -const { resolveNemoclawStateDir } = require("../state/paths"); const { appendAuditEntry } = require("./audit"); const { resolveAgentConfig, + resolveRegisteredSandboxAgentAuthority, resolveAgentStateLockContract, }: typeof import("../sandbox/agent-config") = require("../sandbox/agent-config"); const { @@ -77,6 +79,7 @@ const { const { inspectAnyShieldsTransitionLockOwner, isShieldsTransitionLockUnavailable, + resolveShieldsStateDir, withShieldsTransitionLock, }: typeof import("./transition-lock") = require("./transition-lock"); const { @@ -88,6 +91,7 @@ const { withMcpLifecycleLockSync, withTimerBoundAutoRestoreLock, withTimerBoundShieldsMutationLock, + withTimerBoundShieldsMutationLockFallback, }: typeof import("./timer-bound-lock") = require("./timer-bound-lock"); const { buildConfigHashRepairCommand, @@ -117,15 +121,23 @@ const { const { normalizeMutableOpenClawConfig, }: typeof import("./mutable-config-repair") = require("./mutable-config-repair"); +const { + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PATH, + hasActiveHermesRuntimeProviderStateMutation, + runHermesRuntimeProviderStateMutation, + supportsHermesRuntimeProviderStateMutation, +}: typeof import("./hermes-runtime-state-mutation") = require("./hermes-runtime-state-mutation"); type MutableConfigPermsInspection = import("./mutable-config-perms").MutableConfigPermsInspection; type MutableConfigRepairResult = import("./mutable-config-perms").MutableConfigRepairResult; type AgentStateLockPlan = import("../agent/definition-types").AgentStateLockPlan; type ManagedMcpPolicyOmission = import("./permissive-runtime").ManagedMcpPolicyOmission; type TimerMarker = import("./timer-control").TimerMarker; -const STATE_DIR = resolveNemoclawStateDir(); +const STATE_DIR = resolveShieldsStateDir(); const SHIELDS_TRANSITION_POLL_MS = 50; const SHIELDS_TRANSITION_HANDOFF_GRACE_MS = 500; const SHIELDS_TRANSITION_TERMINATE_GRACE_MS = 1000; +const SHIELDS_TIMER_START_IDENTITY_WAIT_MS = 1000; +const SHIELDS_TIMER_AUTHORIZATION_WAIT_MS = 5000; const INTERACTIVE_CONTAINMENT_COMMIT_MAX_ATTEMPTS = Math.floor(SHIELDS_TRANSITION_HANDOFF_GRACE_MS / SHIELDS_TRANSITION_POLL_MS) + 1; const AUTO_RESTORE_COMPLETION_GRACE_MS = 30_000; @@ -138,12 +150,34 @@ const HERMES_RUNTIME_CONFIG_GUARD = "/usr/local/lib/nemoclaw/hermes-runtime-conf 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 HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PROBE = [ + "import os", + "import sys", + "try:", + " os.lstat(sys.argv[1])", + "except FileNotFoundError:", + ' print("absent")', + "else:", + ' print("present")', +].join("\n"); const STATE_DIR_GUARD_TIMEOUT_MS = 15 * 60 * 1000; const OPENCLAW_CONFIG_GUARD_TIMEOUT_MS = 6 * 60 * 1000; // Exceeds the failed-startup guard's 25-minute in-container timeout and its // five-second termination grace, so the host never abandons a live recovery. const OPENCLAW_CONFIG_GUARD_RECOVERY_TIMEOUT_MS = 26 * 60 * 1000; const HERMES_CONFIG_GUARD_TIMEOUT_MS = 11 * 60 * 1000; +const MAX_SHIELDS_FORWARD_POLICY_BYTES = 16 * 1024 * 1024; + +type ShieldsDownForwardPolicy = { + schemaVersion: 1; + path: string; + sha256: string; + size: number; + mode: number; + uid: number; + gid: number; + nlink: 1; +}; type ShieldsDownTransition = { version: 1; @@ -155,6 +189,8 @@ type ShieldsDownTransition = { snapshotPath: string; /** Exact generated MCP keys owned when snapshotPath was captured. */ managedMcpPolicyKeys?: string[]; + /** Durable exact policy replay authority for interrupted forward recovery. */ + forwardPolicy?: ShieldsDownForwardPolicy; }; const transitionPollBuffer = new Int32Array(new SharedArrayBuffer(4)); @@ -166,7 +202,11 @@ function sameTimerMarkerGeneration(current: TimerMarker | null, expected: TimerM current.snapshotPath === expected.snapshotPath && current.restoreAt === expected.restoreAt && current.processToken === expected.processToken && + current.timerProcessStartIdentity === expected.timerProcessStartIdentity && current.allowLegacyHermesProtocol === expected.allowLegacyHermesProtocol && + current.agentName === expected.agentName && + current.configPath === expected.configPath && + current.configDir === expected.configDir && current.leaseOwnerPid === expected.leaseOwnerPid && current.leaseOwnerStartIdentity === expected.leaseOwnerStartIdentity ); @@ -178,6 +218,55 @@ function assertTimerMarkerGeneration(sandboxName: string, expected: TimerMarker) } } +function isExactLiveFutureTimerAuthority(marker: TimerMarker, now = Date.now()): boolean { + const restoreAtMs = new Date(marker.restoreAt).getTime(); + if (!Number.isFinite(restoreAtMs) || restoreAtMs <= now || !marker.timerProcessStartIdentity) { + return false; + } + const deadline = processInspectionDeadlineAfter(SHIELDS_TRANSITION_TERMINATE_GRACE_MS); + return ( + isProcessAlive(marker.pid, deadline) && + readProcessStartIdentity(marker.pid, deadline) === marker.timerProcessStartIdentity && + verifyTimerMarkerIdentity(marker).verified && + hasExactTimerAuthorizationProof(marker) + ); +} + +function assertExactLiveFutureTimerAuthority(sandboxName: string, marker: TimerMarker): void { + assertTimerMarkerGeneration(sandboxName, marker); + if (!isExactLiveFutureTimerAuthority(marker)) { + throw new Error( + "Interrupted Hermes Shields down recovery has no exact live future auto-restore timer authority", + ); + } + assertTimerMarkerGeneration(sandboxName, marker); +} + +function waitForTimerProcessStartIdentity(pid: number): string | null { + const deadline = Date.now() + SHIELDS_TIMER_START_IDENTITY_WAIT_MS; + while (true) { + const identity = readProcessStartIdentity(pid); + if (identity) return identity; + if (Date.now() >= deadline || !isProcessAlive(pid)) return null; + Atomics.wait(transitionPollBuffer, 0, 0, SHIELDS_TRANSITION_POLL_MS); + } +} + +function waitForTimerAuthorizationProof(marker: TimerMarker): boolean { + const deadline = Date.now() + SHIELDS_TIMER_AUTHORIZATION_WAIT_MS; + while (true) { + if (hasExactTimerAuthorizationProof(marker)) return true; + if ( + Date.now() >= deadline || + !isProcessAlive(marker.pid) || + readProcessStartIdentity(marker.pid) !== marker.timerProcessStartIdentity + ) { + return false; + } + Atomics.wait(transitionPollBuffer, 0, 0, SHIELDS_TRANSITION_POLL_MS); + } +} + function appendAuditEntryBestEffort(entry: Parameters[0]): void { try { appendAuditEntry(entry); @@ -190,6 +279,32 @@ function shieldsDownTransitionPath(sandboxName: string, processToken: string): s return path.join(STATE_DIR, `shields-transition-${sandboxName}-${processToken}.json`); } +function shieldsDownForwardPolicyPath(sandboxName: string, processToken: string): string { + return path.join(STATE_DIR, `shields-forward-policy-${sandboxName}-${processToken}.yaml`); +} + +function isShieldsDownForwardPolicy(value: unknown): value is ShieldsDownForwardPolicy { + if (!isObjectRecord(value)) return false; + return ( + value.schemaVersion === 1 && + typeof value.path === "string" && + typeof value.sha256 === "string" && + /^[0-9a-f]{64}$/.test(value.sha256) && + typeof value.size === "number" && + Number.isSafeInteger(value.size) && + value.size > 0 && + value.size <= MAX_SHIELDS_FORWARD_POLICY_BYTES && + value.mode === 0o600 && + typeof value.uid === "number" && + Number.isSafeInteger(value.uid) && + value.uid >= 0 && + typeof value.gid === "number" && + Number.isSafeInteger(value.gid) && + value.gid >= 0 && + value.nlink === 1 + ); +} + function isShieldsDownTransition(value: unknown): value is ShieldsDownTransition { if (!isObjectRecord(value)) return false; return ( @@ -206,7 +321,8 @@ function isShieldsDownTransition(value: unknown): value is ShieldsDownTransition /^[0-9a-f]{32}$/.test(value.processToken) && typeof value.sandboxName === "string" && typeof value.snapshotPath === "string" && - isOptionalManagedMcpPolicyKeys(value.managedMcpPolicyKeys) + isOptionalManagedMcpPolicyKeys(value.managedMcpPolicyKeys) && + (value.forwardPolicy === undefined || isShieldsDownForwardPolicy(value.forwardPolicy)) ); } @@ -218,6 +334,190 @@ function sameManagedMcpPolicyKeys( return left.length === right.length && left.every((key, index) => key === right[index]); } +function sameShieldsDownForwardPolicy( + left: ShieldsDownForwardPolicy | undefined, + right: ShieldsDownForwardPolicy | undefined, +): boolean { + if (left === undefined || right === undefined) return left === right; + return ( + left.schemaVersion === right.schemaVersion && + left.path === right.path && + left.sha256 === right.sha256 && + left.size === right.size && + left.mode === right.mode && + left.uid === right.uid && + left.gid === right.gid && + left.nlink === right.nlink + ); +} + +function sameShieldsDownTransitionAuthority( + left: ShieldsDownTransition, + right: ShieldsDownTransition, + phase: ShieldsDownTransition["phase"] = right.phase, +): boolean { + return ( + left.version === right.version && + left.phase === phase && + left.ownerPid === right.ownerPid && + left.ownerStartIdentity === right.ownerStartIdentity && + left.processToken === right.processToken && + left.sandboxName === right.sandboxName && + left.snapshotPath === right.snapshotPath && + sameManagedMcpPolicyKeys(left.managedMcpPolicyKeys, right.managedMcpPolicyKeys) && + sameShieldsDownForwardPolicy(left.forwardPolicy, right.forwardPolicy) + ); +} + +function fsyncShieldsStateDirectory(): void { + const directoryFd = fs.openSync(STATE_DIR, "r"); + try { + fs.fsyncSync(directoryFd); + } finally { + fs.closeSync(directoryFd); + } +} + +function writeShieldsFileAtomicDurable( + filePath: string, + content: string | Buffer, + mode = 0o600, + replaceExisting = true, +): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 }); + const tempPath = `${filePath}.${String(process.pid)}.${randomBytes(8).toString("hex")}.tmp`; + let fd: number | undefined; + try { + fd = fs.openSync( + tempPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, + mode, + ); + fs.writeFileSync(fd, content); + fs.fchmodSync(fd, mode); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = undefined; + if (replaceExisting) { + fs.renameSync(tempPath, filePath); + } else { + fs.linkSync(tempPath, filePath); + fs.unlinkSync(tempPath); + } + const directoryFd = fs.openSync(path.dirname(filePath), "r"); + try { + fs.fsyncSync(directoryFd); + } finally { + fs.closeSync(directoryFd); + } + } finally { + if (fd !== undefined) fs.closeSync(fd); + fs.rmSync(tempPath, { force: true }); + } +} + +function publishShieldsDownForwardPolicy( + sandboxName: string, + processToken: string, + sourcePath: string, +): ShieldsDownForwardPolicy { + const content = fs.readFileSync(sourcePath); + if (content.length === 0 || content.length > MAX_SHIELDS_FORWARD_POLICY_BYTES) { + throw new Error( + `Shields-down forward policy must contain 1-${String(MAX_SHIELDS_FORWARD_POLICY_BYTES)} bytes`, + ); + } + const artifactPath = shieldsDownForwardPolicyPath(sandboxName, processToken); + const flags = + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW; + let fd: number | undefined; + let created = false; + try { + fd = fs.openSync(artifactPath, flags, 0o600); + created = true; + fs.writeFileSync(fd, content); + fs.fchmodSync(fd, 0o600); + fs.fsyncSync(fd); + const metadata = fs.fstatSync(fd); + if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 0o777) !== 0o600) { + throw new Error("Shields-down forward policy was published with unsafe metadata"); + } + const currentUid = typeof process.getuid === "function" ? process.getuid() : metadata.uid; + if (metadata.uid !== currentUid) { + throw new Error("Shields-down forward policy is not owned by the current host identity"); + } + fs.closeSync(fd); + fd = undefined; + fsyncShieldsStateDirectory(); + return Object.freeze({ + schemaVersion: 1, + path: artifactPath, + sha256: createHash("sha256").update(content).digest("hex"), + size: content.length, + mode: 0o600, + uid: metadata.uid, + gid: metadata.gid, + nlink: 1, + }); + } catch (error) { + if (fd !== undefined) fs.closeSync(fd); + if (created) fs.rmSync(artifactPath, { force: true }); + throw error; + } +} + +function requireShieldsDownForwardPolicy(transition: ShieldsDownTransition): string { + const binding = transition.forwardPolicy; + const expectedPath = shieldsDownForwardPolicyPath( + transition.sandboxName, + transition.processToken, + ); + if (!binding || binding.path !== expectedPath || path.normalize(binding.path) !== binding.path) { + throw new Error( + "Interrupted Shields down recovery is missing its exact forward-policy authority", + ); + } + let fd: number | undefined; + try { + fd = fs.openSync( + binding.path, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + const before = fs.fstatSync(fd); + if ( + !before.isFile() || + before.nlink !== binding.nlink || + (before.mode & 0o777) !== binding.mode || + before.uid !== binding.uid || + before.gid !== binding.gid || + before.size !== binding.size || + (typeof process.getuid === "function" && before.uid !== process.getuid()) + ) { + throw new Error("Interrupted Shields down forward policy has unsafe metadata"); + } + const content = fs.readFileSync(fd); + const after = fs.fstatSync(fd); + if ( + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeMs !== after.mtimeMs || + content.length !== binding.size || + createHash("sha256").update(content).digest("hex") !== binding.sha256 + ) { + throw new Error("Interrupted Shields down forward policy no longer matches its binding"); + } + return binding.path; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Cannot validate interrupted Shields down forward policy: ${message}`, { + cause: error, + }); + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + function readShieldsDownTransition( sandboxName: string, processToken: string, @@ -252,18 +552,31 @@ function writeShieldsDownTransition( !current || current.phase !== expectedPhase || current.ownerPid !== transition.ownerPid || + current.ownerStartIdentity !== transition.ownerStartIdentity || current.snapshotPath !== transition.snapshotPath || - !sameManagedMcpPolicyKeys(current.managedMcpPolicyKeys, transition.managedMcpPolicyKeys) + !sameManagedMcpPolicyKeys(current.managedMcpPolicyKeys, transition.managedMcpPolicyKeys) || + !sameShieldsDownForwardPolicy(current.forwardPolicy, transition.forwardPolicy) ) { throw new Error("Shields-down recovery ownership changed during the transition"); } } const tempPath = `${transitionPath}.${String(process.pid)}.${randomBytes(8).toString("hex")}.tmp`; + let tempFd: number | undefined; try { - fs.writeFileSync(tempPath, JSON.stringify(transition), { flag: "wx", mode: 0o600 }); + tempFd = fs.openSync( + tempPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, + 0o600, + ); + fs.writeFileSync(tempFd, JSON.stringify(transition)); + fs.fsyncSync(tempFd); + fs.closeSync(tempFd); + tempFd = undefined; fs.renameSync(tempPath, transitionPath); + fsyncShieldsStateDirectory(); } finally { + if (tempFd !== undefined) fs.closeSync(tempFd); try { fs.rmSync(tempPath, { force: true }); } catch { @@ -273,27 +586,30 @@ function writeShieldsDownTransition( } function writeTimerMarkerAtomic(sandboxName: string, marker: TimerMarker): void { - const markerPath = timerMarkerPath(sandboxName); - fs.mkdirSync(path.dirname(markerPath), { recursive: true, mode: 0o700 }); - const tempPath = `${markerPath}.${String(process.pid)}.${randomBytes(8).toString("hex")}.tmp`; - try { - fs.writeFileSync(tempPath, JSON.stringify(marker), { flag: "wx", mode: 0o600 }); - fs.renameSync(tempPath, markerPath); - } finally { - try { - fs.rmSync(tempPath, { force: true }); - } catch { - // Best effort. The authoritative path was either atomically replaced or unchanged. - } - } + writeShieldsFileAtomicDurable(timerMarkerPath(sandboxName), JSON.stringify(marker)); } function clearShieldsDownTransition(sandboxName: string, processToken: string): void { + let removed = false; try { fs.rmSync(shieldsDownTransitionPath(sandboxName, processToken), { force: true }); + removed = true; } catch { // Best effort. A stale transition marker never grants mutation authority. } + try { + fs.rmSync(shieldsDownForwardPolicyPath(sandboxName, processToken), { force: true }); + removed = true; + } catch { + // Best effort. The deterministic artifact path cannot grant authority alone. + } + if (removed) { + try { + fsyncShieldsStateDirectory(); + } catch { + // Best effort. Neither retired path can grant recovery authority alone. + } + } } type ExactProcessStatus = "current" | "gone" | "unknown"; @@ -368,7 +684,8 @@ function waitForShieldsDownForwardCommit( next.ownerStartIdentity !== observed.ownerStartIdentity || next.snapshotPath !== observed.snapshotPath || next.processToken !== observed.processToken || - !sameManagedMcpPolicyKeys(next.managedMcpPolicyKeys, observed.managedMcpPolicyKeys) + !sameManagedMcpPolicyKeys(next.managedMcpPolicyKeys, observed.managedMcpPolicyKeys) || + !sameShieldsDownForwardPolicy(next.forwardPolicy, observed.forwardPolicy) ) { throw new Error("Shields-down recovery ownership changed while waiting for forward commit"); } @@ -466,17 +783,21 @@ function openClawRollbackIssue(prefix: string, error: unknown): OpenClawRollback } function privilegedSandboxExec(sandboxName: string, cmd: string[], timeout = 15000): void { - dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { - stdio: ["ignore", "pipe", "pipe"], - timeout, + withPrivilegedSandboxExecutionLease(sandboxName, "shields privileged execution", () => { + dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { + stdio: ["ignore", "pipe", "pipe"], + timeout, + }); }); } function privilegedSandboxExecCapture(sandboxName: string, cmd: string[], timeout = 15000): string { - return dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { - stdio: ["ignore", "pipe", "pipe"], - timeout, - }).trim(); + return withPrivilegedSandboxExecutionLease(sandboxName, "shields privileged capture", () => + dockerExecFileSync(privilegedSandboxExecArgv(sandboxName, cmd, false, true), { + stdio: ["ignore", "pipe", "pipe"], + timeout, + }).trim(), + ); } function hermesShieldsGuardArgs( @@ -502,7 +823,11 @@ function hermesShieldsGuardArgs( ]; } -type HermesShieldsProtocol = "sealed-plan-v1" | "sealed-v1" | "legacy"; +type HermesShieldsProtocol = + | "provider-state-mutation-v2" + | "sealed-plan-v1" + | "sealed-v1" + | "legacy"; const HERMES_SEALED_V1_CONTRACT = [ "begin-shields-transition", @@ -523,11 +848,94 @@ const HERMES_LEGACY_GUARD_CONTRACT = [ "provider-placeholders", ] as const; +function hasActiveRuntimeProviderStateMutation(sandboxName: string): boolean { + return hasActiveHermesRuntimeProviderStateMutation(sandboxName, STATE_DIR); +} + +/** + * Drain retained provider authority before a Shields command can return from + * persisted state or invoke an ordinary privileged container command. The + * full same-locked transition first recovers the retained plan to its + * fail-closed rollback, then republishes and verifies the complete recursive + * locked plan before releasing the new fence. + */ +function resolveActiveHermesRuntimeProviderMutationTarget( + sandboxName: string, +): AgentConfigTarget | null { + if (!hasActiveRuntimeProviderStateMutation(sandboxName)) return null; + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + if (target.agentName !== "hermes") { + throw new Error( + "An active runtime-provider state mutation no longer matches the Hermes sandbox registry authority", + ); + } + return target; +} + +function recoverActiveHermesRuntimeProviderMutation(sandboxName: string): AgentConfigTarget | null { + const target = resolveActiveHermesRuntimeProviderMutationTarget(sandboxName); + if (!target) return null; + runHermesProviderProtectionTransition(sandboxName, target, "locked", "locked"); + return target; +} + function inspectHermesShieldsProtocol( sandboxName: string, target: AgentConfigTarget, ): HermesShieldsProtocol { if (target.agentName !== "hermes") return "sealed-plan-v1"; + const { sandbox } = resolveRegisteredSandboxAgentAuthority(sandboxName); + if (!sandbox || sandbox.agent !== "hermes") { + throw new Error("Hermes shields protocol inspection lost its exact sandbox registry authority"); + } + if (hasActiveRuntimeProviderStateMutation(sandboxName)) { + return "provider-state-mutation-v2"; + } + if ( + sandbox.openshellDriver?.trim().toLowerCase() === "docker" && + sandbox.workload?.kind === "managed-image" && + !sandbox.lifecycleGeneration + ) { + throw new Error("Managed Hermes Docker registry authority has no lifecycle generation"); + } + if ( + sandbox.openshellDriver?.trim().toLowerCase() === "docker" && + sandbox.workload?.kind === "managed-image" && + sandbox.lifecycleGeneration + ) { + const capabilityPresence = privilegedSandboxExecCapture(sandboxName, [ + HERMES_PYTHON, + "-I", + "-c", + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PROBE, + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PATH, + ]); + if (capabilityPresence === "present") { + const metadata = privilegedSandboxExecCapture(sandboxName, [ + "stat", + "-c", + "%a %u %g %h %F", + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PATH, + ]); + const content = privilegedSandboxExecCapture(sandboxName, [ + "cat", + HERMES_RUNTIME_STATE_MUTATION_CAPABILITY_PATH, + ]); + if (supportsHermesRuntimeProviderStateMutation(sandbox, { content, metadata })) { + return "provider-state-mutation-v2"; + } + throw new Error( + "Hermes runtime state-mutation capability is present but invalid or unsupported; rebuild the sandbox", + ); + } + if (capabilityPresence !== "absent") { + throw new Error( + `Unexpected Hermes runtime state-mutation capability probe response: ${capabilityPresence}`, + ); + } + // A successful lstat probe proved the old image has no provider publisher + // capability. Only that exact absence may select its sealed-plan protocol. + } const help = privilegedSandboxExecCapture( sandboxName, [ @@ -716,6 +1124,94 @@ function runHermesStateDirTransition( ); } +function requireHermesRuntimeProviderSandbox(sandboxName: string) { + const { sandbox } = resolveRegisteredSandboxAgentAuthority(sandboxName); + if ( + !sandbox || + sandbox.agent !== "hermes" || + sandbox.openshellDriver?.trim().toLowerCase() !== "docker" || + sandbox.workload?.kind !== "managed-image" || + !sandbox.lifecycleGeneration + ) { + throw new Error( + "Hermes runtime-provider state mutation lost its exact managed Docker registry authority", + ); + } + return sandbox; +} + +function runHermesProviderProtectionTransition( + sandboxName: string, + configTarget: AgentConfigTarget, + targetPosture: "locked" | "mutable", + rollback: "locked" | "mutable", +): void { + runHermesRuntimeProviderStateMutation({ + environment: process.env, + sandbox: requireHermesRuntimeProviderSandbox(sandboxName), + sandboxName, + configTarget, + target: targetPosture, + rollback, + }); +} + +function verifyHermesProviderMutablePosture(sandboxName: string, target: AgentConfigTarget): void { + const issues: string[] = []; + for (const file of [target.configPath, ...(target.sensitiveFiles || [])]) { + try { + const [mode, owner] = privilegedSandboxExecCapture(sandboxName, [ + "stat", + "-c", + "%a %U:%G", + file, + ]).split(" "); + if (mode !== "640") issues.push(`${file} mode=${mode} (expected 640)`); + if (owner !== "sandbox:sandbox") { + issues.push(`${file} owner=${owner} (expected sandbox:sandbox)`); + } + const [flags] = privilegedSandboxExecCapture(sandboxName, ["lsattr", "-d", file]) + .trim() + .split(/\s+/, 1); + if (flags.includes("i")) issues.push(`${file} immutable bit still set`); + } catch (error) { + issues.push( + `${file} verification failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + try { + const [mode, owner] = privilegedSandboxExecCapture(sandboxName, [ + "stat", + "-c", + "%a %U:%G", + target.configDir, + ]).split(" "); + if (mode !== "3770") issues.push(`${target.configDir} mode=${mode} (expected 3770)`); + if (owner !== "sandbox:sandbox") { + issues.push(`${target.configDir} owner=${owner} (expected sandbox:sandbox)`); + } + } catch (error) { + issues.push( + `${target.configDir} verification failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (issues.length > 0) throw new Error(`Config not unlocked: ${issues.join(", ")}`); +} + +function hermesProviderChattrApplied(sandboxName: string, target: AgentConfigTarget): boolean { + try { + return [target.configPath, ...(target.sensitiveFiles || [])].every((file) => { + const [flags] = privilegedSandboxExecCapture(sandboxName, ["lsattr", "-d", file]) + .trim() + .split(/\s+/, 1); + return flags.includes("i"); + }); + } catch { + return false; + } +} + // Re-export for tests and external consumers const MAX_TIMEOUT_SECONDS = MAX_SECONDS; const DEFAULT_TIMEOUT_SECONDS = DEFAULT_SECONDS; @@ -1020,17 +1516,7 @@ function inspectExpiredAutoRestoreMarker(sandboxName: string): TimerMarker | nul if (state._isCorrupt || state.shieldsDown !== true) return null; const marker = readTimerMarker(sandboxName); if (!marker) return null; - const restoreAtMs = new Date(marker.restoreAt).getTime(); - const now = Date.now(); - if (!Number.isFinite(restoreAtMs) || restoreAtMs > now) return null; - if ( - isProcessAlive(marker.pid) && - verifyTimerMarkerIdentity(marker).verified && - now <= restoreAtMs + AUTO_RESTORE_COMPLETION_GRACE_MS - ) { - return null; - } - return marker; + return isExactLiveFutureTimerAuthority(marker) ? null : marker; } function inspectExpiredAutoRestoreTakeover( @@ -1163,18 +1649,48 @@ function withExpiredAutoRestoreDeadlineFence( sandboxName: string, command: string, operation: (allowInlineRecovery: boolean) => T, + fallbackTakeoverToken?: string, ): T { const expiredMarker = inspectExpiredAutoRestoreMarker(sandboxName); const takeover = inspectExpiredAutoRestoreTakeover(sandboxName, expiredMarker); const runWithHostLock = (callback: () => T) => - withTimerBoundShieldsMutationLock(sandboxName, command, callback); - const recoverThenRun = () => + fallbackTakeoverToken + ? withTimerBoundShieldsMutationLockFallback( + sandboxName, + command, + fallbackTakeoverToken, + callback, + ) + : withTimerBoundShieldsMutationLock(sandboxName, command, callback); + const retireUnexpectedFreshTimerGeneration = () => { + if (!fallbackTakeoverToken) return; + const state = loadShieldsState(sandboxName); + if (state._isCorrupt || state.shieldsDown === true || !readTimerMarker(sandboxName)) return; + withTimerBoundShieldsMutationLock(sandboxName, command, () => { + const marker = readTimerMarker(sandboxName); + const currentState = loadShieldsState(sandboxName); + if (!marker || currentState._isCorrupt || currentState.shieldsDown === true) return; + const revocation = killTimer(sandboxName); + for (const warning of revocation.warnings) console.warn(` ${warning}`); + if (!revocation.authorityRevoked) { + throw new Error( + `Cannot revoke stale auto-restore timer authority for ${sandboxName}; refusing to create a replacement generation`, + ); + } + if (marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { + clearShieldsDownTransition(sandboxName, marker.processToken); + } + }); + }; + const recoverThenRun = () => { withTimerBoundAutoRestoreLock(sandboxName, command, () => { if (takeover) retryInlineAutoRestore(sandboxName, takeover.marker); - return operation(false); }); + return runWithHostLock(() => operation(false)); + }; if (isMcpLifecycleLockHeld(sandboxName, STATE_DIR)) { if (!expiredMarker || !takeover) { + retireUnexpectedFreshTimerGeneration(); return runWithHostLock(() => operation(true)); } const { marker } = takeover; @@ -1184,14 +1700,24 @@ function withExpiredAutoRestoreDeadlineFence( marker.snapshotPath, () => assertTimerMarkerGeneration(sandboxName, marker), ); + if (fallbackTakeoverToken) { + retryInlineAutoRestore(sandboxName, marker); + } // This lifecycle owner is what the live timer is waiting on. Run the // nested operation without re-entering recovery against that timer. return runWithHostLock(() => operation(false)); } if (!takeover) { - return withMcpLifecycleLockSync(sandboxName, () => runWithHostLock(() => operation(true)), { - stateDir: STATE_DIR, - }); + return withMcpLifecycleLockSync( + sandboxName, + () => { + retireUnexpectedFreshTimerGeneration(); + return runWithHostLock(() => operation(true)); + }, + { + stateDir: STATE_DIR, + }, + ); } const { marker } = takeover; @@ -1293,8 +1819,7 @@ function saveShieldsState(sandboxName: string, patch: ShieldsState): ShieldsStat ...patch, updatedAt: new Date().toISOString(), }; - fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 }); - fs.writeFileSync(stateFilePath(sandboxName), JSON.stringify(updated, null, 2), { mode: 0o600 }); + writeShieldsFileAtomicDurable(stateFilePath(sandboxName), JSON.stringify(updated, null, 2)); return updated; } @@ -1310,11 +1835,10 @@ function restoreShieldsStateSnapshot(sandboxName: string, state: LoadedShieldsSt fs.rmSync(filePath, { force: true }); return; } - fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 }); if (isCorrupt) { throw new Error("Cannot restore a corrupt shields state snapshot"); } - fs.writeFileSync(filePath, JSON.stringify(persisted, null, 2), { mode: 0o600 }); + writeShieldsFileAtomicDurable(filePath, JSON.stringify(persisted, null, 2)); } function isOptionalBoolean(value: unknown): value is boolean | undefined { @@ -1383,50 +1907,52 @@ function isShieldsState(value: unknown): value is ShieldsState { function stateDirLockExec(sandboxName: string) { return { - 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 } : {}), - }; - }, + run: (cmd: string[], input?: string) => + withPrivilegedSandboxExecutionLease(sandboxName, "state directory guard", () => { + 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 timeout = cmd.includes("unlock-failed-startup") - ? OPENCLAW_CONFIG_GUARD_RECOVERY_TIMEOUT_MS - : OPENCLAW_CONFIG_GUARD_TIMEOUT_MS; - const result = dockerSpawnSync( - privilegedSandboxExecArgv(sandboxName, cmd, input !== undefined, true), - { - encoding: "utf-8", - input, - timeout, - 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 } : {}), - }; - }, + run: (cmd: string[], input?: string) => + withPrivilegedSandboxExecutionLease(sandboxName, "OpenClaw config guard", () => { + const timeout = cmd.includes("unlock-failed-startup") + ? OPENCLAW_CONFIG_GUARD_RECOVERY_TIMEOUT_MS + : OPENCLAW_CONFIG_GUARD_TIMEOUT_MS; + const result = dockerSpawnSync( + privilegedSandboxExecArgv(sandboxName, cmd, input !== undefined, true), + { + encoding: "utf-8", + input, + timeout, + 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 } : {}), + }; + }), }; } @@ -2252,6 +2778,22 @@ function unlockAgentConfigUnderMutationLock( protocol: HermesShieldsProtocol, ): void { const target = ensureConfigHashSensitiveFile(rawTarget); + if (target.agentName === "hermes" && protocol === "provider-state-mutation-v2") { + if (!rollbackLocked) { + runHermesProviderProtectionTransition(sandboxName, target, "mutable", "mutable"); + try { + verifyHermesProviderMutablePosture(sandboxName, target); + return; + } catch { + // State-derived mutable-default authority disagrees with the live + // posture. Repair it with a restrictive rollback instead of creating + // an invalid same-posture provider plan. + } + } + runHermesProviderProtectionTransition(sandboxName, target, "mutable", "locked"); + verifyHermesProviderMutablePosture(sandboxName, target); + return; + } const compatibilityIssues = stateLockPlanCompatibilityIssues( stateDirLockExec(sandboxName), requireStateLockPlan(target), @@ -2664,6 +3206,38 @@ function lockAgentConfigUnderMutationLock( protocol: HermesShieldsProtocol, ): { chattrApplied: boolean; fileHashes: { [path: string]: string } } { const target = ensureConfigHashSensitiveFile(rawTarget); + if (target.agentName === "hermes" && protocol === "provider-state-mutation-v2") { + const verifyProviderLockedPosture = () => { + const chattrApplied = hermesProviderChattrApplied(sandboxName, target); + const verified = verifyShieldsLockState(sandboxName, target, { + verifyChattr: chattrApplied, + verifyParentProtection: true, + exec: (cmd: string[]) => privilegedSandboxExecCapture(sandboxName, cmd), + assertLegacyLayout: assertNoLegacyStateLayout, + }); + if (verified.issues.length > 0) { + throw new Error(`Config not locked: ${verified.issues.join(", ")}`); + } + return { + chattrApplied, + fileHashes: captureSealHashes(sandboxName, [ + target.configPath, + ...(target.sensitiveFiles || []), + ]), + }; + }; + if (rollbackLocked) { + runHermesProviderProtectionTransition(sandboxName, target, "locked", "locked"); + try { + return verifyProviderLockedPosture(); + } catch { + // Repair a drifted live posture with a mutable rollback. Locked-target + // failures retain the provider fence, so this remains fail-closed. + } + } + runHermesProviderProtectionTransition(sandboxName, target, "locked", "mutable"); + return verifyProviderLockedPosture(); + } const compatibilityIssues = stateLockPlanCompatibilityIssues( stateDirLockExec(sandboxName), requireStateLockPlan(target), @@ -3251,17 +3825,14 @@ function applyShieldsPolicySnapshot( marker?.sandboxName === sandboxName && marker.snapshotPath === snapshotPath && marker.processToken === options.transitionProcessToken; - const restoreAtMs = marker ? new Date(marker.restoreAt).getTime() : Number.NaN; - const expiredTimerIsInactive = + const timerAuthorityIsInactive = options.expiredTimerRecovery === true && markerMatchesRecovery && - Number.isFinite(restoreAtMs) && - restoreAtMs <= Date.now() && - (!isProcessAlive(marker!.pid) || !verifyTimerMarkerIdentity(marker!).verified); + !isExactLiveFutureTimerAuthority(marker!); if ( options.transitionProcessToken === undefined || !markerMatchesRecovery || - (marker!.pid !== process.pid && !expiredTimerIsInactive) + (marker!.pid !== process.pid && !timerAuthorityIsInactive) ) { throw new Error("The active auto-restore timer does not authorize deadline restoration"); } @@ -3373,10 +3944,16 @@ function rollbackShieldsDown( let timerAuthorityRevoked = false; let rollbackChattrApplied: boolean | null = null; let rollbackFileHashes: { [path: string]: string } | null = null; + const protocol = resolveHermesShieldsProtocol( + sandboxName, + target, + allowLegacyHermesProtocol, + cachedProtocol, + ); if (rollbackResult?.status === 0) { if (initialMode === "mutable_default" && target.agentName === "openclaw") { try { - unlockAgentConfig(sandboxName, target, false, allowLegacyHermesProtocol, cachedProtocol); + unlockAgentConfigUnderMutationLock(sandboxName, target, false, protocol); const timerCancellation = killTimer(sandboxName); timerAuthorityRevoked = timerCancellation.authorityRevoked; if (!timerCancellation.authorityRevoked) { @@ -3399,7 +3976,7 @@ function rollbackShieldsDown( // auto-restore path. Leaves the hashes null (→ "manual intervention" // below) when the lock will not re-confirm. const relock = relockAndReconfirm(() => - lockAgentConfig(sandboxName, target, true, allowLegacyHermesProtocol, cachedProtocol), + lockAgentConfigUnderMutationLock(sandboxName, target, true, protocol), ); if (relock.ok && relock.lastResult) { rollbackChattrApplied = relock.lastResult.chattrApplied; @@ -3413,6 +3990,15 @@ function rollbackShieldsDown( console.error(" Warning: Policy restore failed during rollback."); } if (rollbackChattrApplied !== null && rollbackFileHashes !== null) { + if (!timerAuthorityRevoked) { + const timerCancellation = killTimer(sandboxName); + timerAuthorityRevoked = timerCancellation.authorityRevoked; + if (!timerCancellation.authorityRevoked) { + console.error( + ` Warning: Lockdown was restored, but auto-restore timer authority could not be revoked: ${timerCancellation.warnings.join("; ")}`, + ); + } + } saveShieldsState(sandboxName, { shieldsDown: false, shieldsDownAt: null, @@ -3520,32 +4106,25 @@ function recoverExpiredAutoRestoreInline( if (state.shieldsDown !== true) return { attempted: false, restored: false }; const marker = readTimerMarker(sandboxName); - if (!marker) return { attempted: false, restored: false }; - - const restoreAtMs = new Date(marker.restoreAt).getTime(); - if (!Number.isFinite(restoreAtMs) || restoreAtMs > Date.now()) { + if (marker && isExactLiveFutureTimerAuthority(marker)) { return { attempted: false, restored: false }; } - // PID liveness alone is unsafe: after a reboot/OOM the original timer's PID - // can be reassigned to an unrelated live process, which would otherwise block - // 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) { - if (Date.now() <= restoreAtMs + AUTO_RESTORE_COMPLETION_GRACE_MS) { - return { attempted: false, restored: false }; - } + const snapshotPath = marker?.snapshotPath ?? state.shieldsPolicySnapshotPath; + if (!snapshotPath || !fs.existsSync(snapshotPath)) { console.error( - " Recovery warning: the expired auto-restore timer is still active; refusing portable process-tree preemption and waiting for it to exit.", + " Recovery warning: DOWN state has no usable timer authority or restrictive policy snapshot.", ); 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.", + marker + ? " Warning: auto-restore timer authority is expired, invalid, or no longer live; attempting inline restore." + : " Warning: DOWN state has a missing or malformed auto-restore marker; attempting inline restore under the lifecycle gate.", ); - if (marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { + if (marker?.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { try { synchronizeAutoRestoreTransition(sandboxName, marker.processToken, marker.snapshotPath, { expiredTimerRecovery: true, @@ -3568,14 +4147,14 @@ function recoverExpiredAutoRestoreInline( } } - const cachedTarget = resolvePersistedAutoRestoreTarget(sandboxName, marker); + const cachedTarget = marker ? resolvePersistedAutoRestoreTarget(sandboxName, marker) : undefined; const activation = activateLockdownFromSnapshot( sandboxName, - marker.snapshotPath, - marker.allowLegacyHermesProtocol === true, + snapshotPath, + marker?.allowLegacyHermesProtocol === true, cachedTarget, undefined, - marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken) + marker?.processToken && /^[0-9a-f]{32}$/.test(marker.processToken) ? { transitionProcessToken: marker.processToken, deadlineAuthoritative: true, @@ -3590,7 +4169,7 @@ function recoverExpiredAutoRestoreInline( sandbox: sandboxName, timestamp: nowIso, restored_by: "auto_timer", - policy_snapshot: marker.snapshotPath, + policy_snapshot: snapshotPath, error: `Inline auto-restore failed: ${activation.error ?? "unknown error"}`, }); console.error(" Recovery warning: inline auto-restore failed; shields remain DOWN."); @@ -3611,7 +4190,7 @@ function recoverExpiredAutoRestoreInline( } : {}), }); - if (marker.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { + if (marker?.processToken && /^[0-9a-f]{32}$/.test(marker.processToken)) { clearShieldsDownTransition(sandboxName, marker.processToken); } clearTimerMarker(sandboxName); @@ -3620,7 +4199,7 @@ function recoverExpiredAutoRestoreInline( sandbox: sandboxName, timestamp: nowIso, restored_by: "auto_timer", - policy_snapshot: marker.snapshotPath, + policy_snapshot: snapshotPath, restored_at: nowIso, ...(activation.managedMcpOmissions?.length ? { @@ -3659,7 +4238,6 @@ interface ShieldsDownOpts { timeout?: string | null; reason?: string | null; policy?: string; - skipTimer?: boolean; throwOnError?: boolean; allowLegacyHermesProtocol?: boolean; // Internal rebuild lease: once the deadline expires, the detached recovery @@ -3669,19 +4247,427 @@ interface ShieldsDownOpts { processToken?: string; } +type RecoveredShieldsDownCompletion = { + readonly alreadyCommitted: boolean; + readonly audit: Parameters[0]; + readonly marker: TimerMarker | null; + readonly authority: ShieldsDownTransition | null; + readonly transition: ShieldsDownTransition | null; +}; + +function prepareRecoveredShieldsDownCompletion( + sandboxName: string, + target: AgentConfigTarget, + state: LoadedShieldsState, +): RecoveredShieldsDownCompletion { + if ( + !state.shieldsDownAt || + !Number.isFinite(new Date(state.shieldsDownAt).getTime()) || + typeof state.shieldsDownTimeout !== "number" || + !state.shieldsDownPolicy || + !state.shieldsPolicySnapshotPath || + !fs.existsSync(state.shieldsPolicySnapshotPath) + ) { + throw new Error( + "Interrupted Hermes Shields down recovery is missing its exact persisted completion state", + ); + } + const audit: Parameters[0] = { + action: "shields_down", + sandbox: sandboxName, + timestamp: state.shieldsDownAt, + timeout_seconds: state.shieldsDownTimeout, + reason: state.shieldsDownReason ?? undefined, + policy_applied: state.shieldsDownPolicy, + policy_snapshot: state.shieldsPolicySnapshotPath, + }; + const marker = readTimerMarker(sandboxName); + if (!marker) { + throw new Error( + "Interrupted Hermes Shields down recovery lost its exact auto-restore timer authority", + ); + } + if ( + !marker.processToken || + !/^[0-9a-f]{32}$/.test(marker.processToken) || + marker.snapshotPath !== state.shieldsPolicySnapshotPath || + marker.agentName !== target.agentName || + marker.configPath !== target.configPath || + marker.configDir !== target.configDir + ) { + throw new Error( + "Interrupted Hermes Shields down recovery no longer matches its exact timer authority", + ); + } + const transition = readShieldsDownTransition(sandboxName, marker.processToken); + if ( + !transition || + transition.snapshotPath !== marker.snapshotPath || + !sameManagedMcpPolicyKeys(transition.managedMcpPolicyKeys, state.shieldsManagedMcpPolicyKeys) + ) { + throw new Error( + "Interrupted Hermes Shields down recovery no longer matches its timer-bound transition", + ); + } + if (transition.phase === "policy_rejected") { + throw new Error("A rejected Shields down transition cannot be recovered as mutable"); + } + requireShieldsDownForwardPolicy(transition); + return { + alreadyCommitted: transition.phase === "active", + audit, + marker, + authority: transition, + transition: transition.phase === "preparing" ? transition : null, + }; +} + +function applyRecoveredShieldsDownForwardPolicy( + sandboxName: string, + completion: RecoveredShieldsDownCompletion, +): void { + if (!completion.authority) return; + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); + const policyPath = requireShieldsDownForwardPolicy(completion.authority); + const result = run(buildPolicySetCommand(policyPath, sandboxName), { ignoreError: true }); + if (result.status !== 0) { + throw new Error("Interrupted Shields down forward policy could not be reapplied"); + } + requireShieldsDownForwardPolicy(completion.authority); + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); +} + +function assertRecoveredShieldsDownAuthority( + sandboxName: string, + completion: RecoveredShieldsDownCompletion, + phase: ShieldsDownTransition["phase"], +): void { + if (!completion.marker || !completion.authority) return; + assertExactLiveFutureTimerAuthority(sandboxName, completion.marker); + const current = readShieldsDownTransition(sandboxName, completion.authority.processToken); + if (!current || !sameShieldsDownTransitionAuthority(current, completion.authority, phase)) { + throw new Error("Interrupted Hermes Shields down recovery lost its exact transition authority"); + } + requireShieldsDownForwardPolicy(current); + assertExactLiveFutureTimerAuthority(sandboxName, completion.marker); +} + +function assertFreshShieldsDownAuthority( + sandboxName: string, + marker: TimerMarker, + transition: ShieldsDownTransition, + phase: ShieldsDownTransition["phase"], +): void { + assertExactLiveFutureTimerAuthority(sandboxName, marker); + const current = readShieldsDownTransition(sandboxName, transition.processToken); + if (!current || !sameShieldsDownTransitionAuthority(current, transition, phase)) { + throw new Error("Fresh Shields down lost its exact timer-bound transition authority"); + } + requireShieldsDownForwardPolicy(current); + assertExactLiveFutureTimerAuthority(sandboxName, marker); +} + +function resolveReleasedProviderShieldsDownTarget( + sandboxName: string, + state: LoadedShieldsState, + allowLegacyHermesProtocol: boolean, +): AgentConfigTarget | null { + if (!state.shieldsDown) return null; + const marker = readTimerMarker(sandboxName); + if (!marker?.processToken || !/^[0-9a-f]{32}$/.test(marker.processToken)) return null; + const transition = readShieldsDownTransition(sandboxName, marker.processToken); + if (transition?.phase !== "preparing") return null; + const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + if (target.agentName !== "hermes") return null; + return requireHermesShieldsProtocol(sandboxName, target, allowLegacyHermesProtocol) === + "provider-state-mutation-v2" + ? target + : null; +} + +function finishRecoveredHermesShieldsDown( + sandboxName: string, + completion: RecoveredShieldsDownCompletion, +): void { + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); + } + const convergence = waitForHermesInferenceRouteConvergence(sandboxName, { run }); + if (!convergence.ok) { + const status = convergence.httpStatus > 0 ? `HTTP ${convergence.httpStatus}` : "unavailable"; + throw new Error( + `Hermes inference route did not converge after policy transition (${status}; ${convergence.attempts} attempts)`, + ); + } + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); + } + if (completion.transition) { + writeShieldsDownTransition({ ...completion.transition, phase: "active" }, "preparing"); + } + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, "active"); + } +} + +function failRecoveredHermesShieldsDown( + sandboxName: string, + target: AgentConfigTarget, + state: LoadedShieldsState, + completion: RecoveredShieldsDownCompletion, + allowLegacyHermesProtocol: boolean, + error: unknown, + throwOnError: boolean | undefined, +): never { + const message = error instanceof Error ? error.message : String(error); + const rollback = rollbackShieldsDown( + sandboxName, + target, + state.shieldsPolicySnapshotPath as string, + "locked", + state, + allowLegacyHermesProtocol, + "provider-state-mutation-v2", + ); + if (completion.transition && rollback.timerAuthorityRevoked) { + clearShieldsDownTransition(sandboxName, completion.transition.processToken); + } + console.error(` ERROR: ${message}`); + const timerAuthority = describeRollbackTimerAuthority( + completion.transition !== null, + rollback.timerAuthorityRevoked, + ); + if (rollback.outcome === "lockdown_restored") { + console.error(` Interrupted config unlock was rolled back to lockdown.${timerAuthority}`); + } else { + console.error( + ` Interrupted config unlock recovery is incomplete.${timerAuthority} Manual intervention is required.`, + ); + } + return failShieldsCommand(message, throwOnError); +} + +type FreshShieldsDownTimerStart = { + transition: ShieldsDownTransition; + timerAuthority: TimerMarker; + policyPathForApply: string; +}; + +function startFreshShieldsDownTimer(input: { + sandboxName: string; + timeoutSeconds: number; + processToken: string; + snapshotPath: string; + target: AgentConfigTarget; + allowLegacyHermesProtocol: boolean; + deferAutoRestoreWhileOwnerAlive: boolean; + managedMcpPolicyKeys: string[]; + policyFile: string; +}): FreshShieldsDownTimerStart { + const { + sandboxName, + timeoutSeconds, + processToken, + snapshotPath, + target, + allowLegacyHermesProtocol, + deferAutoRestoreWhileOwnerAlive, + managedMcpPolicyKeys, + policyFile, + } = input; + const restoreAt = new Date(Date.now() + timeoutSeconds * 1000); + const timerScript = path.join(__dirname, "timer.ts"); + const timerScriptJs = timerScript.replace(/\.ts$/, ".js"); + const actualScript = fs.existsSync(timerScriptJs) ? timerScriptJs : timerScript; + let timerChild: ReturnType | null = null; + let transition: ShieldsDownTransition | null = null; + + try { + const ownerStartIdentity = + readProcessStartIdentity(process.pid) ?? + (() => { + throw new Error("Cannot identify shields-down owner process"); + })(); + const forwardPolicy = publishShieldsDownForwardPolicy(sandboxName, processToken, policyFile); + transition = { + version: 1, + phase: "preparing", + ownerPid: process.pid, + ownerStartIdentity, + processToken, + sandboxName, + snapshotPath, + managedMcpPolicyKeys, + forwardPolicy, + }; + const leaseOwnerPid = deferAutoRestoreWhileOwnerAlive ? transition.ownerPid : null; + const leaseOwnerStartIdentity = deferAutoRestoreWhileOwnerAlive + ? transition.ownerStartIdentity + : null; + // Publish forward ownership before authorizing the timer so an early + // deadline waits for active or owner death instead of racing mutations. + writeShieldsDownTransition(transition, null); + timerChild = fork( + actualScript, + [ + sandboxName, + snapshotPath, + restoreAt.toISOString(), + target.configPath, + target.configDir, + processToken, + allowLegacyHermesProtocol ? "1" : "0", + leaseOwnerPid === null ? "" : String(leaseOwnerPid), + leaseOwnerStartIdentity ?? "", + target.agentName ?? "", + ], + { + detached: true, + stdio: ["ignore", "ignore", "ignore", "ipc"], + }, + ); + if (!timerChild.pid) throw new Error("auto-restore timer did not report a process id"); + const timerProcessStartIdentity = waitForTimerProcessStartIdentity(timerChild.pid); + if (!timerProcessStartIdentity) { + throw new Error("auto-restore timer process identity could not be verified"); + } + const timerMarker: TimerMarker = { + pid: timerChild.pid, + sandboxName, + snapshotPath, + restoreAt: restoreAt.toISOString(), + processToken, + timerProcessStartIdentity, + allowLegacyHermesProtocol, + agentName: target.agentName, + configPath: target.configPath, + configDir: target.configDir, + ...(leaseOwnerPid !== null && leaseOwnerStartIdentity + ? { leaseOwnerPid, leaseOwnerStartIdentity } + : {}), + }; + writeTimerMarkerAtomic(sandboxName, timerMarker); + if (!timerChild.send({ type: "authorize", processToken, acknowledge: true })) { + throw new Error("auto-restore timer authorization channel closed early"); + } + if (!waitForTimerAuthorizationProof(timerMarker)) { + throw new Error("auto-restore timer did not publish exact authorization proof"); + } + assertExactLiveFutureTimerAuthority(sandboxName, timerMarker); + timerChild.disconnect(); + timerChild.unref(); + return { + transition, + timerAuthority: timerMarker, + policyPathForApply: forwardPolicy.path, + }; + } catch (error) { + clearTimerMarker(sandboxName); + if (transition) clearShieldsDownTransition(sandboxName, processToken); + if (timerChild) { + try { + timerChild.disconnect(); + } catch { + // The failed child may already have closed IPC. + } + timerChild.unref(); + } + throw error; + } +} + function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = {}): void { validateName(sandboxName, "sandbox name"); const state = loadShieldsState(sandboxName); + const retainedProviderTarget = resolveActiveHermesRuntimeProviderMutationTarget(sandboxName); if (state._isCorrupt) { + if (retainedProviderTarget) { + runHermesProviderProtectionTransition( + sandboxName, + retainedProviderTarget, + "locked", + "locked", + ); + } console.error(" Shields state is corrupt; refusing to unlock."); console.error( ` Recovery: inspect the reported state error and restore trusted state for ${sandboxName} before retrying.`, ); return failShieldsCommand(`Shields state is corrupt for ${sandboxName}`, opts.throwOnError); } + let recoveredProviderTarget: AgentConfigTarget | null = null; + if (retainedProviderTarget && state.shieldsDown !== true) { + runHermesProviderProtectionTransition(sandboxName, retainedProviderTarget, "locked", "locked"); + recoveredProviderTarget = retainedProviderTarget; + } const initialMode = deriveShieldsMode(state, state._hasStateFile); if (state.shieldsDown) { + // Provider release deliberately precedes route convergence and the final + // timer-bound transition commit. A process can therefore die after the + // durable provider claim is gone while the exact host transition remains + // in preparing. Treat that marker as recovery authority too: verify (or + // repair) mutable posture, converge the route, then commit it active. + const completionTarget = + retainedProviderTarget ?? + resolveReleasedProviderShieldsDownTarget( + sandboxName, + state, + opts.allowLegacyHermesProtocol === true, + ); + if (completionTarget) { + const completion = prepareRecoveredShieldsDownCompletion( + sandboxName, + completionTarget, + state, + ); + // The provisional DOWN record can outlive a process that lost its + // provider-unlock response. Recovery first restores the retained plan's + // restrictive rollback. Reconcile the recorded mutable posture and + // verify it before treating this retry as complete. + try { + applyRecoveredShieldsDownForwardPolicy(sandboxName, completion); + if (retainedProviderTarget) { + runHermesProviderProtectionTransition( + sandboxName, + retainedProviderTarget, + "locked", + "locked", + ); + } + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); + } + unlockAgentConfigUnderMutationLock( + sandboxName, + completionTarget, + false, + "provider-state-mutation-v2", + ); + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, completion.authority.phase); + } + finishRecoveredHermesShieldsDown(sandboxName, completion); + } catch (error) { + return failRecoveredHermesShieldsDown( + sandboxName, + completionTarget, + state, + completion, + opts.allowLegacyHermesProtocol === true, + error, + opts.throwOnError, + ); + } + if (!completion.alreadyCommitted) { + if (completion.authority) { + assertRecoveredShieldsDownAuthority(sandboxName, completion, "active"); + } + appendAuditEntry(completion.audit); + } + console.log(` Recovered interrupted config unlock for ${sandboxName}.`); + return; + } console.error( ` Config is already unlocked for ${sandboxName} (since ${state.shieldsDownAt}).`, ); @@ -3694,12 +4680,11 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = // 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, - ); + const target = + recoveredProviderTarget ?? ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const protocol: HermesShieldsProtocol = recoveredProviderTarget + ? "provider-state-mutation-v2" + : 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 @@ -3717,6 +4702,10 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = const timeoutSeconds = parseDuration(opts.timeout || `${DEFAULT_TIMEOUT_SECONDS}`); const reason = opts.reason || null; const policyName = opts.policy || "permissive"; + const processToken = opts.processToken ?? randomBytes(16).toString("hex"); + if (!/^[0-9a-f]{32}$/.test(processToken)) { + throw new Error("Invalid shields-down recovery process token"); + } // 1. Capture current policy snapshot console.log(" Capturing current policy snapshot..."); @@ -3746,10 +4735,11 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = } const snapshotManagedMcpPolicyKeys = managedMcpPolicies.map((policy) => policy.key); - const ts = Date.now(); - const snapshotPath = path.join(STATE_DIR, `policy-snapshot-${ts}.yaml`); - fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 }); - fs.writeFileSync(snapshotPath, policyYaml, { mode: 0o600 }); + const snapshotPath = path.join( + STATE_DIR, + `policy-snapshot-${sandboxName}-${processToken}-${randomBytes(8).toString("hex")}.yaml`, + ); + writeShieldsFileAtomicDurable(snapshotPath, policyYaml, 0o600, false); console.log(` Saved: ${snapshotPath}`); // 2. Determine and apply relaxed policy @@ -3803,97 +4793,36 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = }; const now = new Date().toISOString(); - let transition: ShieldsDownTransition | null = null; - // 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 = 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, + let timerStart: FreshShieldsDownTimerStart; + try { + timerStart = startFreshShieldsDownTimer({ sandboxName, + timeoutSeconds, + processToken, snapshotPath, + target, + allowLegacyHermesProtocol: opts.allowLegacyHermesProtocol === true, + deferAutoRestoreWhileOwnerAlive: opts.deferAutoRestoreWhileOwnerAlive === true, managedMcpPolicyKeys: snapshotManagedMcpPolicyKeys, - }; - const leaseOwnerPid = opts.deferAutoRestoreWhileOwnerAlive ? transition.ownerPid : null; - const leaseOwnerStartIdentity = opts.deferAutoRestoreWhileOwnerAlive - ? transition.ownerStartIdentity - : null; - let timerChild: ReturnType | null = null; - - try { - // 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, - snapshotPath, - restoreAt.toISOString(), - target.configPath, - target.configDir, - processToken, - opts.allowLegacyHermesProtocol === true ? "1" : "0", - leaseOwnerPid === null ? "" : String(leaseOwnerPid), - leaseOwnerStartIdentity ?? "", - target.agentName ?? "", - ], - { - detached: true, - stdio: ["ignore", "ignore", "ignore", "ipc"], - }, - ); - if (!timerChild.pid) throw new Error("auto-restore timer did not report a process id"); - writeTimerMarkerAtomic(sandboxName, { - pid: timerChild.pid, - sandboxName, - snapshotPath, - restoreAt: restoreAt.toISOString(), - processToken, - allowLegacyHermesProtocol: opts.allowLegacyHermesProtocol === true, - agentName: target.agentName, - configPath: target.configPath, - configDir: target.configDir, - ...(leaseOwnerPid !== null && leaseOwnerStartIdentity - ? { leaseOwnerPid, leaseOwnerStartIdentity } - : {}), - }); - if (!timerChild.send({ type: "authorize", processToken })) { - throw new Error("auto-restore timer authorization channel closed early"); - } - timerChild.disconnect(); - timerChild.unref(); - } catch (err) { - clearTimerMarker(sandboxName); - clearShieldsDownTransition(sandboxName, processToken); - cleanupRuntimePolicyFile(); - const message = err instanceof Error ? err.message : String(err); - console.error(` Cannot start auto-restore timer: ${message}`); - return failShieldsCommand(`Cannot start auto-restore timer: ${message}`, opts.throwOnError); - } + policyFile, + }); + } catch (error) { + cleanupRuntimePolicyFile(); + const message = error instanceof Error ? error.message : String(error); + console.error(` Cannot start auto-restore timer: ${message}`); + return failShieldsCommand(`Cannot start auto-restore timer: ${message}`, opts.throwOnError); } + let { transition } = timerStart; + const { timerAuthority, policyPathForApply } = timerStart; try { + if (transition && timerAuthority) { + assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "preparing"); + } saveShieldsState(sandboxName, { shieldsDown: true, shieldsDownAt: now, @@ -3905,17 +4834,51 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = }); } catch (error) { if (transition) { - clearShieldsDownTransition(sandboxName, transition.processToken); - killTimer(sandboxName); + const timerCancellation = killTimer(sandboxName); + if (timerCancellation.authorityRevoked) { + clearShieldsDownTransition(sandboxName, transition.processToken); + } } cleanupRuntimePolicyFile(); throw error; } + if (transition && timerAuthority) { + try { + assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "preparing"); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const rollback = rollbackShieldsDown( + sandboxName, + target, + snapshotPath, + initialMode, + state, + opts.allowLegacyHermesProtocol === true, + protocol, + ); + if (rollback.timerAuthorityRevoked) { + clearShieldsDownTransition(sandboxName, transition.processToken); + } + cleanupRuntimePolicyFile(); + console.error(` ERROR: ${message}`); + if (rollback.outcome === "mutable_default_restored") { + console.error( + " Timer handoff failed before policy mutation; original state was restored.", + ); + } else if (rollback.outcome === "lockdown_restored") { + console.error(" Timer handoff failed before policy mutation; lockdown was restored."); + } else { + console.error(" Timer handoff failed; manual recovery is required."); + } + return failShieldsCommand(message, opts.throwOnError); + } + } + console.log(` Applying ${policyName} policy...`); let policySetResult: ReturnType; try { - policySetResult = run(buildPolicySetCommand(policyFile, sandboxName), { + policySetResult = run(buildPolicySetCommand(policyPathForApply, sandboxName), { ignoreError: true, }); } finally { @@ -3965,8 +4928,10 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = console.error(" The scheduled auto-restore remains authoritative."); return failShieldsCommand(`Could not apply ${policyName} policy`, opts.throwOnError); } - if (transition) clearShieldsDownTransition(sandboxName, transition.processToken); - killTimer(sandboxName); + const timerCancellation = killTimer(sandboxName); + if (transition && timerCancellation.authorityRevoked) { + clearShieldsDownTransition(sandboxName, transition.processToken); + } console.error( ` ERROR: Could not apply the ${policyName} policy; the sandbox remains in the Shields up state.`, ); @@ -3980,6 +4945,9 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = console.log(` Unlocking ${target.agentName} config (${target.configPath})...`); let inferenceRouteConvergenceFailed = false; try { + if (transition && timerAuthority) { + assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "preparing"); + } unlockAgentConfig( sandboxName, target, @@ -4010,7 +4978,9 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = opts.allowLegacyHermesProtocol === true, protocol, ); - if (transition) clearShieldsDownTransition(sandboxName, transition.processToken); + if (transition && rollback.timerAuthorityRevoked) { + clearShieldsDownTransition(sandboxName, transition.processToken); + } console.error(` ERROR: ${message}`); const timerAuthority = describeRollbackTimerAuthority( transition !== null, @@ -4043,8 +5013,13 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = if (transition) { try { + if (!timerAuthority) { + throw new Error("Fresh Shields down lost its timer authorization proof"); + } + assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "preparing"); transition = { ...transition, phase: "active" }; writeShieldsDownTransition(transition, "preparing"); + assertFreshShieldsDownAuthority(sandboxName, timerAuthority, transition, "active"); } catch (err) { const message = err instanceof Error ? err.message : String(err); const rollback = rollbackShieldsDown( @@ -4056,7 +5031,9 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = opts.allowLegacyHermesProtocol === true, protocol, ); - clearShieldsDownTransition(sandboxName, transition.processToken); + if (rollback.timerAuthorityRevoked) { + clearShieldsDownTransition(sandboxName, transition.processToken); + } console.error(` ERROR: ${message}`); const timerAuthority = describeRollbackTimerAuthority(true, rollback.timerAuthorityRevoked); if (rollback.outcome === "mutable_default_restored") { @@ -4086,34 +5063,26 @@ function shieldsDownWithoutHostLock(sandboxName: string, opts: ShieldsDownOpts = }); // 6. Output - if (opts.skipTimer) { - console.log( - ` Config unlocked for ${sandboxName} (no auto-lockdown timer; caller will re-lock).`, - ); - } else { - const mins = Math.floor(timeoutSeconds / 60); - const secs = timeoutSeconds % 60; - console.log( - ` Config unlocked for ${sandboxName} (auto-lockdown in: ${mins}m${secs ? ` ${secs}s` : ""})`, - ); - console.log(""); - console.log(" Sandbox is in default (mutable) state."); - console.log(` Run \`nemoclaw ${sandboxName} shields up\` to opt into lockdown.`); - } + const mins = Math.floor(timeoutSeconds / 60); + const secs = timeoutSeconds % 60; + console.log( + ` Config unlocked for ${sandboxName} (auto-lockdown in: ${mins}m${secs ? ` ${secs}s` : ""})`, + ); + console.log(""); + console.log(" Sandbox is in default (mutable) state."); + console.log(` Run \`nemoclaw ${sandboxName} shields up\` to opt into lockdown.`); } 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; + const processToken = opts.processToken ?? randomBytes(16).toString("hex"); + const effectiveOpts = { ...opts, processToken }; try { - return withShieldsTransitionLock( + return withExpiredAutoRestoreDeadlineFence( sandboxName, "shields down", () => shieldsDownWithoutHostLock(sandboxName, effectiveOpts), - processToken ? { takeoverToken: processToken } : {}, + processToken, ); } catch (error) { return completeDeferredShieldsExit(error, opts.throwOnError === true); @@ -4134,6 +5103,7 @@ function shieldsUpWithoutHostLock( validateName(sandboxName, "sandbox name"); const state = loadShieldsState(sandboxName); + const recoveredProviderTarget = recoverActiveHermesRuntimeProviderMutation(sandboxName); if (state._isCorrupt) { console.error(" Shields state is corrupt; refusing to raise shields."); console.error( @@ -4151,7 +5121,15 @@ function shieldsUpWithoutHostLock( // host-root tamper has reverted protected perms or rewritten file // content (even when the mode/owner is restored), re-apply the lock // so the recovery hint surfaced by `shields status` actually works. - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const target = + recoveredProviderTarget ?? ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + if ( + !recoveredProviderTarget && + target.agentName === "hermes" && + inspectHermesShieldsProtocol(sandboxName, target) === "provider-state-mutation-v2" + ) { + runHermesProviderProtectionTransition(sandboxName, target, "locked", "locked"); + } const { issues } = verifyShieldsLockState(sandboxName, target, { verifyChattr: state.chattrApplied === true, verifyParentProtection: requiresProtectedSandboxParent(target), @@ -4241,11 +5219,9 @@ function shieldsUpWithoutHostLock( // 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, - ); + const protocol: HermesShieldsProtocol = recoveredProviderTarget + ? "provider-state-mutation-v2" + : 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 @@ -4294,12 +5270,11 @@ function shieldsUpWithoutHostLock( ); return failShieldsCommand("Saved policy snapshot is missing", opts.throwOnError); } - const target = ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); - const protocol = requireHermesShieldsProtocol( - sandboxName, - target, - opts.allowLegacyHermesProtocol === true, - ); + const target = + recoveredProviderTarget ?? ensureConfigHashSensitiveFile(resolveAgentConfig(sandboxName)); + const protocol: HermesShieldsProtocol = recoveredProviderTarget + ? "provider-state-mutation-v2" + : 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 @@ -4431,6 +5406,47 @@ type ShieldsStatusDeps = { verifyStateLockPlan?: (sandboxName: string, target: AgentConfigTarget) => string[]; }; +function verifyHermesProviderMutableStatus( + sandboxName: string, + mode: "mutable_default" | "temporarily_unlocked", + transition: ShieldsDownTransition | null, + resolveConfig: typeof resolveAgentConfig, +): void { + try { + const target = ensureConfigHashSensitiveFile(resolveConfig(sandboxName)); + if (target.agentName !== "hermes") return; + if (inspectHermesShieldsProtocol(sandboxName, target) !== "provider-state-mutation-v2") { + return; + } + + const marker = mode === "temporarily_unlocked" ? readTimerMarker(sandboxName) : null; + const assertTimedAuthority = () => { + if (mode !== "temporarily_unlocked") return; + if (!marker || !transition || transition.phase !== "active") { + throw new Error("Timed mutable status lost its exact active auto-restore authority"); + } + assertFreshShieldsDownAuthority(sandboxName, marker, transition, "active"); + }; + + assertTimedAuthority(); + runHermesProviderProtectionTransition(sandboxName, target, "mutable", "mutable"); + assertTimedAuthority(); + verifyHermesProviderMutablePosture(sandboxName, target); + assertTimedAuthority(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const declared = mode === "temporarily_unlocked" ? "DOWN" : "NOT CONFIGURED"; + console.error( + ` Shields: ${declared} (DRIFTED — declared mutable but runtime-provider verification failed)`, + ); + console.error(` Drift: ${message}`); + console.error( + ` Recovery: run \`nemoclaw ${sandboxName} shields up\` to reconcile and verify lockdown.`, + ); + throw new DeferredShieldsExit("Mutable shields state has runtime-provider drift", 2); + } +} + function shieldsStatusWithoutHostLock( sandboxName: string, allowInlineRecovery = true, @@ -4459,8 +5475,21 @@ function shieldsStatusWithoutHostLock( throw new DeferredShieldsExit("Shields down transition is incomplete", 1); } + const recoveredProviderTarget = recoverActiveHermesRuntimeProviderMutation(sandboxName); + if (recoveredProviderTarget && posture.mode !== "locked") { + console.error(" Shields: ERROR (runtime-provider recovery restored lockdown)"); + console.error( + ` Recovery: retry the intended Shields transition for ${sandboxName}; persisted posture was not accepted as clean.`, + ); + throw new DeferredShieldsExit( + "Recovered runtime-provider mutation conflicts with persisted mutable posture", + 2, + ); + } + switch (posture.mode) { case "mutable_default": + verifyHermesProviderMutableStatus(sandboxName, posture.mode, transition, resolveConfig); // NC-2227-02: Fresh sandbox with no shields history — do NOT claim locked console.log(` Shields: ${posture.statusText}`); console.log(" Config is mutable. Run `nemoclaw shields up` to opt into lockdown."); @@ -4473,7 +5502,15 @@ function shieldsStatusWithoutHostLock( let driftIssues: string[] = []; let planIssues: string[] = []; try { - const target = ensureConfigHashSensitiveFile(resolveConfig(sandboxName)); + const target = + recoveredProviderTarget ?? ensureConfigHashSensitiveFile(resolveConfig(sandboxName)); + if ( + !recoveredProviderTarget && + target.agentName === "hermes" && + inspectHermesShieldsProtocol(sandboxName, target) === "provider-state-mutation-v2" + ) { + runHermesProviderProtectionTransition(sandboxName, target, "locked", "locked"); + } try { planIssues = deps.verifyStateLockPlan ? deps.verifyStateLockPlan(sandboxName, target) @@ -4570,6 +5607,7 @@ function shieldsStatusWithoutHostLock( } case "temporarily_unlocked": { + verifyHermesProviderMutableStatus(sandboxName, posture.mode, transition, resolveConfig); const downSince = state.shieldsDownAt ? new Date(state.shieldsDownAt) : null; const elapsed = downSince ? Math.floor((Date.now() - downSince.getTime()) / 1000) : 0; const remaining = diff --git a/src/lib/shields/legacy-hermes-compat.test.ts b/src/lib/shields/legacy-hermes-compat.test.ts index 3bb761d6107..c1caf4269f4 100644 --- a/src/lib/shields/legacy-hermes-compat.test.ts +++ b/src/lib/shields/legacy-hermes-compat.test.ts @@ -7,6 +7,18 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; +import { + HERMES_PROVIDER_CAPABILITY_PATH as CAPABILITY_PATH, + createFailingCapabilityProbeResponse, + createHermesShieldsProviderConsumerHarness, + createRetainedUnlockSimulation, + createTimerAuthorizationSender, + createTransitionFailureForPosture, + hermesProviderConsumerSandbox as sandbox, + hermesProviderConsumerTarget as target, + writeBoundForwardPolicy, + writeTimerAuthorizationProof, +} from "../../../test/helpers/hermes-shields-provider-consumer-harness"; import { testTimeout } from "../../../test/helpers/timeouts"; @@ -14,8 +26,9 @@ 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 RUNTIME_STATE_MUTATION_CAPABILITY = + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json"; const LOCK_TOKEN = "a".repeat(64); -const SETUP_TIMEOUT_MS = 30_000; const OLD_GUARD_HELP = "usage: guard {ensure-api-key,refresh-hashes,provider-placeholders}"; const PARTIAL_GUARD_HELP = "begin-shields-transition --rollback-shields-mode"; const PREVIOUS_SEALED_GUARD_HELP = [ @@ -82,6 +95,90 @@ function isIsolatedInlinePython(cmd: string[]): boolean { return isInlinePython(cmd) && cmd[1] === "-I" && cmd[2] === "-c"; } +function isRuntimeStateMutationCapabilityProbe(cmd: string[]): boolean { + return ( + cmd[0] === HERMES_PYTHON && + cmd[1] === "-I" && + cmd[2] === "-c" && + cmd[3]?.includes("os.lstat") === true && + cmd.at(-1) === RUNTIME_STATE_MUTATION_CAPABILITY + ); +} + +type ForwardPolicyFailureSetup = (input: { + readonly forwardPolicyPath: string; + readonly routeSpy: MockInstance; + readonly timerPath: string; +}) => void; + +type ForwardPolicyFailureAssertion = (input: { + readonly routeSpy: MockInstance; + readonly runSpy: MockInstance; + readonly transitionPath: string; + readonly transitionSpy: MockInstance; +}) => void; + +function removeForwardPolicy({ + forwardPolicyPath, +}: Parameters[0]): void { + fs.rmSync(forwardPolicyPath); +} + +function tamperForwardPolicy({ + forwardPolicyPath, +}: Parameters[0]): void { + fs.writeFileSync(forwardPolicyPath, "tampered\n", { mode: 0o600 }); +} + +function replaceTimerDuringRoute({ + routeSpy, + timerPath, +}: Parameters[0]): void { + routeSpy.mockImplementation(() => { + const marker = JSON.parse(fs.readFileSync(timerPath, "utf-8")); + fs.writeFileSync( + timerPath, + JSON.stringify({ ...marker, timerProcessStartIdentity: "replacement-timer-start" }), + ); + return { ok: true, attempts: 1, httpStatus: 200 }; + }); +} + +function expectForwardPolicyRejectedBeforeMutation({ + routeSpy, + runSpy, + transitionSpy, +}: Parameters[0]): void { + expect(runSpy).not.toHaveBeenCalled(); + expect(transitionSpy).not.toHaveBeenCalled(); + expect(routeSpy).not.toHaveBeenCalled(); +} + +function expectTimerReplacementRejectedAfterMutation({ + routeSpy, + runSpy, + transitionPath, + transitionSpy, +}: Parameters[0]): void { + expect(runSpy).toHaveBeenCalled(); + expect(transitionSpy).toHaveBeenCalled(); + expect(routeSpy).toHaveBeenCalledTimes(1); + expect(fs.existsSync(transitionPath)).toBe(false); +} + +const forwardPolicyFailureFixtures: ReadonlyArray< + readonly [string, ForwardPolicyFailureSetup, RegExp, ForwardPolicyFailureAssertion] +> = [ + ["missing", removeForwardPolicy, /forward policy/u, expectForwardPolicyRejectedBeforeMutation], + ["tampered", tamperForwardPolicy, /forward policy/u, expectForwardPolicyRejectedBeforeMutation], + [ + "timer-replaced", + replaceTimerDuringRoute, + /auto-restore authority changed|timer generation/iu, + expectTimerReplacementRejectedAfterMutation, + ], +]; + describe("legacy Hermes shields compatibility", () => { let homeDir: string; let shields: ShieldsModule; @@ -103,6 +200,7 @@ describe("legacy Hermes shields compatibility", () => { const runner = requireSource("../runner.js"); const policy = requireSource("../policy/index.js"); const agentConfig = requireSource("../sandbox/agent-config.js"); + const registry = requireSource("../state/registry.js"); const privilegedExec = requireSource("../sandbox/privileged-exec.js"); const dockerExec = requireSource("../adapters/docker/exec.js"); const stateDirLock = requireSource("./state-dir-lock.js"); @@ -110,6 +208,16 @@ describe("legacy Hermes shields compatibility", () => { const audit = requireSource("./audit.js"); const permissiveRuntime = requireSource("./permissive-runtime.js"); const tempFiles = requireSource("../onboard/temp-files.js"); + const childProcess = requireSource("node:child_process"); + const timerControl = requireSource("./timer-control.js"); + const readProcessStartIdentity = timerControl.readProcessStartIdentity; + const isProcessAlive = timerControl.isProcessAlive; + const verifyTimerMarkerIdentity = timerControl.verifyTimerMarkerIdentity; + const fakeTimerPid = 4242; + const permissivePolicyPath = path.join(homeDir, "permissive.yaml"); + fs.writeFileSync(permissivePolicyPath, "version: 1\nnetwork_policies: {}\n", { + mode: 0o600, + }); runSpy = vi.spyOn(runner, "run").mockReturnValue({ status: 0 }); dockerExecSpy = vi.spyOn(dockerExec, "dockerExecFileSync"); @@ -141,8 +249,15 @@ describe("legacy Hermes shields compatibility", () => { String(name), ]), vi.spyOn(policy, "parseCurrentPolicy").mockImplementation((raw: unknown) => String(raw)), - vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue("/mock/permissive.yaml"), + vi.spyOn(policy, "resolvePermissivePolicyPath").mockReturnValue(permissivePolicyPath), vi.spyOn(agentConfig, "resolveAgentConfig").mockImplementation(() => hermesTarget()), + vi.spyOn(registry, "getSandbox").mockImplementation((name: unknown) => ({ + name: String(name), + agent: "hermes", + openshellDriver: "docker", + lifecycleGeneration: "legacy-generation", + workload: { kind: "managed-image" }, + })), privilegedExecArgvSpy, dockerExecSpy, applyStateDirLockModeSpy, @@ -158,10 +273,40 @@ describe("legacy Hermes shields compatibility", () => { vi.spyOn(console, "log").mockImplementation(() => undefined), vi.spyOn(console, "warn").mockImplementation(() => undefined), errorSpy, + vi + .spyOn(timerControl, "readProcessStartIdentity") + .mockImplementation((pidValue: unknown) => + Number(pidValue) === fakeTimerPid + ? "legacy-fake-timer-start" + : readProcessStartIdentity(Number(pidValue)), + ), + vi + .spyOn(timerControl, "isProcessAlive") + .mockImplementation((pidValue: unknown) => + Number(pidValue) === fakeTimerPid ? true : isProcessAlive(Number(pidValue)), + ), + vi + .spyOn(timerControl, "verifyTimerMarkerIdentity") + .mockImplementation((markerValue: unknown) => { + const marker = markerValue as import("./timer-control").TimerMarker; + return marker.pid === fakeTimerPid + ? { verified: true } + : verifyTimerMarkerIdentity(marker); + }), + vi.spyOn(childProcess, "fork").mockImplementation((_modulePath: unknown, args: unknown) => { + const sandboxName = String((args as unknown[])[0]); + return { + pid: fakeTimerPid, + disconnect: vi.fn(), + unref: vi.fn(), + kill: vi.fn(() => true), + send: vi.fn(createTimerAuthorizationSender(requireSource, sandboxName)), + }; + }), ); shields = requireSource(INDEX_MODULE); - }, testTimeout(SETUP_TIMEOUT_MS)); + }, testTimeout(60_000)); afterEach(() => { for (const spy of spies) spy.mockRestore(); @@ -180,6 +325,8 @@ describe("legacy Hermes shields compatibility", () => { let appliedMode: "locked" | "mutable" = "mutable"; dockerExecSpy.mockImplementation((cmd: string[]) => { switch (true) { + case isRuntimeStateMutationCapabilityProbe(cmd): + return "absent"; case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): return help; case isGuardAction(cmd, "begin-shields-transition"): { @@ -225,7 +372,6 @@ describe("legacy Hermes shields compatibility", () => { expect(() => shields.shieldsDown("legacy-hermes", { - skipTimer: true, throwOnError: true, }), ).toThrow(/predates sealed shields transitions|rebuild/i); @@ -273,7 +419,6 @@ describe("legacy Hermes shields compatibility", () => { expect(() => shields.shieldsDown("partial-hermes", { - skipTimer: true, throwOnError: true, }), ).toThrow(/predates sealed shields transitions|incomplete|rebuild/i); @@ -432,7 +577,6 @@ describe("legacy Hermes shields compatibility", () => { expect(() => shields.shieldsDown("current-hermes", { - skipTimer: true, throwOnError: true, }), ).not.toThrow(); @@ -456,7 +600,6 @@ describe("legacy Hermes shields compatibility", () => { expect(() => shields.shieldsDown("current-hermes", { - skipTimer: true, throwOnError: true, }), ).toThrow( @@ -482,6 +625,8 @@ describe("legacy Hermes shields compatibility", () => { it("descriptor-safely protects and verifies the sandbox parent when a failed rebuild relocks an old image", () => { dockerExecSpy.mockImplementation((cmd: string[]) => { switch (true) { + case isRuntimeStateMutationCapabilityProbe(cmd): + return "absent"; case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): return OLD_GUARD_HELP; case cmd[0] === "stat": @@ -522,6 +667,8 @@ describe("legacy Hermes shields compatibility", () => { it("refuses to report a legacy relock when sandbox parent protection did not hold", () => { dockerExecSpy.mockImplementation((cmd: string[]) => { switch (true) { + case isRuntimeStateMutationCapabilityProbe(cmd): + return "absent"; case cmd.includes(HERMES_GUARD) && cmd.includes("--help"): return OLD_GUARD_HELP; case cmd[0] === "stat": @@ -545,14 +692,12 @@ describe("legacy Hermes shields compatibility", () => { }); 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 ""; - } - }); + dockerExecSpy.mockImplementation( + createFailingCapabilityProbeResponse( + isRuntimeStateMutationCapabilityProbe, + new Error("temporary Docker exec failure"), + ), + ); expect(() => shields.unlockAgentConfig("unreachable-hermes", hermesTarget(), true, true), @@ -560,6 +705,753 @@ describe("legacy Hermes shields compatibility", () => { const commands = dockerExecSpy.mock.calls.map(commandFromCall); expect(commands.some(isInlinePython)).toBe(false); + expect(commands.some((cmd) => cmd.includes(HERMES_GUARD) && cmd.includes("--help"))).toBe( + false, + ); expect(applyStateDirLockModeSpy).not.toHaveBeenCalled(); }); }); + +{ + describe("Hermes Shields runtime-provider consumer", () => { + let harness: ReturnType; + let spies: MockInstance[]; + let transitionSpy: MockInstance; + let runSpy: MockInstance; + let supportSpy: MockInstance; + let lifecycleGateSpy: MockInstance; + let dockerExecSpy: MockInstance; + let registrySpy: MockInstance; + let verifyLockSpy: MockInstance; + let routeSpy: MockInstance; + let auditSpy: MockInstance; + let commands: string[][]; + let capabilityProbe: { error: Error | null; presence: string }; + let shields: typeof import("./index"); + + beforeEach(() => { + harness = createHermesShieldsProviderConsumerHarness(requireSource); + ({ + auditSpy, + capabilityProbe, + commands, + dockerExecSpy, + lifecycleGateSpy, + registrySpy, + routeSpy, + runSpy, + shields, + spies, + supportSpy, + transitionSpy, + verifyLockSpy, + } = harness); + }); + + afterEach(() => { + harness.cleanup(); + }); + + it("migrates the current managed Hermes unlock leaf to the provider transaction", () => { + shields.unlockAgentConfig(sandbox.name, target, true, false); + + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandbox, + sandboxName: sandbox.name, + configTarget: target, + target: "mutable", + rollback: "locked", + }), + ); + expect(commands.some((command) => command.includes("begin-shields-transition"))).toBe(false); + expect(commands.some((command) => command.includes("run-state-dir-transition"))).toBe(false); + }); + + it("treats a fresh mutable-default provider unlock as recovery plus live verification", () => { + shields.unlockAgentConfig(sandbox.name, target, false, false); + + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandbox, + sandboxName: sandbox.name, + configTarget: target, + target: "mutable", + rollback: "mutable", + }), + ); + expect(transitionSpy).toHaveBeenCalledTimes(1); + expect(commands.some((command) => command.includes("begin-shields-transition"))).toBe(false); + }); + + it("migrates the current managed Hermes lock leaf and preserves the host seal result", () => { + const result = shields.lockAgentConfig(sandbox.name, target, false, false); + + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandbox, + sandboxName: sandbox.name, + configTarget: target, + target: "locked", + rollback: "mutable", + }), + ); + expect(result.fileHashes).toEqual({ + "/sandbox/.hermes/config.yaml": "c".repeat(64), + "/sandbox/.hermes/.env": "c".repeat(64), + "/sandbox/.hermes/.config-hash": "c".repeat(64), + }); + expect(commands.some((command) => command.includes("begin-shields-transition"))).toBe(false); + }); + + it("treats an already-locked provider lock as recovery plus live verification", () => { + const result = shields.lockAgentConfig(sandbox.name, target, true, false); + + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandbox, + sandboxName: sandbox.name, + configTarget: target, + target: "locked", + rollback: "locked", + }), + ); + expect(transitionSpy).toHaveBeenCalledTimes(1); + expect(result.fileHashes).toEqual({ + "/sandbox/.hermes/config.yaml": "c".repeat(64), + "/sandbox/.hermes/.env": "c".repeat(64), + "/sandbox/.hermes/.config-hash": "c".repeat(64), + }); + }); + + it("completes a timed retained unlock once and leaves its retry side effects idempotent", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + const processToken = "d".repeat(32); + const snapshotPath = path.join(stateDir, "shields-policy-before-provider-crash.yaml"); + const timerPath = path.join(stateDir, `shields-timer-${sandbox.name}.json`); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandbox.name}-${processToken}.json`, + ); + fs.mkdirSync(path.join(stateDir, "runtime-provider-lifecycle"), { + recursive: true, + mode: 0o700, + }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n restrictive: {}\n"); + const forwardPolicy = writeBoundForwardPolicy(stateDir, sandbox.name, processToken); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: "2026-08-09T00:00:00.000Z", + shieldsDownTimeout: 300, + shieldsDownReason: "crash retry", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + fs.writeFileSync( + timerPath, + JSON.stringify({ + pid: 4242, + sandboxName: sandbox.name, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + timerProcessStartIdentity: "live-timer-start", + allowLegacyHermesProtocol: false, + agentName: "hermes", + configPath: target.configPath, + configDir: target.configDir, + }), + ); + writeTimerAuthorizationProof(requireSource, sandbox.name); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "preparing", + ownerPid: 4242, + ownerStartIdentity: "dead-provider-owner", + processToken, + sandboxName: sandbox.name, + snapshotPath, + forwardPolicy, + }), + ); + const events: string[] = []; + const simulation = createRetainedUnlockSimulation(events, commands); + runSpy.mockImplementation(simulation.run); + lifecycleGateSpy.mockImplementation(simulation.hasActiveClaim); + transitionSpy.mockImplementation(simulation.transition); + dockerExecSpy.mockImplementation(simulation.dockerExec); + routeSpy.mockImplementation(() => { + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("preparing"); + events.push("route"); + return { ok: true, attempts: 1, httpStatus: 200 }; + }); + auditSpy.mockImplementation(() => { + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("active"); + events.push("audit"); + }); + + shields.shieldsDown(sandbox.name, { throwOnError: true }); + + expect( + transitionSpy.mock.calls.map(([input]) => ({ + target: (input as { target: string }).target, + rollback: (input as { rollback: string }).rollback, + })), + ).toEqual([ + { target: "locked", rollback: "locked" }, + { target: "mutable", rollback: "mutable" }, + { target: "mutable", rollback: "locked" }, + ]); + expect(simulation.livePosture()).toBe("mutable"); + expect(simulation.activeClaim()).toBe(false); + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("active"); + expect( + JSON.parse(fs.readFileSync(path.join(stateDir, `shields-${sandbox.name}.json`), "utf-8")), + ).toMatchObject({ shieldsDown: true, shieldsPolicySnapshotPath: snapshotPath }); + expect(events.indexOf("provider:mutable/locked")).toBeLessThan( + events.indexOf("verified-mutable"), + ); + expect(events.indexOf("policy")).toBeLessThan(events.indexOf("provider:locked/locked")); + expect(events.indexOf("verified-mutable")).toBeLessThan(events.indexOf("route")); + expect(events.indexOf("route")).toBeLessThan(events.indexOf("audit")); + expect(routeSpy).toHaveBeenCalledTimes(1); + expect(auditSpy).toHaveBeenCalledWith({ + action: "shields_down", + sandbox: sandbox.name, + timestamp: "2026-08-09T00:00:00.000Z", + timeout_seconds: 300, + reason: "crash retry", + policy_applied: "permissive", + policy_snapshot: snapshotPath, + }); + expect(auditSpy).toHaveBeenCalledTimes(1); + expect(transitionSpy.mock.invocationCallOrder[0]).toBeLessThan( + dockerExecSpy.mock.invocationCallOrder[0] as number, + ); + expect(commands.some((command) => command.includes(CAPABILITY_PATH))).toBe(false); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + + expect(() => shields.shieldsDown(sandbox.name, { throwOnError: true })).toThrow( + /already unlocked/u, + ); + expect(routeSpy).toHaveBeenCalledTimes(1); + expect(auditSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("active"); + }); + + it("completes timed DOWN bookkeeping after provider release removed the durable claim", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + const processToken = "e".repeat(32); + const snapshotPath = path.join(stateDir, "shields-policy-after-provider-release.yaml"); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandbox.name}-${processToken}.json`, + ); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n restrictive: {}\n"); + const forwardPolicy = writeBoundForwardPolicy(stateDir, sandbox.name, processToken); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: "2026-08-09T00:05:00.000Z", + shieldsDownTimeout: 300, + shieldsDownReason: "post-release crash", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + fs.writeFileSync( + path.join(stateDir, `shields-timer-${sandbox.name}.json`), + JSON.stringify({ + pid: 4343, + sandboxName: sandbox.name, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + timerProcessStartIdentity: "live-timer-start", + allowLegacyHermesProtocol: false, + agentName: "hermes", + configPath: target.configPath, + configDir: target.configDir, + }), + ); + writeTimerAuthorizationProof(requireSource, sandbox.name); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "preparing", + ownerPid: 4343, + ownerStartIdentity: "dead-post-release-owner", + processToken, + sandboxName: sandbox.name, + snapshotPath, + forwardPolicy, + }), + ); + lifecycleGateSpy.mockReturnValue(false); + transitionSpy.mockReturnValue(null); + routeSpy.mockImplementation(() => { + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("preparing"); + return { ok: true, attempts: 1, httpStatus: 200 }; + }); + auditSpy.mockImplementation(() => { + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("active"); + }); + + shields.shieldsDown(sandbox.name, { throwOnError: true }); + + expect(supportSpy).toHaveBeenCalledTimes(1); + expect(transitionSpy).toHaveBeenCalledTimes(1); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "mutable", rollback: "mutable" }), + ); + expect(routeSpy).toHaveBeenCalledTimes(1); + expect(auditSpy).toHaveBeenCalledWith({ + action: "shields_down", + sandbox: sandbox.name, + timestamp: "2026-08-09T00:05:00.000Z", + timeout_seconds: 300, + reason: "post-release crash", + policy_applied: "permissive", + policy_snapshot: snapshotPath, + }); + expect(JSON.parse(fs.readFileSync(transitionPath, "utf-8")).phase).toBe("active"); + }); + + it.each( + forwardPolicyFailureFixtures, + )("fails closed when the recovered forward policy is %s", (_failureMode, arrangeFailure, expectedError, assertSideEffects) => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + const processToken = "f".repeat(32); + const snapshotPath = path.join(stateDir, "shields-policy-invalid-forward.yaml"); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandbox.name}-${processToken}.json`, + ); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n restrictive: {}\n"); + const forwardPolicy = writeBoundForwardPolicy(stateDir, sandbox.name, processToken); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date().toISOString(), + shieldsDownTimeout: 300, + shieldsDownReason: "invalid forward policy", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + const timerPath = path.join(stateDir, `shields-timer-${sandbox.name}.json`); + fs.writeFileSync( + timerPath, + JSON.stringify({ + pid: 4444, + sandboxName: sandbox.name, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + timerProcessStartIdentity: "live-timer-start", + allowLegacyHermesProtocol: false, + agentName: "hermes", + configPath: target.configPath, + configDir: target.configDir, + }), + ); + writeTimerAuthorizationProof(requireSource, sandbox.name); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "preparing", + ownerPid: 4444, + ownerStartIdentity: "dead-forward-owner", + processToken, + sandboxName: sandbox.name, + snapshotPath, + forwardPolicy, + }), + ); + arrangeFailure({ forwardPolicyPath: forwardPolicy.path, routeSpy, timerPath }); + lifecycleGateSpy.mockReturnValue(false); + + expect(() => shields.shieldsDown(sandbox.name, { throwOnError: true })).toThrow( + expectedError, + ); + assertSideEffects({ routeSpy, runSpy, transitionPath, transitionSpy }); + expect(auditSpy).not.toHaveBeenCalled(); + }); + + it("recovers a retained lock before verifying an already-UP Shields record", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + fs.mkdirSync(path.join(stateDir, "runtime-provider-lifecycle"), { + recursive: true, + mode: 0o700, + }); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: false, + chattrApplied: true, + fileHashes: { [target.configPath]: "c".repeat(64) }, + }), + ); + let activeClaim = true; + lifecycleGateSpy.mockImplementation(() => activeClaim); + transitionSpy.mockImplementation(() => { + activeClaim = false; + return { fence: {}, proof: {} }; + }); + verifyLockSpy.mockImplementation( + ( + _sandboxName: string, + _target: unknown, + options: { exec: (command: string[]) => string }, + ) => { + options.exec(["stat", "-c", "%a %U:%G", target.configPath]); + return { issues: [] }; + }, + ); + + shields.shieldsUp(sandbox.name, { throwOnError: true }); + + expect(transitionSpy).toHaveBeenCalledTimes(1); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "locked", rollback: "locked" }), + ); + expect(activeClaim).toBe(false); + expect(transitionSpy.mock.invocationCallOrder[0]).toBeLessThan( + verifyLockSpy.mock.invocationCallOrder[0] as number, + ); + expect(transitionSpy.mock.invocationCallOrder[0]).toBeLessThan( + dockerExecSpy.mock.invocationCallOrder[0] as number, + ); + expect(commands.some((command) => command.includes(CAPABILITY_PATH))).toBe(false); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("does not report clean UP when provider verification finds nested skills or pairing drift", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: false, + chattrApplied: true, + fileHashes: { [target.configPath]: "c".repeat(64) }, + updatedAt: new Date().toISOString(), + }), + ); + lifecycleGateSpy.mockReturnValue(false); + transitionSpy.mockImplementation( + createTransitionFailureForPosture( + "locked", + "recursive state lock plan drift under skills/pairing", + ), + ); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as never); + spies.push(exitSpy); + + expect(() => shields.shieldsStatus(sandbox.name)).toThrow("process exit 2"); + + const errors = vi.mocked(console.error).mock.calls.flat().map(String).join("\n"); + const logs = vi.mocked(console.log).mock.calls.flat().map(String).join("\n"); + expect(errors).toContain("recursive state lock plan drift under skills/pairing"); + expect(errors).toContain("UP (DRIFTED"); + expect(logs).not.toContain("UP (lockdown active)"); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "locked", rollback: "locked" }), + ); + + transitionSpy.mockClear(); + vi.mocked(console.log).mockClear(); + expect(() => shields.shieldsUp(sandbox.name, { throwOnError: true })).toThrow( + "recursive state lock plan drift under skills/pairing", + ); + expect(vi.mocked(console.log).mock.calls.flat().map(String).join("\n")).not.toContain( + "already locked", + ); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "locked", rollback: "locked" }), + ); + + transitionSpy.mockClear(); + expect(() => shields.lockAgentConfig(sandbox.name, target, true, false)).toThrow( + "recursive state lock plan drift under skills/pairing", + ); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "locked", rollback: "locked" }), + ); + }); + + it("does not report clean mutable-default when provider verification finds nested skills or pairing drift", () => { + lifecycleGateSpy.mockReturnValue(false); + transitionSpy.mockImplementation( + createTransitionFailureForPosture( + "mutable", + "recursive mutable state drift under skills/pairing", + ), + ); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as never); + spies.push(exitSpy); + + expect(() => shields.shieldsStatus(sandbox.name)).toThrow("process exit 2"); + + const errors = vi.mocked(console.error).mock.calls.flat().map(String).join("\n"); + const logs = vi.mocked(console.log).mock.calls.flat().map(String).join("\n"); + expect(errors).toContain("recursive mutable state drift under skills/pairing"); + expect(errors).toContain("NOT CONFIGURED (DRIFTED"); + expect(logs).not.toContain("NOT CONFIGURED (default mutable state)"); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "mutable", rollback: "mutable" }), + ); + }); + + it("does not report clean timed DOWN on recursive drift or timer loss during verification", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const stateDir = statePaths.resolveNemoclawStateDir(); + const processToken = "e".repeat(32); + const snapshotPath = path.join(stateDir, "shields-policy-timed-status.yaml"); + const timerPath = path.join(stateDir, `shields-timer-${sandbox.name}.json`); + const transitionPath = path.join( + stateDir, + `shields-transition-${sandbox.name}-${processToken}.json`, + ); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync(snapshotPath, "version: 1\nnetwork_policies:\n restrictive: {}\n"); + const forwardPolicy = writeBoundForwardPolicy(stateDir, sandbox.name, processToken); + fs.writeFileSync( + path.join(stateDir, `shields-${sandbox.name}.json`), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date().toISOString(), + shieldsDownTimeout: 300, + shieldsDownReason: "timed mutable status", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + updatedAt: new Date().toISOString(), + }), + ); + fs.writeFileSync( + timerPath, + JSON.stringify({ + pid: 4444, + sandboxName: sandbox.name, + snapshotPath, + restoreAt: new Date(Date.now() + 60_000).toISOString(), + processToken, + timerProcessStartIdentity: "live-timer-start", + allowLegacyHermesProtocol: false, + agentName: "hermes", + configPath: target.configPath, + configDir: target.configDir, + }), + ); + writeTimerAuthorizationProof(requireSource, sandbox.name); + fs.writeFileSync( + transitionPath, + JSON.stringify({ + version: 1, + phase: "active", + ownerPid: 4444, + ownerStartIdentity: "timed-status-owner", + processToken, + sandboxName: sandbox.name, + snapshotPath, + managedMcpPolicyKeys: [], + forwardPolicy, + }), + ); + lifecycleGateSpy.mockReturnValue(false); + transitionSpy.mockImplementation( + createTransitionFailureForPosture( + "mutable", + "recursive timed state drift under skills/pairing", + ), + ); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process exit ${String(code)}`); + }) as never); + spies.push(exitSpy); + + expect(() => shields.shieldsStatus(sandbox.name)).toThrow("process exit 2"); + + const errors = vi.mocked(console.error).mock.calls.flat().map(String).join("\n"); + const logs = vi.mocked(console.log).mock.calls.flat().map(String).join("\n"); + expect(errors).toContain("recursive timed state drift under skills/pairing"); + expect(errors).toContain("DOWN (DRIFTED"); + expect(logs).not.toContain("DOWN (temporarily unlocked)"); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "mutable", rollback: "mutable" }), + ); + expect(fs.existsSync(timerPath)).toBe(true); + expect(fs.existsSync(transitionPath)).toBe(true); + + const timerControl = requireSource("./timer-control.js") as typeof import("./timer-control"); + transitionSpy.mockClear(); + vi.mocked(console.error).mockClear(); + vi.mocked(console.log).mockClear(); + transitionSpy.mockImplementation(() => { + fs.rmSync(timerControl.timerAuthorizationProofPath(sandbox.name, processToken)); + return { fence: {}, proof: {} }; + }); + + expect(() => shields.shieldsStatus(sandbox.name)).toThrow("process exit 2"); + + const timerLossErrors = vi.mocked(console.error).mock.calls.flat().map(String).join("\n"); + const timerLossLogs = vi.mocked(console.log).mock.calls.flat().map(String).join("\n"); + expect(timerLossErrors).toContain("exact live future auto-restore timer authority"); + expect(timerLossErrors).toContain("DOWN (DRIFTED"); + expect(timerLossLogs).not.toContain("DOWN (temporarily unlocked)"); + expect(transitionSpy).toHaveBeenCalledWith( + expect.objectContaining({ target: "mutable", rollback: "mutable" }), + ); + }); + + it("falls back to the sealed-plan protocol only after proving capability absence", () => { + capabilityProbe.presence = "absent"; + + expect(shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toBe(true); + + expect(supportSpy).not.toHaveBeenCalled(); + expect(commands.some((command) => command.includes("--help"))).toBe(true); + }); + + it("keeps non-managed Docker Hermes sandboxes on their sealed-plan protocol", () => { + registrySpy.mockReturnValue({ ...sandbox, workload: undefined }); + + expect(shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toBe(true); + + expect( + commands.some( + (command) => + command.includes("-c") && command.some((entry) => entry.includes("os.lstat")), + ), + ).toBe(false); + expect(supportSpy).not.toHaveBeenCalled(); + expect(commands.some((command) => command.includes("--help"))).toBe(true); + }); + + it("keeps an explicit custom Dockerfile Hermes sandbox on its sealed-plan protocol", () => { + registrySpy.mockReturnValue({ + ...sandbox, + workload: { + schemaVersion: 1, + kind: "legacy-dockerfile", + reference: null, + shared: false, + }, + }); + + expect(shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toBe(true); + + expect( + commands.some( + (command) => + command.includes("-c") && command.some((entry) => entry.includes("os.lstat")), + ), + ).toBe(false); + expect(supportSpy).not.toHaveBeenCalled(); + expect(commands.some((command) => command.includes("--help"))).toBe(true); + }); + + it("fails closed when a present capability is invalid", () => { + supportSpy.mockReturnValue(false); + + expect(() => shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toThrow( + /capability is present but invalid or unsupported/u, + ); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("fails closed when the capability presence probe cannot inspect the image", () => { + capabilityProbe.error = new Error("permission denied while inspecting capability"); + + expect(() => shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toThrow( + /permission denied while inspecting capability/u, + ); + expect(supportSpy).not.toHaveBeenCalled(); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("fails closed when provider selection fails for a present capability", () => { + supportSpy.mockImplementation(() => { + throw new Error("runtime provider registry unavailable"); + }); + + expect(() => shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toThrow( + /runtime provider registry unavailable/u, + ); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("fails closed when a present lifecycle ledger cannot be validated", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const lifecyclePath = path.join( + statePaths.resolveNemoclawStateDir(), + "runtime-provider-lifecycle", + ); + fs.mkdirSync(path.dirname(lifecyclePath), { recursive: true }); + fs.symlinkSync(`${lifecyclePath}.missing`, lifecyclePath); + + expect(() => shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toThrow(); + expect( + commands.some( + (command) => + command.includes("-c") && command.some((entry) => entry.includes("os.lstat")), + ), + ).toBe(false); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("does not reinterpret a lifecycle scan failure as ledger absence", () => { + const statePaths = requireSource("../state/paths.js") as typeof import("../state/paths"); + const lifecyclePath = path.join( + statePaths.resolveNemoclawStateDir(), + "runtime-provider-lifecycle", + ); + fs.mkdirSync(lifecyclePath, { recursive: true, mode: 0o700 }); + lifecycleGateSpy.mockImplementation(() => { + throw Object.assign(new Error("claim disappeared during stable ledger inspection"), { + code: "ENOENT", + }); + }); + + expect(() => shields.supportsHermesSealedShieldsTransactions(sandbox.name)).toThrow( + /claim disappeared during stable ledger inspection/u, + ); + expect( + commands.some( + (command) => + command.includes("-c") && command.some((entry) => entry.includes("os.lstat")), + ), + ).toBe(false); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + + it("fails closed when managed Docker registry lifecycle authority is incomplete", () => { + registrySpy.mockReturnValue({ ...sandbox, lifecycleGeneration: undefined }); + + expect(() => shields.lockAgentConfig(sandbox.name, target, false, false)).toThrow( + /registry authority has no lifecycle generation/u, + ); + expect(commands.some((command) => command.includes("--help"))).toBe(false); + }); + }); +} diff --git a/src/lib/shields/mutable-config-repair.ts b/src/lib/shields/mutable-config-repair.ts index 4494b496a1f..ca7530aee2f 100644 --- a/src/lib/shields/mutable-config-repair.ts +++ b/src/lib/shields/mutable-config-repair.ts @@ -14,25 +14,36 @@ const MUTABLE_CONFIG_NORMALIZER_WATCHDOG = [ ] as const; function runPrivileged(sandboxName: string, cmd: string[], timeout = 15000): void { - dockerExec.dockerExecFileSync( - privilegedExecModule.privilegedSandboxExecArgv(sandboxName, cmd, false, true), - { - stdio: ["ignore", "pipe", "pipe"], - timeout, + privilegedExecModule.withPrivilegedSandboxExecutionLease( + sandboxName, + "mutable config permission repair", + () => { + dockerExec.dockerExecFileSync( + privilegedExecModule.privilegedSandboxExecArgv(sandboxName, cmd, false, true), + { + stdio: ["ignore", "pipe", "pipe"], + timeout, + }, + ); }, ); } function privilegedExecCapture(sandboxName: string, cmd: string[], timeout = 15000): string { - return dockerExec - .dockerExecFileSync( - privilegedExecModule.privilegedSandboxExecArgv(sandboxName, cmd, false, true), - { - stdio: ["ignore", "pipe", "pipe"], - timeout, - }, - ) - .trim(); + return privilegedExecModule.withPrivilegedSandboxExecutionLease( + sandboxName, + "mutable config identity lookup", + () => + dockerExec + .dockerExecFileSync( + privilegedExecModule.privilegedSandboxExecArgv(sandboxName, cmd, false, true), + { + stdio: ["ignore", "pipe", "pipe"], + timeout, + }, + ) + .trim(), + ); } function sandboxIdentityId(sandboxName: string, flag: "-u" | "-g"): string { diff --git a/src/lib/shields/openclaw-transition.test.ts b/src/lib/shields/openclaw-transition.test.ts index b8df96593a3..25fdf1bb168 100644 --- a/src/lib/shields/openclaw-transition.test.ts +++ b/src/lib/shields/openclaw-transition.test.ts @@ -7,6 +7,10 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; +import { + createShieldsFlowHarness, + type ShieldsFlowHarnessOptions, +} from "../../../test/helpers/shields-flow-harness"; const requireSource = createRequire(import.meta.url); const INDEX_MODULE = "./index.js"; @@ -358,3 +362,408 @@ describe("OpenClaw shields top-config transaction", () => { expect(restoreStateSpy).not.toHaveBeenCalled(); }); }); + +describe("OpenClaw shields flow rollback and recovery", () => { + let tmpDir: string; + + function createHarness(options: ShieldsFlowHarnessOptions = {}) { + return createShieldsFlowHarness(requireSource, tmpDir, options); + } + + function expectStagedDriverNeutralRecovery( + errorSpy: MockInstance, + sandboxName: string, + cliName = "nemoclaw", + ): string { + const output = errorSpy.mock.calls.flat().map(String).join("\n"); + expect(output).toContain( + `Recovery: confirm the sandbox is running and ready, then retry \`${cliName} ${sandboxName} shields up\`.`, + ); + expect(output).toContain( + `If the retry still fails, rebuild a known-good baseline with \`${cliName} ${sandboxName} rebuild --yes\`.`, + ); + expect(output).not.toMatch(/kubectl/i); + return output; + } + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "shields-openclaw-recovery-")); + vi.stubEnv("HOME", tmpDir); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + delete require.cache[requireSource.resolve(INDEX_MODULE)]; + delete require.cache[requireSource.resolve("./timer-bound-lock.js")]; + delete require.cache[requireSource.resolve("./transition-lock.js")]; + delete require.cache[requireSource.resolve("./permissive-runtime.js")]; + delete require.cache[requireSource.resolve("../actions/sandbox/mcp-bridge-policy.js")]; + delete require.cache[requireSource.resolve("../cli/branding.js")]; + }); + + it("shields down removes the permissive runtime temp directory when the auto-restore timer fails (#7964)", () => { + const mkdtempSpy = vi.spyOn(fs, "mkdtempSync"); + // shieldsDown builds the temp policy before it forks the auto-restore timer, + // so the fork mock observes the runtime-policy directory mid-transition. That + // proves the test exercises real temp-policy creation, not only the absence + // of a leak. + let runtimeDirDuringFork: string | undefined; + let runtimeDirExistedDuringFork = false; + // A real `openshell policy get --base` carries filesystem_policy paths, so the + // permissive merge writes a temp policy file instead of returning the static + // base path. That is the state that makes the leak reachable. + const harness = createHarness({ + livePolicyYaml: + "version: 1\nfilesystem_policy:\n read_write:\n - /proc\n read_only:\n - /opt/hermes\n", + fork: () => { + runtimeDirDuringFork = mkdtempSpy.mock.results + .filter((result) => result.type === "return") + .map((result) => String(result.value)) + .find((directory) => path.basename(directory).startsWith("nemoclaw-permissive-runtime-")); + runtimeDirExistedDuringFork = + runtimeDirDuringFork !== undefined && fs.existsSync(runtimeDirDuringFork); + return { + pid: 0, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => true), + kill: vi.fn(() => true), + }; + }, + }); + + expect(() => + harness.shieldsDown("openclaw", { + timeout: "5m", + reason: "temp cleanup coverage", + throwOnError: true, + }), + ).toThrow("Cannot start auto-restore timer"); + // One runtime-policy directory existed during the transition, and none + // remains after the failed shields down. + expect(runtimeDirExistedDuringFork).toBe(true); + expect(runtimeDirDuringFork).toBeDefined(); + expect(fs.existsSync(runtimeDirDuringFork!)).toBe(false); + }); + + it.skipIf(process.platform === "win32")( + "atomically replaces a timer marker symlink without modifying its target", + () => { + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const markerPath = path.join(stateDir, "shields-timer-openclaw.json"); + const markerTargetPath = path.join(stateDir, "operator-owned-marker.json"); + const markerTarget = "operator-owned marker contents"; + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync(markerTargetPath, markerTarget); + const originalRename = fs.renameSync.bind(fs); + const plantMarkerSymlink = () => fs.symlinkSync(markerTargetPath, markerPath); + const publicationRoutes = new Map void>([[markerPath, plantMarkerSymlink]]); + const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => { + (publicationRoutes.get(String(destination)) ?? (() => undefined))(); + originalRename(source, destination); + }); + const harness = createHarness({ + fork: () => ({ + pid: 4242, + disconnect: vi.fn(), + unref: vi.fn(), + send: vi.fn(() => true), + kill: vi.fn(() => true), + }), + }); + + harness.shieldsDown("openclaw", { + timeout: "5m", + reason: "marker publication coverage", + throwOnError: true, + }); + + expect(renameSpy).toHaveBeenCalledWith(expect.stringContaining(".tmp"), markerPath); + const markerFd = fs.openSync(markerPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + expect(fs.fstatSync(markerFd).isFile()).toBe(true); + expect(JSON.parse(fs.readFileSync(markerFd, "utf-8"))).toMatchObject({ + pid: 4242, + sandboxName: "openclaw", + }); + } finally { + fs.closeSync(markerFd); + } + expect(fs.readFileSync(markerTargetPath, "utf-8")).toBe(markerTarget); + }, + ); + + 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"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync( + path.join(stateDir, "shields-openclaw.json"), + JSON.stringify({ + shieldsDown: true, + shieldsDownAt: new Date(Date.now() - 120_000).toISOString(), + shieldsDownTimeout: 300, + shieldsDownReason: "coverage", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: path.join(stateDir, "missing-snapshot.yaml"), + }), + ); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + "Saved policy snapshot is missing", + ); + }); + + it("reports staged driver-neutral recovery when shields-down rollback cannot re-lock (#6126)", () => { + const harness = createHarness({ failOpenClawGuardActions: ["unlock", "lock"] }); + + expect(() => + harness.shieldsDown("openclaw", { + timeout: "5m", + reason: "recovery-hint coverage", + throwOnError: true, + }), + ).toThrow(/startup-not-ready/); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); + expect(output).toContain("Rolling back — restoring policy from snapshot"); + expect(output).toContain("Config remains unlocked — manual intervention required"); + }); + + it("keeps the host attached beyond failed-startup recovery's container timeout (#8304)", () => { + const harness = createHarness({ failOpenClawGuardActions: ["preflight"] }); + + expect(() => + harness.shieldsDown("openclaw", { + timeout: "5m", + reason: "failed-startup timeout coverage", + throwOnError: true, + }), + ).not.toThrow(); + + const recovery = harness.dockerSpawnCalls.find(({ args }) => + args.includes("unlock-failed-startup"), + ); + expect(recovery?.args).toEqual( + expect.arrayContaining(["timeout", "--kill-after=5s", "25m", "unlock-failed-startup"]), + ); + expect(recovery?.timeout).toBe(26 * 60 * 1000); + }); + + it("reports staged driver-neutral recovery when snapshot restoration fails (#6126)", () => { + const harness = createHarness({ run: () => ({ status: 1 }) }); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + const snapshotPath = path.join(stateDir, "policy-snapshot-failed-restore.yaml"); + 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: 300, + shieldsDownReason: "recovery-hint coverage", + shieldsDownPolicy: "permissive", + shieldsPolicySnapshotPath: snapshotPath, + }), + ); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + "policy restore exited with status 1", + ); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); + expect(output).toContain("Config remains unlocked — manual intervention required"); + }); + + it("reports staged driver-neutral recovery when the initial config lock fails (#6126)", () => { + const harness = createHarness({ failOpenClawGuardActions: ["lock"] }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /startup-not-ready/, + ); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); + expect(output).toContain( + "Warning: OpenClaw lock rollback could not restore the trusted posture", + ); + expect(output).not.toContain("CRITICAL: OpenClaw lock rollback"); + expect(output).not.toContain( + "OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox", + ); + }); + + it("uses the invoked nemohermes alias in staged recovery commands (#6126)", () => { + const harness = createHarness({ + failOpenClawGuardActions: ["lock"], + invokedAs: "nemohermes", + }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /startup-not-ready/, + ); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw", "nemohermes"); + expect(output).not.toContain("`nemoclaw openclaw shields up`"); + expect(output).not.toContain("`nemoclaw openclaw rebuild --yes`"); + }); + + it("reports staged recovery when a stopped sandbox prevents config relock (#6126)", () => { + const harness = createHarness({ directSandboxUnavailable: true }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /No running direct OpenShell sandbox container found/, + ); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); + expect(output).toContain( + "Warning: OpenClaw lock rollback could not restore the trusted posture", + ); + expect(output).not.toContain("CRITICAL: OpenClaw lock rollback"); + }); + + it("retains critical recovery for non-transient OpenClaw rollback failures (#6126)", () => { + const harness = createHarness({ + failOpenClawGuardActions: ["lock"], + openClawGuardFailure: { + code: "unsafe-config-path", + path: "/sandbox/.openclaw/openclaw.json", + detail: "canonical config path is not a safe regular file", + }, + }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /unsafe-config-path/, + ); + + const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); + expect(output).toContain( + "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", + ); + expect(output).not.toContain( + "Warning: OpenClaw lock rollback could not restore the trusted posture", + ); + }); + + it("retains critical recovery for structural startup-not-ready diagnostics (#6126)", () => { + const harness = createHarness({ + failOpenClawGuardActions: ["lock"], + openClawGuardFailure: { + code: "startup-not-ready", + path: "/run/nemoclaw/openclaw-config-ready.json", + detail: "installed config guard requires NemoClaw PID 1", + }, + }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /requires NemoClaw PID 1/, + ); + + const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); + expect(output).toContain( + "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", + ); + expect(output).not.toContain( + "Warning: OpenClaw lock rollback could not restore the trusted posture", + ); + }); + + it("retains critical recovery when a transient diagnostic is followed by another issue (#6126)", () => { + const harness = createHarness({ + failOpenClawGuardActions: ["lock"], + openClawGuardFailures: [ + { + code: "startup-not-ready", + path: "/run/nemoclaw/openclaw-config-ready.json", + detail: "OpenClaw startup is not ready for host config mutations", + }, + { + code: "unsafe-config-path", + path: "/sandbox/.openclaw/openclaw.json", + detail: "canonical config path is not a safe regular file", + }, + ], + }); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /unsafe-config-path/, + ); + + const output = harness.errorSpy.mock.calls.flat().map(String).join("\n"); + expect(output).toContain( + "CRITICAL: OpenClaw lock rollback could not restore the trusted posture. Restore from a trusted backup and recreate the sandbox.", + ); + expect(output).not.toContain( + "Warning: OpenClaw lock rollback could not restore the trusted posture", + ); + }); + + it("reports staged driver-neutral recovery when drift remediation cannot re-lock (#6126)", () => { + const harness = createHarness({ failOpenClawGuardActions: ["lock"] }); + const stateDir = path.join(tmpDir, ".nemoclaw", "state"); + fs.mkdirSync(stateDir, { recursive: true }); + fs.writeFileSync( + path.join(stateDir, "shields-openclaw.json"), + JSON.stringify({ + shieldsDown: false, + chattrApplied: false, + fileHashes: { + "/sandbox/.openclaw/openclaw.json": "a".repeat(64), + "/sandbox/.openclaw/.config-hash": "a".repeat(64), + }, + }), + ); + + expect(() => harness.shieldsUp("openclaw", { throwOnError: true })).toThrow( + /startup-not-ready/, + ); + + const output = expectStagedDriverNeutralRecovery(harness.errorSpy, "openclaw"); + expect(output).toContain("Config remains drifted — manual intervention required"); + }); + + 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); + }); +}); diff --git a/src/lib/shields/policy-transition.test.ts b/src/lib/shields/policy-transition.test.ts index a8c59a29a82..efde176a806 100644 --- a/src/lib/shields/policy-transition.test.ts +++ b/src/lib/shields/policy-transition.test.ts @@ -80,7 +80,7 @@ describe("shields policy transition", () => { }); it("never relaxes policy or persists mutable state when the base-policy read fails", () => { - expect(() => shields.shieldsDown("openclaw", { skipTimer: true, throwOnError: true })).toThrow( + expect(() => shields.shieldsDown("openclaw", { throwOnError: true })).toThrow( "Cannot capture current policy", ); expect(runSpy).not.toHaveBeenCalled(); @@ -98,7 +98,7 @@ describe("shields policy transition", () => { ])("never relaxes policy or persists mutable state for exit-zero %s output", (_name, output) => { runCaptureSpy.mockReturnValue(output); - expect(() => shields.shieldsDown("openclaw", { skipTimer: true, throwOnError: true })).toThrow( + expect(() => shields.shieldsDown("openclaw", { throwOnError: true })).toThrow( "Cannot capture current policy", ); expect(runSpy).not.toHaveBeenCalled(); @@ -138,7 +138,6 @@ describe("shields down policy rejection", () => { expect(() => harness.shieldsDown("openclaw", { reason: "verify", - skipTimer: true, throwOnError: true, }), ).toThrow(/Could not apply/); @@ -1105,19 +1104,12 @@ describe("shields-down rollback flow", () => { it("restores fresh mutable-default state when the timer handoff fails", () => { const stateDir = path.join(tmpDir, ".nemoclaw", "state"); const harness = createHarness({ + timerDiesAfterUnlock: true, fork: () => ({ pid: 4242, disconnect: vi.fn(), unref: vi.fn(), - send: vi.fn(() => { - const transitionName = fs - .readdirSync(stateDir) - .find((entry) => entry.startsWith("shields-transition-openclaw-")); - const transitionPath = path.join(stateDir, transitionName!); - const transition = JSON.parse(fs.readFileSync(transitionPath, "utf-8")); - fs.writeFileSync(transitionPath, JSON.stringify({ ...transition, phase: "active" })); - return true; - }), + send: vi.fn(() => true), kill: vi.fn(() => true), }), }); @@ -1128,7 +1120,7 @@ describe("shields-down rollback flow", () => { reason: "rollback coverage", throwOnError: true, }), - ).toThrow("Shields-down recovery ownership changed during the transition"); + ).toThrow(/live future auto-restore timer authority/u); expect(fs.existsSync(path.join(stateDir, "shields-openclaw.json"))).toBe(false); expect(harness.getOpenClawPosture()).toBe("mutable"); @@ -1145,20 +1137,13 @@ describe("shields-down rollback flow", () => { const stateDir = path.join(tmpDir, ".nemoclaw", "state"); const harness = createHarness({ confirmOpenClawInodeFlags: true, + timerDiesAfterUnlock: true, timerAuthorityRevokedSequence: [true, false], fork: () => ({ pid: 4242, disconnect: vi.fn(), unref: vi.fn(), - send: vi.fn(() => { - const transitionName = fs - .readdirSync(stateDir) - .find((entry) => entry.startsWith("shields-transition-openclaw-")); - const transitionPath = path.join(stateDir, transitionName!); - const transition = JSON.parse(fs.readFileSync(transitionPath, "utf-8")); - fs.writeFileSync(transitionPath, JSON.stringify({ ...transition, phase: "active" })); - return true; - }), + send: vi.fn(() => true), kill: vi.fn(() => true), }), }); @@ -1169,7 +1154,7 @@ describe("shields-down rollback flow", () => { reason: "timer authority coverage", throwOnError: true, }), - ).toThrow("Shields-down recovery ownership changed during the transition"); + ).toThrow(/live future auto-restore timer authority/u); expect(harness.getOpenClawPosture()).toBe("locked"); expect( @@ -1189,19 +1174,12 @@ describe("shields-down rollback flow", () => { const originalRmSync = fs.rmSync.bind(fs); const harness = createHarness({ confirmOpenClawInodeFlags: true, + timerDiesAfterUnlock: true, fork: () => ({ pid: 4242, disconnect: vi.fn(), unref: vi.fn(), - send: vi.fn(() => { - const transitionName = fs - .readdirSync(stateDir) - .find((entry) => entry.startsWith("shields-transition-openclaw-")); - const transitionPath = path.join(stateDir, transitionName!); - const transition = JSON.parse(fs.readFileSync(transitionPath, "utf-8")); - fs.writeFileSync(transitionPath, JSON.stringify({ ...transition, phase: "active" })); - return true; - }), + send: vi.fn(() => true), kill: vi.fn(() => true), }), }); @@ -1215,7 +1193,7 @@ describe("shields-down rollback flow", () => { reason: "state restoration coverage", throwOnError: true, }), - ).toThrow("Shields-down recovery ownership changed during the transition"); + ).toThrow(/live future auto-restore timer authority/u); expect(harness.getOpenClawPosture()).toBe("locked"); expect(JSON.parse(fs.readFileSync(statePath, "utf-8"))).toMatchObject({ shieldsDown: false }); @@ -1232,19 +1210,12 @@ describe("shields-down rollback flow", () => { const originalRmSync = fs.rmSync.bind(fs); const harness = createHarness({ failOpenClawGuardActions: ["lock"], + timerDiesAfterUnlock: true, fork: () => ({ pid: 4242, disconnect: vi.fn(), unref: vi.fn(), - send: vi.fn(() => { - const transitionName = fs - .readdirSync(stateDir) - .find((entry) => entry.startsWith("shields-transition-openclaw-")); - const transitionPath = path.join(stateDir, transitionName!); - const transition = JSON.parse(fs.readFileSync(transitionPath, "utf-8")); - fs.writeFileSync(transitionPath, JSON.stringify({ ...transition, phase: "active" })); - return true; - }), + send: vi.fn(() => true), kill: vi.fn(() => true), }), }); @@ -1258,7 +1229,7 @@ describe("shields-down rollback flow", () => { reason: "manual recovery coverage", throwOnError: true, }), - ).toThrow("Shields-down recovery ownership changed during the transition"); + ).toThrow(/live future auto-restore timer authority/u); expect(harness.getOpenClawPosture()).toBe("mutable"); expect(JSON.parse(fs.readFileSync(statePath, "utf-8"))).toMatchObject({ shieldsDown: true }); @@ -1320,7 +1291,6 @@ describe("shields-down rollback flow", () => { harness.shieldsDown("openclaw", { timeout: "5m", reason: "containment coverage", - skipTimer: true, throwOnError: true, }), ).toThrow(/startup-not-ready/); diff --git a/src/lib/shields/timer-bound-lock.test.ts b/src/lib/shields/timer-bound-lock.test.ts index 435c558cb9e..a72caa2cfd3 100644 --- a/src/lib/shields/timer-bound-lock.test.ts +++ b/src/lib/shields/timer-bound-lock.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { withTimerBoundShieldsMutationLock, withTimerBoundShieldsMutationLockAsync, + withTimerBoundShieldsMutationLockFallback, } from "./timer-bound-lock"; describe("timer-bound shields mutation lock", () => { @@ -47,6 +48,67 @@ describe("timer-bound shields mutation lock", () => { expect(callback).toHaveBeenCalledTimes(1); }); + it("uses the fallback token when no timer marker exists", () => { + const fallbackToken = "b".repeat(32); + const callback = vi.fn(() => "done"); + const withLock = vi.fn((_name, _command, fn, options) => { + expect(options).toEqual({ takeoverToken: fallbackToken }); + return fn(); + }); + + expect( + withTimerBoundShieldsMutationLockFallback("alpha", "shields down", fallbackToken, callback, { + readToken: () => undefined, + withLock, + withLockAsync: vi.fn(), + }), + ).toBe("done"); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it("gives an existing timer marker token priority over the fallback", () => { + const fallbackToken = "b".repeat(32); + const markerToken = "c".repeat(32); + const callback = vi.fn(() => "done"); + const withLock = vi.fn((_name, _command, fn, options) => { + expect(options).toEqual({ takeoverToken: markerToken }); + return fn(); + }); + + expect( + withTimerBoundShieldsMutationLockFallback("alpha", "shields down", fallbackToken, callback, { + readToken: () => markerToken, + withLock, + withLockAsync: vi.fn(), + }), + ).toBe("done"); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it("retries a marker generation change and preserves marker priority", () => { + const fallbackToken = "b".repeat(32); + const markerToken = "c".repeat(32); + const tokens = [undefined, markerToken, markerToken, markerToken]; + const callback = vi.fn(() => "done"); + const observedOptions: unknown[] = []; + + expect( + withTimerBoundShieldsMutationLockFallback("alpha", "shields down", fallbackToken, callback, { + readToken: () => tokens.shift(), + withLock: (_name, _command, fn, options) => { + observedOptions.push(options); + return fn(); + }, + withLockAsync: vi.fn(), + }), + ).toBe("done"); + expect(callback).toHaveBeenCalledTimes(1); + expect(observedOptions).toEqual([ + { takeoverToken: fallbackToken }, + { takeoverToken: markerToken }, + ]); + }); + it("fails closed when timer generations keep changing", () => { let generation = 0; expect(() => diff --git a/src/lib/shields/timer-bound-lock.ts b/src/lib/shields/timer-bound-lock.ts index d27b6e00420..616bdce39d0 100644 --- a/src/lib/shields/timer-bound-lock.ts +++ b/src/lib/shields/timer-bound-lock.ts @@ -40,9 +40,11 @@ function withTimerBoundShieldsMutationLockOptions( fn: () => T, lockOptions: ShieldsTransitionLockOptions, deps: TimerBoundLockDeps, + fallbackTakeoverToken?: string, ): T { for (let attempt = 0; attempt < MAX_TIMER_GENERATION_RETRIES; attempt += 1) { const token = deps.readToken(sandboxName); + const takeoverToken = token ?? fallbackTakeoverToken; const result = deps.withLock>( sandboxName, command, @@ -52,7 +54,7 @@ function withTimerBoundShieldsMutationLockOptions( }, { ...lockOptions, - ...(token ? { takeoverToken: token } : {}), + ...(takeoverToken ? { takeoverToken } : {}), }, ); if (!result.retry) return result.value; @@ -60,6 +62,27 @@ function withTimerBoundShieldsMutationLockOptions( throw new Error(`Auto-restore timer generation kept changing while acquiring '${command}'`); } +/** + * Bind a fresh timer generation before its marker exists, while still giving + * an already-published marker generation priority during recovery. + */ +export function withTimerBoundShieldsMutationLockFallback( + sandboxName: string, + command: string, + fallbackTakeoverToken: string, + fn: () => T, + deps: TimerBoundLockDeps = defaultDeps, +): T { + return withTimerBoundShieldsMutationLockOptions( + sandboxName, + command, + fn, + {}, + deps, + fallbackTakeoverToken, + ); +} + /** * 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 diff --git a/src/lib/shields/timer-control.ts b/src/lib/shields/timer-control.ts index 73352968034..1ce2555b097 100644 --- a/src/lib/shields/timer-control.ts +++ b/src/lib/shields/timer-control.ts @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; import fs from "node:fs"; +import path from "node:path"; import { performance } from "node:perf_hooks"; import { @@ -13,6 +15,16 @@ import { } from "../state/mcp-lifecycle-lock/shields-timer-authority"; const DEFAULT_PROCESS_INSPECTION_TIMEOUT_MS = 5_000; +const MAX_TIMER_AUTHORIZATION_PROOF_BYTES = 16 * 1024; + +interface TimerAuthorizationProof { + schemaVersion: 1; + pid: number; + sandboxName: string; + processToken: string; + timerProcessStartIdentity: string; + authoritySha256: string; +} function processInspectionDeadline(deadline?: number): number { return deadline ?? processInspectionDeadlineAfter(DEFAULT_PROCESS_INSPECTION_TIMEOUT_MS); @@ -43,15 +55,173 @@ function readAutoRestoreTakeoverToken(sandboxName: string): string | undefined { return readShieldsTimerTakeoverToken(sandboxName); } +function timerAuthoritySha256(marker: ShieldsTimerMarker): string { + return createHash("sha256") + .update( + JSON.stringify({ + schemaVersion: 1, + pid: marker.pid, + sandboxName: marker.sandboxName, + snapshotPath: marker.snapshotPath, + restoreAt: marker.restoreAt, + processToken: marker.processToken ?? null, + timerProcessStartIdentity: marker.timerProcessStartIdentity ?? null, + allowLegacyHermesProtocol: marker.allowLegacyHermesProtocol === true, + agentName: marker.agentName ?? null, + configPath: marker.configPath ?? null, + configDir: marker.configDir ?? null, + leaseOwnerPid: marker.leaseOwnerPid ?? null, + leaseOwnerStartIdentity: marker.leaseOwnerStartIdentity ?? null, + }), + ) + .digest("hex"); +} + +function timerAuthorizationProofPath(sandboxName: string, processToken: string): string { + if (!/^[0-9a-f]{32}$/.test(processToken)) { + throw new Error("Invalid timer authorization process token"); + } + return path.join( + path.dirname(timerMarkerPath(sandboxName)), + `shields-timer-authorization-${sandboxName}-${processToken}.json`, + ); +} + +function isTimerAuthorizationProof(value: unknown): value is TimerAuthorizationProof { + if (typeof value !== "object" || value === null) return false; + const proof = value as Partial; + return ( + proof.schemaVersion === 1 && + typeof proof.pid === "number" && + Number.isInteger(proof.pid) && + proof.pid > 0 && + typeof proof.sandboxName === "string" && + typeof proof.processToken === "string" && + /^[0-9a-f]{32}$/.test(proof.processToken) && + typeof proof.timerProcessStartIdentity === "string" && + proof.timerProcessStartIdentity.length > 0 && + typeof proof.authoritySha256 === "string" && + /^[0-9a-f]{64}$/.test(proof.authoritySha256) + ); +} + +function writeTimerAuthorizationProofForMarker(marker: ShieldsTimerMarker): void { + if (!marker.processToken || !marker.timerProcessStartIdentity) { + throw new Error("Timer marker is missing authorization proof identity"); + } + const currentStartIdentity = readProcessStartIdentity(process.pid); + if (marker.pid !== process.pid || currentStartIdentity !== marker.timerProcessStartIdentity) { + throw new Error("Timer process cannot publish authorization for another process identity"); + } + const proofPath = timerAuthorizationProofPath(marker.sandboxName, marker.processToken); + const tempPath = `${proofPath}.${String(process.pid)}.${Date.now().toString(16)}.tmp`; + const proof: TimerAuthorizationProof = { + schemaVersion: 1, + pid: marker.pid, + sandboxName: marker.sandboxName, + processToken: marker.processToken, + timerProcessStartIdentity: marker.timerProcessStartIdentity, + authoritySha256: timerAuthoritySha256(marker), + }; + let fd: number | undefined; + try { + fs.mkdirSync(path.dirname(proofPath), { recursive: true, mode: 0o700 }); + fd = fs.openSync( + tempPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, + 0o600, + ); + fs.writeFileSync(fd, JSON.stringify(proof)); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = undefined; + fs.renameSync(tempPath, proofPath); + const directoryFd = fs.openSync(path.dirname(proofPath), "r"); + try { + fs.fsyncSync(directoryFd); + } finally { + fs.closeSync(directoryFd); + } + } finally { + if (fd !== undefined) fs.closeSync(fd); + fs.rmSync(tempPath, { force: true }); + } +} + +function hasExactTimerAuthorizationProof(marker: ShieldsTimerMarker): boolean { + if (!marker.processToken || !marker.timerProcessStartIdentity) return false; + let fd: number | undefined; + try { + fd = fs.openSync( + timerAuthorizationProofPath(marker.sandboxName, marker.processToken), + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + const before = fs.fstatSync(fd); + if ( + !before.isFile() || + before.nlink !== 1 || + (before.mode & 0o777) !== 0o600 || + before.size <= 0 || + before.size > MAX_TIMER_AUTHORIZATION_PROOF_BYTES || + (typeof process.getuid === "function" && before.uid !== process.getuid()) + ) { + return false; + } + const raw = fs.readFileSync(fd, "utf-8"); + const after = fs.fstatSync(fd); + if ( + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeMs !== after.mtimeMs + ) { + return false; + } + const proof = JSON.parse(raw) as unknown; + return ( + isTimerAuthorizationProof(proof) && + proof.pid === marker.pid && + proof.sandboxName === marker.sandboxName && + proof.processToken === marker.processToken && + proof.timerProcessStartIdentity === marker.timerProcessStartIdentity && + proof.authoritySha256 === timerAuthoritySha256(marker) + ); + } catch { + return false; + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + +function removeTimerAuthorizationProof( + sandboxName: string, + processToken: string | undefined, +): void { + if (!processToken || !/^[0-9a-f]{32}$/.test(processToken)) return; + try { + fs.rmSync(timerAuthorizationProofPath(sandboxName, processToken), { force: true }); + } catch { + // Best effort. A proof cannot grant authority without its exact marker. + } +} + interface ClearTimerMarkerResult { cleared: boolean; warning?: string; } function clearTimerMarker(sandboxName: string): ClearTimerMarkerResult { + const marker = readTimerMarker(sandboxName); const markerPath = timerMarkerPath(sandboxName); try { fs.unlinkSync(markerPath); + removeTimerAuthorizationProof(sandboxName, marker?.processToken); + const directoryFd = fs.openSync(path.dirname(markerPath), "r"); + try { + fs.fsyncSync(directoryFd); + } finally { + fs.closeSync(directoryFd); + } return { cleared: true }; } catch (error) { const errno = error as NodeJS.ErrnoException; @@ -179,6 +349,15 @@ function verifyTimerMarkerIdentity(marker: ShieldsTimerMarker): { verified: boolean; warning?: string; } { + if ( + marker.timerProcessStartIdentity !== undefined && + readProcessStartIdentity(marker.pid) !== marker.timerProcessStartIdentity + ) { + return { + verified: false, + warning: `PID ${String(marker.pid)} start identity does not match the shields timer for sandbox '${marker.sandboxName}'; clearing marker without signaling.`, + }; + } const commandLine = readProcessCommandLine(marker.pid); if (!commandLine) { return { @@ -257,6 +436,7 @@ function killTimer(sandboxName: string): KillTimerResult { export type { ClearTimerMarkerResult, KillTimerResult, ShieldsTimerMarker as TimerMarker }; export { clearTimerMarker, + hasExactTimerAuthorizationProof, isProcessAlive, killTimer, processInspectionDeadlineAfter, @@ -265,6 +445,10 @@ export { readProcessStartIdentity, readProcessState, readTimerMarker, + removeTimerAuthorizationProof, + timerAuthoritySha256, + timerAuthorizationProofPath, timerMarkerPath, verifyTimerMarkerIdentity, + writeTimerAuthorizationProofForMarker, }; diff --git a/src/lib/shields/timer-process.test.ts b/src/lib/shields/timer-process.test.ts index e1c61c6c63f..0bc49be3391 100644 --- a/src/lib/shields/timer-process.test.ts +++ b/src/lib/shields/timer-process.test.ts @@ -29,7 +29,7 @@ describe("detached Shields timer process", () => { "exits after cooperative marker revocation", { timeout: 20_000 }, async () => { - const { killTimer } = await import("./timer-control"); + const { killTimer, readProcessStartIdentity } = await import("./timer-control"); const stateDir = path.join(tmpHome, ".nemoclaw", "state"); const sandboxName = "cooperative-stop"; const snapshotPath = path.join(stateDir, "snapshot.yaml"); @@ -60,6 +60,14 @@ describe("detached Shields timer process", () => { ); expect(child.pid).toBeTypeOf("number"); const childPid = child.pid as number; + let childStartIdentity: string | null = null; + await vi.waitFor( + () => { + childStartIdentity = readProcessStartIdentity(childPid); + expect(childStartIdentity).toBeTypeOf("string"); + }, + { timeout: 5_000, interval: 10 }, + ); let childStderr = ""; child.stderr?.setEncoding("utf-8"); child.stderr?.on("data", (chunk: string) => { @@ -75,6 +83,7 @@ describe("detached Shields timer process", () => { snapshotPath, restoreAt: restoreAtIso, processToken: PROCESS_TOKEN, + timerProcessStartIdentity: childStartIdentity, agentName: "openclaw", configPath: "/sandbox/.openclaw/openclaw.json", configDir: "/sandbox/.openclaw", diff --git a/src/lib/shields/timer.test.ts b/src/lib/shields/timer.test.ts index 2500b75b772..6b376d1c497 100644 --- a/src/lib/shields/timer.test.ts +++ b/src/lib/shields/timer.test.ts @@ -301,6 +301,11 @@ describe("shields timer authorization", () => { ); it("binds rebuild-only legacy authorization to both argv and the root-owned marker", async () => { + const timerControl = await import("./timer-control"); + const selfStartIdentity = "proc:self-start"; + const identitySpy = vi + .spyOn(timerControl, "readProcessStartIdentity") + .mockReturnValue(selfStartIdentity); const timer = await import("./timer"); const stateDir = path.join(tmpHome, ".nemoclaw", "state"); fs.mkdirSync(stateDir, { recursive: true }); @@ -316,6 +321,7 @@ describe("shields timer authorization", () => { snapshotPath, restoreAt: restoreAtIso, processToken: PROCESS_TOKEN, + timerProcessStartIdentity: selfStartIdentity, allowLegacyHermesProtocol: true, agentName: "openclaw", configPath: "/sandbox/.hermes/config.yaml", @@ -380,6 +386,7 @@ describe("shields timer authorization", () => { expect(timer.markerMatchesCurrentTimer(ordinary!)).toBe(false); expect(timer.markerMatchesCurrentTimer(mismatchedAgent!)).toBe(false); expect(timer.markerMatchesCurrentTimer(mismatchedTarget!)).toBe(false); + expect(identitySpy).toHaveBeenCalledTimes(1); expect( timer.parseTimerArgs([sandboxName, snapshotPath, restoreAtIso, "", "", PROCESS_TOKEN, "yes"]), ).toBeNull(); diff --git a/src/lib/shields/timer.ts b/src/lib/shields/timer.ts index 526222483f2..e792d7bbb99 100644 --- a/src/lib/shields/timer.ts +++ b/src/lib/shields/timer.ts @@ -26,7 +26,13 @@ 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 { + hasExactTimerAuthorizationProof, + isProcessAlive, + readProcessStartIdentity, + removeTimerAuthorizationProof, + writeTimerAuthorizationProofForMarker, +} from "./timer-control"; import { withShieldsTransitionLock } from "./transition-lock"; interface ShieldsStatePatch { @@ -184,6 +190,17 @@ function readTimerMarker(markerPath: string): ShieldsTimerMarker | null { return readShieldsTimerMarkerFile(markerPath); } +let cachedCurrentProcessStartIdentity: string | undefined; + +function currentProcessStartIdentity(): string | null { + if (cachedCurrentProcessStartIdentity !== undefined) { + return cachedCurrentProcessStartIdentity; + } + const identity = readProcessStartIdentity(process.pid); + if (identity !== null) cachedCurrentProcessStartIdentity = identity; + return identity; +} + function markerRecordMatchesCurrentTimer( marker: ShieldsTimerMarker | null, args: TimerArgs, @@ -195,6 +212,8 @@ function markerRecordMatchesCurrentTimer( marker.snapshotPath === args.snapshotPath && marker.restoreAt === args.restoreAtIso && marker.processToken === args.processToken && + (marker.timerProcessStartIdentity === undefined || + marker.timerProcessStartIdentity === currentProcessStartIdentity()) && (marker.allowLegacyHermesProtocol === true) === args.allowLegacyHermesProtocol && marker.leaseOwnerPid === args.leaseOwnerPid && marker.leaseOwnerStartIdentity === args.leaseOwnerStartIdentity && @@ -215,6 +234,13 @@ function cleanupOwnedTimerMarker(args: TimerArgs): boolean { if (markerRecordMatchesCurrentTimer(readTimerMarker(quarantinePath), args)) { fs.unlinkSync(quarantinePath); + removeTimerAuthorizationProof(args.sandboxName, args.processToken); + const directoryFd = fs.openSync(path.dirname(args.markerPath), "r"); + try { + fs.fsyncSync(directoryFd); + } finally { + fs.closeSync(directoryFd); + } return true; } @@ -650,12 +676,16 @@ function main(): void { let scheduled = false; const authorize = (): boolean => { if (scheduled) return true; - if (!markerMatchesCurrentTimer(args)) return false; - scheduled = true; + const marker = readTimerMarker(args.markerPath); + if (!markerRecordMatchesCurrentTimer(marker, args)) return false; const restoreTimeout = setTimeout( () => { clearInterval(authorityPoll); - if (!markerMatchesCurrentTimer(args)) { + const currentMarker = readTimerMarker(args.markerPath); + if ( + !markerRecordMatchesCurrentTimer(currentMarker, args) || + !hasExactTimerAuthorizationProof(currentMarker!) + ) { process.exit(0); return; } @@ -664,11 +694,29 @@ function main(): void { Math.max(0, args.restoreAtMs - Date.now()), ); const authorityPoll = setInterval(() => { - if (markerMatchesCurrentTimer(args)) return; + const currentMarker = readTimerMarker(args.markerPath); + if ( + markerRecordMatchesCurrentTimer(currentMarker, args) && + hasExactTimerAuthorizationProof(currentMarker!) + ) { + return; + } clearTimeout(restoreTimeout); clearInterval(authorityPoll); process.exit(0); }, AUTO_RESTORE_AUTHORITY_POLL_MS); + scheduled = true; + try { + writeTimerAuthorizationProofForMarker(marker!); + if (!hasExactTimerAuthorizationProof(marker!)) { + throw new Error("Timer authorization proof did not verify after publication"); + } + } catch { + clearTimeout(restoreTimeout); + clearInterval(authorityPoll); + scheduled = false; + return false; + } return true; }; @@ -688,18 +736,17 @@ function main(): void { request.processToken === args.processToken ) { const authorized = authorize(); - if ( - authorized && - request.acknowledge === true && - process.connected && - process.send !== undefined - ) { + if (!authorized) { + process.exit(1); + return; + } + if (request.acknowledge === true && process.connected && process.send !== undefined) { process.send({ type: "authorized", processToken: args.processToken }, () => undefined); } } }); process.once("disconnect", () => { - authorize(); + if (!authorize()) process.exit(1); }); } diff --git a/src/lib/shields/transition-lock.ts b/src/lib/shields/transition-lock.ts index 16cd5fbe55e..8cf56ef2fc9 100644 --- a/src/lib/shields/transition-lock.ts +++ b/src/lib/shields/transition-lock.ts @@ -15,6 +15,11 @@ import { import { resolveNemoclawStateDir } from "../state/paths"; import { isProcessAlive, readProcessStartIdentity } from "./timer-control"; +/** Shared state-root authority for callers already serialized by this facade. */ +export function resolveShieldsStateDir(homeDir?: string): string { + return resolveNemoclawStateDir(homeDir); +} + const LOCK_VERSION = 1; const MAX_OWNER_BYTES = 16 * 1024; const DEFAULT_WAIT_TIMEOUT_MS = 30_000; @@ -411,7 +416,7 @@ export function isShieldsTransitionLockUnavailable( export function shieldsTransitionLockPath( sandboxName: string, - stateDir: string = resolveNemoclawStateDir(), + stateDir: string = resolveShieldsStateDir(), ): string { const validName = validateSandboxName(sandboxName); return path.join(stateDir, `shields-transition-lock-${validName}.json`); @@ -430,7 +435,7 @@ export class ShieldsTransitionLockManager { private readonly ownership = new AsyncLocalStorage>(); constructor(deps: ShieldsTransitionLockDependencies = {}) { - this.stateDir = deps.stateDir ?? resolveNemoclawStateDir(); + this.stateDir = deps.stateDir ?? resolveShieldsStateDir(); this.pid = deps.pid ?? process.pid; this.now = deps.now ?? Date.now; this.sleep = deps.sleep ?? defaultSleep; diff --git a/src/lib/state/mcp-lifecycle-lock/shields-timer-authority.ts b/src/lib/state/mcp-lifecycle-lock/shields-timer-authority.ts index e2673beca34..4e347901d80 100644 --- a/src/lib/state/mcp-lifecycle-lock/shields-timer-authority.ts +++ b/src/lib/state/mcp-lifecycle-lock/shields-timer-authority.ts @@ -14,6 +14,7 @@ export interface ShieldsTimerMarker { snapshotPath: string; restoreAt: string; processToken?: string; + timerProcessStartIdentity?: string; allowLegacyHermesProtocol?: boolean; agentName?: string; configPath?: string; @@ -33,6 +34,9 @@ function isShieldsTimerMarker(value: unknown): value is ShieldsTimerMarker { typeof value.snapshotPath === "string" && typeof value.restoreAt === "string" && (value.processToken === undefined || typeof value.processToken === "string") && + (value.timerProcessStartIdentity === undefined || + (typeof value.timerProcessStartIdentity === "string" && + value.timerProcessStartIdentity.length > 0)) && (value.allowLegacyHermesProtocol === undefined || typeof value.allowLegacyHermesProtocol === "boolean") && (value.agentName === undefined || typeof value.agentName === "string") && diff --git a/test/config-set-nested-ssrf.test.ts b/test/config-set-nested-ssrf.test.ts index 7bec805e8fe..a6a58449c56 100644 --- a/test/config-set-nested-ssrf.test.ts +++ b/test/config-set-nested-ssrf.test.ts @@ -36,6 +36,11 @@ function installMockPrivilegedExec( // config validation and write behavior without requiring real Docker. privilegedSandboxExecArgv: (_sandboxName: string, cmd: readonly string[]) => [...cmd], resolveDirectSandboxContainer: () => "container-id", + withPrivilegedSandboxExecutionLease: ( + _sandboxName: string, + _operation: string, + fn: () => T, + ): T => fn(), }, } as any; requireCache[timerBoundLockPath] = { diff --git a/test/config-set-prompt-error.test.ts b/test/config-set-prompt-error.test.ts index 3c2d8692e35..37e05a01958 100644 --- a/test/config-set-prompt-error.test.ts +++ b/test/config-set-prompt-error.test.ts @@ -102,6 +102,11 @@ async function runConfigSetWithPrompt(prompt: () => Promise) { installMock(privilegedExecPath, { privilegedSandboxExecArgv: () => ["docker", "exec", "container-id"], resolveDirectSandboxContainer: () => "container-id", + withPrivilegedSandboxExecutionLease: ( + _sandboxName: string, + _operation: string, + callback: () => T, + ): T => callback(), }); installMock(credentialStorePath, { prompt }); Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true }); diff --git a/test/e2e/support/base-image-publication.test.ts b/test/e2e/support/base-image-publication.test.ts index a3384554a0c..1a545bc0c24 100644 --- a/test/e2e/support/base-image-publication.test.ts +++ b/test/e2e/support/base-image-publication.test.ts @@ -192,13 +192,9 @@ describe("base-image publication evidence", () => { "nemoclaw/**", "nemoclaw-blueprint/**", "scripts/**", - - "test/e2e/live/managed-image-activation-e2e.test.ts", - "test/e2e/live/managed-image-activation-e2e-helpers.ts", "src/lib/actions/sandbox/openshell-child-visible-credentials.v*.json", "src/lib/messaging/**", "src/lib/tool-disclosure.ts", - "test/e2e/live/managed-image-activation-e2e*.ts", "tools/mcp-tool-discovery-runtime/**", "tsconfig.runtime-preloads.json", ]), diff --git a/test/helpers/docker-operation-authority-test-helpers.ts b/test/helpers/docker-operation-authority-test-helpers.ts new file mode 100644 index 00000000000..d23dbd1492c --- /dev/null +++ b/test/helpers/docker-operation-authority-test-helpers.ts @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { vi } from "vitest"; +import type { ContainerEngineCommandCapture } from "../../src/lib/adapters/container-engine"; + +function contextInspection(host: string) { + return { + status: 0, + stdout: JSON.stringify({ + Endpoints: { docker: { Host: host, SkipTLSVerify: false } }, + TLSMaterial: { docker: [] }, + }), + stderr: "", + }; +} + +export function createContextCapture( + host: string, +): ReturnType> { + return vi.fn((_executable, args) => { + if (args.includes("inspect")) return contextInspection(host); + return { status: 0, stdout: "", stderr: "" }; + }); +} + +export function createDriftingContextCapture(): ReturnType< + typeof vi.fn +> { + let inspections = 0; + return vi.fn((_executable, args) => { + if (args.includes("inspect")) { + inspections += 1; + return contextInspection(`ssh://nvidia@spark-${String(inspections)}.example.test`); + } + return { status: 0, stdout: "", stderr: "" }; + }); +} diff --git a/test/helpers/docker-state-mutation-harness.ts b/test/helpers/docker-state-mutation-harness.ts new file mode 100644 index 00000000000..50368146425 --- /dev/null +++ b/test/helpers/docker-state-mutation-harness.ts @@ -0,0 +1,428 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { vi } from "vitest"; +import type { ContainerEngineCommandCapture } from "../../src/lib/adapters/container-engine"; +import { RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION } from "../../src/lib/onboard/runtime-provider/contract"; +import { createDockerOperationAuthority } from "../../src/lib/onboard/runtime-provider/docker-operation-authority"; +import { createDockerStateMutationOwner } from "../../src/lib/onboard/runtime-provider/docker-state-mutation"; +import { createFilePersistedEngineAuthorityStore } from "../../src/lib/onboard/runtime-provider/persisted-engine-authority"; +import { + createFilePersistedEngineLifecycleStore, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE, +} from "../../src/lib/onboard/runtime-provider/persisted-engine-lifecycle"; +import { prepareRuntimeProviderStateMutationPlan } from "../../src/lib/onboard/runtime-provider/state-mutation"; +import type { SandboxEntry } from "../../src/lib/state/registry/types"; + +export const DOCKER_STATE_MUTATION_RUNTIME_ID = "a".repeat(64); +export const DOCKER_STATE_MUTATION_PROJECTION_SHA256 = "b".repeat(64); +export const DOCKER_STATE_MUTATION_STATE_ROOT = "/sandbox/.hermes"; +export const DOCKER_STATE_MUTATION_LIFECYCLE_GENERATION = "generation-7"; +const SANDBOX_ID = "sandbox-alpha-id"; +export const DOCKER_STATE_MUTATION_SANDBOX_FINGERPRINT = createHash("sha256") + .update(SANDBOX_ID) + .digest("hex"); + +const roots: string[] = []; + +function temporaryRoot(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-state-mutation-")); + roots.push(root); + return root; +} + +export function cleanupDockerStateMutationRoots(): void { + for (const root of roots.splice(0)) fs.rmSync(root, { force: true, recursive: true }); +} + +export function persistedDockerStateMutationIntentPath( + root: string, + transactionId: string, +): string { + return path.join( + root, + PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, + transactionId, + PERSISTED_ENGINE_STATE_MUTATION_INTENT_FILE, + ); +} + +export function persistedDockerStateMutationRuntimeClaimPath(root: string): string { + const identity = createHash("sha256") + .update("docker", "utf8") + .update("\0", "utf8") + .update(DOCKER_STATE_MUTATION_RUNTIME_ID, "utf8") + .digest("hex"); + return path.join(root, PERSISTED_ENGINE_LIFECYCLE_DIRECTORY, "runtime-target-claims", identity); +} + +export function dockerStateMutationPlan() { + return prepareRuntimeProviderStateMutationPlan({ + schemaVersion: RUNTIME_PROVIDER_STATE_MUTATION_PLAN_SCHEMA_VERSION, + intent: "protection-transition", + target: "mutable", + rollback: "locked", + stateRoot: DOCKER_STATE_MUTATION_STATE_ROOT, + selectors: [{ kind: "path", path: "config.yaml" }], + stateLockPlan: { + version: 1, + readOnlyRoots: ["config.yaml"], + confidentialRoots: [], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: [], + }, + projectionSha256: DOCKER_STATE_MUTATION_PROJECTION_SHA256, + }); +} + +export interface DockerStateMutationHarnessOptions { + readonly mutateReceipt?: ( + receipt: Readonly>, + action: string, + ) => Readonly>; + readonly afterHelper?: (action: string, state: DockerStateMutationHarnessState) => void; + readonly deferAcquireOnce?: boolean; + readonly failAcquire?: boolean; + readonly failReleaseOnce?: boolean; + readonly lifecycleGeneration?: string; + readonly loseAcquireResponseOnce?: boolean; + readonly loseReleaseResponseOnce?: boolean; +} + +export interface DockerStateMutationHarnessState { + runtimePid: number; + mountSource: string; + sandboxId: string; + pidMode: string; + privileged: boolean; + overlayProc: boolean; +} + +export function createDockerStateMutationHarness(options: DockerStateMutationHarnessOptions = {}) { + const lifecycleGeneration = + options.lifecycleGeneration ?? DOCKER_STATE_MUTATION_LIFECYCLE_GENERATION; + const state: DockerStateMutationHarnessState = { + runtimePid: 4812, + mountSource: "/var/lib/openshell/alpha/hermes", + sandboxId: SANDBOX_ID, + pidMode: "", + privileged: false, + overlayProc: false, + }; + const helperActions: string[] = []; + const acquireRequests: string[] = []; + let acquireDeferralsRemaining = options.deferAcquireOnce ? 1 : 0; + let lostAcquireResponsesRemaining = options.loseAcquireResponseOnce ? 1 : 0; + let releaseFailuresRemaining = options.failReleaseOnce ? 1 : 0; + let lostReleaseResponsesRemaining = options.loseReleaseResponseOnce ? 1 : 0; + let marker: Record | null = null; + let releasedMarker: Record | null = null; + let deferredAcquireRequest: string | null = null; + + const acquireMarker = (request: Record) => { + const candidate = { + schemaVersion: 1, + phase: "fenced", + transactionId: request.transactionId, + providerId: request.providerId, + sandboxName: request.sandboxName, + lifecycleGeneration: request.lifecycleGeneration, + engineBindingSha256: request.engineBindingSha256, + runtimeId: request.runtimeId, + runtimePid: request.runtimePid, + sandboxIdentitySha256: request.sandboxIdentitySha256, + containerMountsSha256: request.containerMountsSha256, + stateRoot: request.stateRoot, + stateRootMountsSha256: request.stateRootMountsSha256, + mountNamespace: "mnt:[4026533007]", + stateRootDevice: "2050", + stateRootInode: "94212", + planSha256: request.planSha256, + projectionSha256: request.projectionSha256, + nonce: request.nonce, + target: request.target, + rollback: request.rollback, + }; + if (marker !== null && JSON.stringify(marker) !== JSON.stringify(candidate)) { + return { status: 1, stdout: "", stderr: "conflicting acquire request" }; + } + marker = candidate; + return null; + }; + + const capture = vi.fn((_executable, args, _timeout, input) => { + const command = args.slice(4); + if (command[0] === "ps") { + return { status: 0, stdout: `${DOCKER_STATE_MUTATION_RUNTIME_ID}\n`, stderr: "" }; + } + if (command[0] === "container" && command[1] === "inspect") { + return { + status: 0, + stdout: JSON.stringify([ + DOCKER_STATE_MUTATION_RUNTIME_ID, + true, + "running", + false, + false, + false, + state.runtimePid, + "openshell", + "alpha", + state.sandboxId, + state.pidMode, + state.privileged, + [ + { + Type: "bind", + Source: state.mountSource, + Destination: DOCKER_STATE_MUTATION_STATE_ROOT, + Mode: "", + RW: true, + Propagation: "rprivate", + }, + { + Type: "bind", + Source: "/var/lib/openshell/alpha/cache", + Destination: `${DOCKER_STATE_MUTATION_STATE_ROOT}/cache`, + Mode: "", + RW: true, + Propagation: "rprivate", + }, + ...(state.overlayProc + ? [ + { + Type: "bind", + Source: "/proc", + Destination: "/proc", + Mode: "", + RW: true, + Propagation: "rprivate", + }, + ] + : []), + ], + ]), + stderr: "", + }; + } + if (command[0] !== "container" || command[1] !== "exec") { + return { status: 1, stdout: "", stderr: "unexpected command" }; + } + const action = command.at(-1) ?? ""; + helperActions.push(action); + const serializedRequest = input?.toString("utf8") ?? "null"; + const request = JSON.parse(serializedRequest) as Record; + if (action === "acquire") { + acquireRequests.push(serializedRequest); + if (options.failAcquire) { + return { status: 1, stdout: "", stderr: "helper marker unavailable" }; + } + if (acquireDeferralsRemaining > 0) { + acquireDeferralsRemaining -= 1; + deferredAcquireRequest = serializedRequest; + return { status: 1, stdout: "", stderr: "in-container acquire is still queued" }; + } + const conflict = acquireMarker(request); + if (conflict) return conflict; + } else if (!marker) { + if (releasedMarker && (action === "recover" || action === "release")) { + marker = releasedMarker; + } else { + return { status: 1, stdout: "", stderr: "no durable marker" }; + } + } else if (request.providerHandle !== undefined && action !== "recover") { + const active: Record = { ...marker, phase: "fenced" }; + delete active.configurationGeneration; + delete active.listenerIdentity; + delete active.healthSha256; + delete active.activationProviderHandle; + const expected = `docker-state-mutation-v1:${String(marker.transactionId)}:${createHash("sha256").update(JSON.stringify(active), "utf8").digest("hex")}`; + if (request.providerHandle !== expected) { + return { status: 1, stdout: "", stderr: "provider handle mismatch" }; + } + } + const activeMarker = marker as Record; + if (action === "publish") { + marker = { ...activeMarker, phase: "published" }; + } else if (action === "rollback") { + marker = { ...activeMarker, phase: "rolled-back" }; + } else if (action === "activate") { + const configurationGeneration = "config-generation-8"; + const listenerIdentity = "tcp:18789"; + const healthSha256 = "c".repeat(64); + const evidence = { + schemaVersion: 1, + providerId: activeMarker.providerId, + sandboxName: activeMarker.sandboxName, + lifecycleGeneration: activeMarker.lifecycleGeneration, + runtimeId: activeMarker.runtimeId, + nonce: activeMarker.nonce, + configurationGeneration, + listenerIdentity, + healthSha256, + fenceProviderHandle: request.providerHandle, + }; + marker = { + ...activeMarker, + phase: "activation-proven", + configurationGeneration, + listenerIdentity, + healthSha256, + activationProviderHandle: `docker-state-mutation-activation-v1:${String( + activeMarker.transactionId, + )}:${createHash("sha256").update(JSON.stringify(evidence), "utf8").digest("hex")}`, + }; + } else if (action === "release") { + if (releaseFailuresRemaining > 0) { + releaseFailuresRemaining -= 1; + return { status: 1, stdout: "", stderr: "release unavailable" }; + } + if (request.activationProviderHandle !== activeMarker.activationProviderHandle) { + return { status: 1, stdout: "", stderr: "activation handle mismatch" }; + } + } + const response = options.mutateReceipt?.(marker as Record, action) ?? marker; + options.afterHelper?.(action, state); + if (action === "acquire" && lostAcquireResponsesRemaining > 0) { + lostAcquireResponsesRemaining -= 1; + return { status: 1, stdout: "", stderr: "acquire response lost" }; + } + if (action === "release") { + releasedMarker = marker; + marker = null; + if (lostReleaseResponsesRemaining > 0) { + lostReleaseResponsesRemaining -= 1; + return { status: 1, stdout: "", stderr: "release response lost" }; + } + } else if (releasedMarker === marker) { + marker = null; + } + return { status: 0, stdout: `${JSON.stringify(response)}\n`, stderr: "" }; + }); + const root = temporaryRoot(); + const authority = createDockerOperationAuthority( + "sandbox-lifecycle", + { + HOME: "/tmp/nemoclaw-home", + DOCKER_CONFIG: "/tmp/nemoclaw-docker", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + }, + capture, + ); + const engineAuthorityStore = createFilePersistedEngineAuthorityStore(root); + const lifecycleStore = createFilePersistedEngineLifecycleStore(root); + const owner = createDockerStateMutationOwner({ + sandboxName: "alpha", + lifecycleGeneration, + lifecycleLiveIdentityFingerprint: DOCKER_STATE_MUTATION_SANDBOX_FINGERPRINT, + runtimeId: DOCKER_STATE_MUTATION_RUNTIME_ID, + authority, + engineAuthorityStore, + lifecycleStore, + }); + const sandbox: SandboxEntry = { + name: "alpha", + openshellDriver: "docker", + lifecycleGeneration, + lifecycleLiveIdentityFingerprint: DOCKER_STATE_MUTATION_SANDBOX_FINGERPRINT, + }; + const context = { + environment: { + HOME: "/tmp/nemoclaw-home", + DOCKER_CONFIG: "/tmp/nemoclaw-docker", + DOCKER_HOST: "unix:///tmp/nemoclaw-docker.sock", + }, + sandbox, + sandboxName: "alpha", + }; + const replayDeferredAcquire = () => { + if (deferredAcquireRequest === null) throw new Error("No deferred acquire request exists."); + const serializedRequest = deferredAcquireRequest; + deferredAcquireRequest = null; + helperActions.push("acquire"); + acquireRequests.push(serializedRequest); + const request = JSON.parse(serializedRequest) as Record; + const conflict = acquireMarker(request); + if (conflict) throw new Error(conflict.stderr); + return marker; + }; + return { + acquireRequests, + authority, + capture, + context, + engineAuthorityStore, + helperActions, + lifecycleStore, + lifecycleGeneration, + owner, + replayDeferredAcquire, + root, + state, + }; +} + +export function createAmbiguousRuntimeCapture( + runtime: ReturnType, +): ReturnType> { + return vi.fn((executable, args, timeout, input) => { + if (args.slice(4)[0] === "ps") { + return { + status: 0, + stdout: `${DOCKER_STATE_MUTATION_RUNTIME_ID}\n${"c".repeat(64)}\n`, + stderr: "", + }; + } + return runtime.capture(executable, args, timeout, input); + }); +} + +export function createOneTimeAcquireMountDrift(): ( + action: string, + state: DockerStateMutationHarnessState, +) => void { + let driftOnce = true; + return (action, state) => { + if (action === "acquire" && driftOnce) { + driftOnce = false; + state.mountSource = "/var/lib/openshell/replaced/hermes"; + } + }; +} + +export function throwBeforeClaimUnlink( + originalUnlink: typeof fs.unlinkSync, + claimPath: string, + target: fs.PathLike, +): void { + if (String(target) === claimPath) throw new Error("injected exit before claim unlink"); + originalUnlink(target); +} + +export function createDurableReceiptUnlinkInterruption( + originalUnlink: typeof fs.unlinkSync, + claimPath: string, + receiptPath: string, +): { + readonly receiptWasDurable: () => boolean; + readonly unlink: (target: fs.PathLike) => void; +} { + let receiptWasDurable = false; + return { + receiptWasDurable: () => receiptWasDurable, + unlink: (target) => { + if (String(target) === claimPath) { + receiptWasDurable = fs.existsSync(receiptPath); + throw new Error("injected exit before claim unlink"); + } + originalUnlink(target); + }, + }; +} diff --git a/test/helpers/hermes-runtime-state-mutation-test-helpers.ts b/test/helpers/hermes-runtime-state-mutation-test-helpers.ts new file mode 100644 index 00000000000..a15d25a71a1 --- /dev/null +++ b/test/helpers/hermes-runtime-state-mutation-test-helpers.ts @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export type HermesTransitionFailureStage = "publication" | "verification" | "activation"; + +export function createHermesTransitionFailureController( + failureStage: HermesTransitionFailureStage, + failure: Error, + options: { readonly failOnlyFirstActivation?: boolean } = {}, +): { + readonly afterAssertion: () => void; + readonly afterPublication: () => void; + readonly beforeActivation: () => void; +} { + let assertionCount = 0; + let activationCount = 0; + return { + afterAssertion: () => { + assertionCount += 1; + if (failureStage === "verification" && assertionCount === 2) throw failure; + }, + afterPublication: () => { + if (failureStage === "publication") throw failure; + }, + beforeActivation: () => { + activationCount += 1; + if ( + failureStage === "activation" && + (!options.failOnlyFirstActivation || activationCount === 1) + ) { + throw failure; + } + }, + }; +} diff --git a/test/helpers/hermes-shields-provider-consumer-harness.ts b/test/helpers/hermes-shields-provider-consumer-harness.ts new file mode 100644 index 00000000000..5c146c5b139 --- /dev/null +++ b/test/helpers/hermes-shields-provider-consumer-harness.ts @@ -0,0 +1,365 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { type MockInstance, vi } from "vitest"; +import type { SandboxEntry } from "../../src/lib/state/registry"; + +const INDEX_MODULE = "./index.js"; +export const HERMES_PROVIDER_CAPABILITY_PATH = + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json"; +const HERMES_PROVIDER_CAPABILITY = + '{"schemaVersion":1,"protocol":"nemoclaw-runtime-state-mutation-publisher-v1","agent":"hermes","providerId":"docker","stateRoot":"/sandbox/.hermes","planSchemaVersion":2,"entrypoint":"/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"}'; +const SEALED_PLAN_HELP = [ + "begin-shields-transition", + "run-state-dir-transition", + "apply-shields-transition", + "finish-shields-transition", + "prepare-shields-abort", + "abort-shields-transition", + "--rollback-shields-mode", + "--state-lock-plan-json", +].join(" "); + +export const hermesProviderConsumerTarget = { + agentName: "hermes", + configPath: "/sandbox/.hermes/config.yaml", + configDir: "/sandbox/.hermes", + configFile: "config.yaml", + sensitiveFiles: ["/sandbox/.hermes/.config-hash", "/sandbox/.hermes/.env"], + stateLockPlan: { + version: 1 as const, + readOnlyRoots: ["skills"], + confidentialRoots: ["pairing"], + readOnlyPrefixes: [], + confidentialPrefixes: [], + writableSubpaths: [], + }, + stateLockPlanInImage: true, +}; + +export const hermesProviderConsumerSandbox: SandboxEntry = { + name: "current-hermes", + agent: "hermes", + openshellDriver: "docker", + lifecycleGeneration: "generation-1", + workload: { + schemaVersion: 1, + kind: "managed-image", + reference: "ghcr.io/nvidia/nemoclaw/hermes@sha256:abc", + platform: "linux/amd64", + release: "test", + sourceRevision: "a".repeat(40), + sourceCohort: "test", + capabilityContractVersion: 1, + startupProfileContractVersion: 1, + encodedProfile: "e30", + startupProfileSha256: "b".repeat(64), + credentialProxyReplayRequired: true, + shared: true, + }, +}; + +export type HermesShieldsProviderConsumerHarness = { + auditSpy: MockInstance; + capabilityProbe: { + error: Error | null; + presence: string; + }; + commands: string[][]; + dockerExecSpy: MockInstance; + lifecycleGateSpy: MockInstance; + registrySpy: MockInstance; + routeSpy: MockInstance; + runSpy: MockInstance; + shields: typeof import("../../src/lib/shields/index"); + spies: MockInstance[]; + supportSpy: MockInstance; + transitionSpy: MockInstance; + verifyLockSpy: MockInstance; + cleanup: () => void; +}; + +export function writeBoundForwardPolicy( + stateDir: string, + sandboxName: string, + processToken: string, + content = "version: 1\nnetwork_policies:\n permissive: {}\n", +) { + const policyPath = path.join( + stateDir, + `shields-forward-policy-${sandboxName}-${processToken}.yaml`, + ); + fs.writeFileSync(policyPath, content, { mode: 0o600 }); + fs.chmodSync(policyPath, 0o600); + const metadata = fs.statSync(policyPath); + return { + schemaVersion: 1, + path: policyPath, + sha256: createHash("sha256").update(content).digest("hex"), + size: Buffer.byteLength(content), + mode: 0o600, + uid: metadata.uid, + gid: metadata.gid, + nlink: 1, + }; +} + +export function writeTimerAuthorizationProof(loadSource: NodeRequire, sandboxName: string): void { + const timerControl = loadSource( + "./timer-control.js", + ) as typeof import("../../src/lib/shields/timer-control"); + const marker = timerControl.readTimerMarker(sandboxName); + if (!marker?.processToken || !marker.timerProcessStartIdentity) { + throw new Error("Test timer marker is missing exact proof authority"); + } + fs.writeFileSync( + timerControl.timerAuthorizationProofPath(sandboxName, marker.processToken), + JSON.stringify({ + schemaVersion: 1, + pid: marker.pid, + sandboxName, + processToken: marker.processToken, + timerProcessStartIdentity: marker.timerProcessStartIdentity, + authoritySha256: timerControl.timerAuthoritySha256(marker), + }), + { mode: 0o600 }, + ); +} + +export function createTimerAuthorizationSender( + loadSource: NodeRequire, + sandboxName: string, +): (message: unknown) => boolean { + const timerControl = loadSource( + "./timer-control.js", + ) as typeof import("../../src/lib/shields/timer-control"); + return (message) => { + const request = message as { type?: unknown; processToken?: unknown }; + if (request.type === "authorize" && typeof request.processToken === "string") { + const marker = timerControl.readTimerMarker(sandboxName); + if (marker?.timerProcessStartIdentity) { + fs.writeFileSync( + timerControl.timerAuthorizationProofPath(sandboxName, request.processToken), + JSON.stringify({ + schemaVersion: 1, + pid: marker.pid, + sandboxName, + processToken: request.processToken, + timerProcessStartIdentity: marker.timerProcessStartIdentity, + authoritySha256: timerControl.timerAuthoritySha256(marker), + }), + { mode: 0o600 }, + ); + } + } + return true; + }; +} + +export function createFailingCapabilityProbeResponse( + isCapabilityProbe: (command: string[]) => boolean, + error: Error, +): (command: string[]) => string { + return (command) => { + if (isCapabilityProbe(command)) throw error; + return ""; + }; +} + +export function createRetainedUnlockSimulation( + events: string[], + commands: string[][], +): { + readonly activeClaim: () => boolean; + readonly dockerExec: (commandValue: unknown) => string; + readonly hasActiveClaim: () => boolean; + readonly livePosture: () => "locked" | "mutable"; + readonly run: (commandValue: unknown) => { readonly status: 0 }; + readonly transition: (input: { + readonly target: "locked" | "mutable"; + readonly rollback: string; + }) => { readonly fence: Record; readonly proof: Record }; +} { + let activeClaim = true; + let livePosture: "locked" | "mutable" = "mutable"; + return { + activeClaim: () => activeClaim, + dockerExec: (commandValue) => { + const command = commandValue as string[]; + commands.push(command); + if (command[0] === "stat" && command.at(-1) === "/sandbox/.hermes") { + if (livePosture === "mutable") events.push("verified-mutable"); + return livePosture === "locked" ? "755 root:root\n" : "3770 sandbox:sandbox\n"; + } + if (command[0] === "stat") { + return livePosture === "locked" ? "444 root:root\n" : "640 sandbox:sandbox\n"; + } + if (command[0] === "lsattr") { + return `${livePosture === "locked" ? "----i---------------" : "--------------------"} ${String(command.at(-1))}\n`; + } + return ""; + }, + hasActiveClaim: () => activeClaim, + livePosture: () => livePosture, + run: (commandValue) => { + const command = commandValue as string[]; + if (command[0] === "policy" && command[1] === "set") events.push("policy"); + return { status: 0 }; + }, + transition: (input) => { + events.push(`provider:${input.target}/${input.rollback}`); + if (activeClaim) { + // Recovering the interrupted mutable target restores its retained + // restrictive rollback before releasing direct-exec exclusion. + activeClaim = false; + livePosture = "locked"; + } else if (input.target !== input.rollback) { + livePosture = input.target; + } + return { fence: {}, proof: {} }; + }, + }; +} + +export function createTransitionFailureForPosture( + posture: "locked" | "mutable", + message: string, +): (input: { readonly target: string; readonly rollback: string }) => { + readonly fence: Record; + readonly proof: Record; +} { + return (input) => { + if (input.target === posture && input.rollback === posture) throw new Error(message); + return { fence: {}, proof: {} }; + }; +} + +export function createHermesShieldsProviderConsumerHarness( + loadSource: NodeRequire, +): HermesShieldsProviderConsumerHarness { + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-provider-consumer-")); + vi.stubEnv("HOME", homeDir); + const spies: MockInstance[] = []; + const commands: string[][] = []; + const capabilityProbe = { presence: "present", error: null as Error | null }; + delete require.cache[loadSource.resolve(INDEX_MODULE)]; + + const runner = loadSource("../runner.js"); + const policy = loadSource("../policy/index.js"); + const registry = loadSource("../state/registry.js"); + const privilegedExec = loadSource("../sandbox/privileged-exec.js"); + const dockerExec = loadSource("../adapters/docker/exec.js"); + const transition = loadSource("./hermes-runtime-state-mutation.js"); + const runtimeProvider = loadSource("../onboard/runtime-provider/persisted-engine-lifecycle.js"); + const verifyLock = loadSource("./verify-lock.js"); + const relockReconfirm = loadSource("./relock-reconfirm.js"); + const audit = loadSource("./audit.js"); + const timerControl = loadSource("./timer-control.js"); + + const registrySpy = vi + .spyOn(registry, "getSandbox") + .mockReturnValue(hermesProviderConsumerSandbox); + const verifyLockSpy = vi + .spyOn(verifyLock, "verifyShieldsLockState") + .mockReturnValue({ issues: [] }); + const runSpy = vi.spyOn(runner, "run").mockReturnValue({ status: 0 }); + spies.push( + runSpy, + vi.spyOn(runner, "validateName").mockImplementation((value: unknown) => String(value)), + vi + .spyOn(policy, "buildPolicySetCommand") + .mockImplementation((file: unknown, name: unknown) => [ + "policy", + "set", + String(file), + String(name), + ]), + registrySpy, + vi + .spyOn(privilegedExec, "privilegedSandboxExecArgv") + .mockImplementation((_sandboxName: unknown, command: unknown) => command as string[]), + verifyLockSpy, + vi.spyOn(console, "log").mockImplementation(() => undefined), + vi.spyOn(console, "error").mockImplementation(() => undefined), + vi.spyOn(console, "warn").mockImplementation(() => undefined), + vi.spyOn(timerControl, "isProcessAlive").mockReturnValue(true), + vi.spyOn(timerControl, "readProcessStartIdentity").mockReturnValue("live-timer-start"), + vi.spyOn(timerControl, "verifyTimerMarkerIdentity").mockReturnValue({ verified: true }), + ); + const transitionSpy = vi + .spyOn(transition, "runHermesRuntimeProviderStateMutation") + .mockReturnValue({ fence: {}, proof: {} }); + const supportSpy = vi + .spyOn(transition, "supportsHermesRuntimeProviderStateMutation") + .mockReturnValue(true); + const lifecycleGateSpy = vi.spyOn(runtimeProvider, "hasActivePersistedEngineStateMutationTarget"); + const routeSpy = vi + .spyOn(relockReconfirm, "waitForHermesInferenceRouteConvergence") + .mockReturnValue({ ok: true, attempts: 1, httpStatus: 200 }); + const auditSpy = vi.spyOn(audit, "appendAuditEntry").mockImplementation(() => undefined); + const dockerExecSpy = vi + .spyOn(dockerExec, "dockerExecFileSync") + .mockImplementation((commandValue: unknown) => { + const command = commandValue as string[]; + commands.push(command); + if ( + command.includes("-c") && + command.some((entry) => entry.includes("os.lstat")) && + command.at(-1) === HERMES_PROVIDER_CAPABILITY_PATH + ) { + if (capabilityProbe.error) throw capabilityProbe.error; + return `${capabilityProbe.presence}\n`; + } + if (command[0] === "stat" && command.at(-1) === HERMES_PROVIDER_CAPABILITY_PATH) { + return "444 0 0 1 regular file\n"; + } + if (command[0] === "cat" && command.at(-1) === HERMES_PROVIDER_CAPABILITY_PATH) { + return `${HERMES_PROVIDER_CAPABILITY}\n`; + } + if ( + command.some((entry) => entry.endsWith("/hermes-runtime-config-guard.py")) && + command.includes("--help") + ) { + return `${SEALED_PLAN_HELP}\n`; + } + if (command[0] === "stat" && command.at(-1) === hermesProviderConsumerTarget.configDir) { + return "3770 sandbox:sandbox\n"; + } + if (command[0] === "stat") return "640 sandbox:sandbox\n"; + if (command[0] === "lsattr") return `---------------- ${String(command.at(-1))}\n`; + if (command[0] === "sha256sum") { + return `${"c".repeat(64)} ${String(command.at(-1))}\n`; + } + return ""; + }); + spies.push(transitionSpy, supportSpy, lifecycleGateSpy, routeSpy, auditSpy, dockerExecSpy); + + const shields = loadSource(INDEX_MODULE) as typeof import("../../src/lib/shields/index"); + + return { + auditSpy, + capabilityProbe, + cleanup: () => { + for (const spy of spies) spy.mockRestore(); + vi.unstubAllEnvs(); + delete require.cache[loadSource.resolve(INDEX_MODULE)]; + fs.rmSync(homeDir, { recursive: true, force: true }); + }, + commands, + dockerExecSpy, + lifecycleGateSpy, + registrySpy, + routeSpy, + runSpy, + shields, + spies, + supportSpy, + transitionSpy, + verifyLockSpy, + }; +} diff --git a/test/helpers/privileged-exec-test-helpers.ts b/test/helpers/privileged-exec-test-helpers.ts new file mode 100644 index 00000000000..12d077ac8e4 --- /dev/null +++ b/test/helpers/privileged-exec-test-helpers.ts @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { ChildProcess } from "node:child_process"; +import fs from "node:fs"; + +function createReleaseMarker(releasePath: string): void { + try { + fs.writeFileSync(releasePath, "release", { flag: "wx" }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } +} + +export async function waitForChildExit(child: ChildProcess): Promise { + if (child.exitCode !== null) return child.exitCode; + return new Promise((resolve, reject) => { + child.once("error", reject); + child.once("exit", resolve); + }); +} + +export function createOrdinaryExecReleaseSleeper( + releasePath: string, + waitBuffer: Int32Array, +): { + readonly sleep: (milliseconds: number) => void; + readonly wasReleased: () => boolean; +} { + let released = false; + return { + sleep: (milliseconds) => { + if (!released) { + createReleaseMarker(releasePath); + released = true; + } + Atomics.wait(waitBuffer, 0, 0, Math.min(milliseconds, 50)); + }, + wasReleased: () => released, + }; +} + +export async function releaseAndStopChild(child: ChildProcess, releasePath: string): Promise { + try { + createReleaseMarker(releasePath); + } finally { + if (child.exitCode === null) child.kill("SIGKILL"); + await waitForChildExit(child).catch(() => null); + } +} + +export function createPersistedLifecycleStoreOrThrow( + stateMutationGate: { readonly storeError?: Error } | undefined, +): Record { + if (stateMutationGate?.storeError) throw stateMutationGate.storeError; + return {}; +} diff --git a/test/helpers/runtime-provider-state-mutation-test-helpers.ts b/test/helpers/runtime-provider-state-mutation-test-helpers.ts new file mode 100644 index 00000000000..3a018172158 --- /dev/null +++ b/test/helpers/runtime-provider-state-mutation-test-helpers.ts @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { RuntimeProviderStateMutationPlan } from "../../src/lib/onboard/runtime-provider/contract"; + +type ProtectionTransitionPlan = Extract< + RuntimeProviderStateMutationPlan, + { readonly intent: "protection-transition" } +>; + +export function requireProtectionTransitionPlan( + plan: RuntimeProviderStateMutationPlan, +): ProtectionTransitionPlan { + if (plan.intent !== "protection-transition") { + throw new Error("expected protection-transition plan"); + } + return plan; +} diff --git a/test/helpers/shields-flow-harness.ts b/test/helpers/shields-flow-harness.ts index 9e6c4927c97..e4b3b2689d0 100644 --- a/test/helpers/shields-flow-harness.ts +++ b/test/helpers/shields-flow-harness.ts @@ -52,6 +52,8 @@ export type ShieldsFlowHarnessOptions = { detail: string; }>; processStartIdentity?: string; + timerAuthorizationOutcome?: "authorized" | "dies-before-proof"; + timerDiesAfterUnlock?: boolean; fork?: (...args: unknown[]) => { pid: number; disconnect: () => void; @@ -108,6 +110,31 @@ export function managedMcpSandbox( }; } +export function writeShieldsTimerAuthorizationProof( + requireDist: NodeRequire, + sandboxName: string, +): void { + const timerControl = requireDist( + "./timer-control.js", + ) as typeof import("../../src/lib/shields/timer-control.js"); + const marker = timerControl.readTimerMarker(sandboxName); + if (!marker?.processToken || !marker.timerProcessStartIdentity) { + throw new Error("Test timer marker is missing exact proof authority"); + } + fs.writeFileSync( + timerControl.timerAuthorizationProofPath(sandboxName, marker.processToken), + JSON.stringify({ + schemaVersion: 1, + pid: marker.pid, + sandboxName, + processToken: marker.processToken, + timerProcessStartIdentity: marker.timerProcessStartIdentity, + authoritySha256: timerControl.timerAuthoritySha256(marker), + }), + { mode: 0o600 }, + ); +} + function throwHarnessError(error: Error): never { throw error; } @@ -132,11 +159,46 @@ export function createShieldsFlowHarness( const timerControl = requireDist( "./timer-control.js", ) as typeof import("../../src/lib/shields/timer-control.js"); - if (options.processStartIdentity !== undefined) { - vi.spyOn(timerControl, "readProcessStartIdentity").mockReturnValue( - options.processStartIdentity, - ); - } + const readProcessStartIdentity = vi.isMockFunction(timerControl.readProcessStartIdentity) + ? (vi.mocked(timerControl.readProcessStartIdentity).getMockImplementation() ?? + timerControl.readProcessStartIdentity) + : timerControl.readProcessStartIdentity; + const isProcessAlive = vi.isMockFunction(timerControl.isProcessAlive) + ? (vi.mocked(timerControl.isProcessAlive).getMockImplementation() ?? + timerControl.isProcessAlive) + : timerControl.isProcessAlive; + const verifyTimerMarkerIdentity = vi.isMockFunction(timerControl.verifyTimerMarkerIdentity) + ? (vi.mocked(timerControl.verifyTimerMarkerIdentity).getMockImplementation() ?? + timerControl.verifyTimerMarkerIdentity) + : timerControl.verifyTimerMarkerIdentity; + const forkTimer = + options.fork ?? + (() => ({ + pid: 4242, + disconnect: () => undefined, + unref: () => undefined, + send: () => true, + kill: () => true, + })); + let fakeTimerPid: number | undefined; + let fakeTimerAlive = true; + vi.spyOn(timerControl, "readProcessStartIdentity").mockImplementation((pid: number) => + pid === fakeTimerPid + ? fakeTimerAlive + ? (options.processStartIdentity ?? "test-process-start-identity") + : null + : (options.processStartIdentity ?? readProcessStartIdentity(pid)), + ); + vi.spyOn(timerControl, "isProcessAlive").mockImplementation((pid: number) => + pid === fakeTimerPid ? fakeTimerAlive : isProcessAlive(pid), + ); + vi.spyOn(timerControl, "verifyTimerMarkerIdentity").mockImplementation((marker) => + marker.pid === fakeTimerPid + ? fakeTimerAlive + ? { verified: true } + : { verified: false, warning: "fake timer exited" } + : verifyTimerMarkerIdentity(marker), + ); const lifecycleLock = requireDist( "../state/mcp-lifecycle-lock.js", ) as typeof import("../../src/lib/state/mcp-lifecycle-lock.js"); @@ -177,7 +239,44 @@ export function createShieldsFlowHarness( 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(childProcess, "fork").mockImplementation((...args: unknown[]) => { + const child = forkTimer(...args); + const timerArgs = Array.isArray(args[1]) ? args[1] : []; + const timerSandboxName = String(timerArgs[0] ?? "openclaw"); + fakeTimerPid = child.pid; + const send = child.send as (message?: unknown) => boolean; + return { + ...child, + send: (message?: unknown) => { + const sent = send(message); + const request = message as { type?: unknown; processToken?: unknown } | undefined; + if (sent && request?.type === "authorize" && typeof request.processToken === "string") { + if (options.timerAuthorizationOutcome === "dies-before-proof") { + fakeTimerAlive = false; + return sent; + } + const marker = timerControl.readTimerMarker(timerSandboxName); + if (marker?.processToken === request.processToken && marker.timerProcessStartIdentity) { + fs.writeFileSync( + timerControl.timerAuthorizationProofPath(timerSandboxName, request.processToken), + JSON.stringify({ + schemaVersion: 1, + pid: marker.pid, + sandboxName: marker.sandboxName, + processToken: request.processToken, + timerProcessStartIdentity: marker.timerProcessStartIdentity, + authoritySha256: timerControl.timerAuthoritySha256(marker), + }), + { mode: 0o600 }, + ); + } + } + return sent; + }, + }; + }); + } vi.spyOn(policy, "buildPolicyGetCommand").mockReturnValue(["openshell", "policy", "get"]); vi.spyOn(policy, "buildPolicySetCommand").mockImplementation((file: unknown) => { recordPolicySetBody(policySetBodies, file); @@ -266,6 +365,9 @@ export function createShieldsFlowHarness( : openClawGuard && (action === "unlock" || action === "unlock-failed-startup") ? "mutable" : openClawPosture; + if (openClawGuard && action === "unlock" && options.timerDiesAfterUnlock) { + fakeTimerAlive = false; + } const successResult = { status: 0, signal: null, @@ -349,19 +451,8 @@ export function createShieldsFlowHarness( }, ); - if (options.failPolicyRejectionStateClear) { + if (options.failPolicyRejectionStateClear || options.failPolicyRejectionTransitionWrite) { const statePath = path.join(tmpDir, ".nemoclaw", "state", "shields-openclaw.json"); - const originalWriteFileSync = fs.writeFileSync.bind(fs); - let stateWrites = 0; - vi.spyOn(fs, "writeFileSync").mockImplementation(((file, data, writeOptions) => { - if (String(file) === statePath && ++stateWrites === 2) { - throw new Error("state cleanup denied"); - } - return originalWriteFileSync(file, data, writeOptions); - }) as typeof fs.writeFileSync); - } - - if (options.failPolicyRejectionTransitionWrite) { const transitionPrefix = path.join( tmpDir, ".nemoclaw", @@ -369,9 +460,22 @@ export function createShieldsFlowHarness( "shields-transition-openclaw-", ); const originalRenameSync = fs.renameSync.bind(fs); + let stateWrites = 0; let transitionWrites = 0; vi.spyOn(fs, "renameSync").mockImplementation((oldPath, newPath) => { - if (String(newPath).startsWith(transitionPrefix) && ++transitionWrites === 2) { + const destination = String(newPath); + if ( + options.failPolicyRejectionStateClear && + destination === statePath && + ++stateWrites === 2 + ) { + throw new Error("state cleanup denied"); + } + if ( + options.failPolicyRejectionTransitionWrite && + destination.startsWith(transitionPrefix) && + ++transitionWrites === 2 + ) { throw new Error("transition update denied"); } return originalRenameSync(oldPath, newPath); diff --git a/test/hermes-config-transaction-wiring.test.ts b/test/hermes-config-transaction-wiring.test.ts index 5cbf79a7943..06d09c2598c 100644 --- a/test/hermes-config-transaction-wiring.test.ts +++ b/test/hermes-config-transaction-wiring.test.ts @@ -52,6 +52,7 @@ installMock(source("sandbox", "privileged-exec.js"), { capturedPrivilegedExec = { command, sanitizeEnvironment }; return ["docker", "exec", ...(stdin ? ["-i"] : []), sandboxName, ...command]; }, + withPrivilegedSandboxExecutionLease: (_sandboxName, _operation, callback) => callback(), }); installMock(source("adapters", "docker", "exec.js"), { dockerExecFileSync: (argv, options) => { diff --git a/test/hermes-doctor-config-hash.test.ts b/test/hermes-doctor-config-hash.test.ts index 6ec5ca3c6f4..d59beea79e7 100644 --- a/test/hermes-doctor-config-hash.test.ts +++ b/test/hermes-doctor-config-hash.test.ts @@ -120,6 +120,19 @@ describe("Hermes doctor and config hash boundary", () => { "openshell-child-visible-credentials.v0.0.101.json", ); const stateLockPlanPath = path.join(tmp, "state-lock-plan.json"); + const runtimeStateMutationControlPath = path.join(libDir, "runtime-state-mutation-control.py"); + const runtimeStateMutationStartupGatePath = path.join( + libDir, + "runtime-state-mutation-startup-gate.py", + ); + const runtimeStateMutationPublisherPath = path.join( + libDir, + "runtime_state_mutation_hermes_publisher.py", + ); + const runtimeStateMutationCapabilityPath = path.join( + tmp, + "runtime-state-mutation-publisher-v1.json", + ); const hermesCronRestoreControlPath = path.join(libDir, "hermes-cron-restore-control.py"); const nestedDir = path.join(preloadsDir, "nested"); const profileDir = path.join(tmp, "etc-profile.d"); @@ -153,7 +166,11 @@ describe("Hermes doctor and config hash boundary", () => { mcpConfigTransactionPath, mcpCredentialBoundaryPath, path.join(libDir, "state-dir-guard.py"), + runtimeStateMutationControlPath, + runtimeStateMutationStartupGatePath, + runtimeStateMutationPublisherPath, stateLockPlanPath, + runtimeStateMutationCapabilityPath, path.join(libDir, "managed-gateway-control.py"), hermesCronRestoreControlPath, path.join(libDir, "sandbox-rlimits.sh"), @@ -164,6 +181,10 @@ describe("Hermes doctor and config hash boundary", () => { fs.mkdirSync(path.dirname(relativePath), { recursive: true }); fs.writeFileSync(relativePath, "test\n", { mode: 0o666 }); } + fs.writeFileSync(runtimeStateMutationControlPath, "# controller fixture\n"); + fs.writeFileSync(runtimeStateMutationStartupGatePath, "# startup gate fixture\n"); + fs.writeFileSync(runtimeStateMutationPublisherPath, "# publisher fixture\n"); + fs.writeFileSync(path.join(libDir, "hermes-runtime-config-guard.py"), "# guard fixture\n"); const lockCommand = dockerRunCommandBetween( dockerfile, @@ -172,7 +193,12 @@ describe("Hermes doctor and config hash boundary", () => { ) .replaceAll("/usr/local/bin", binDir) .replaceAll("/usr/local/lib/nemoclaw", libDir) + .replaceAll("/opt/hermes/.venv/bin/python3", "python3") .replaceAll("/usr/local/share/nemoclaw/state-lock-plan.json", stateLockPlanPath) + .replaceAll( + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json", + runtimeStateMutationCapabilityPath, + ) .replaceAll("/etc/profile.d", profileDir) .replaceAll("/etc/bash.bashrc", bashrcPath); const script = [ @@ -191,7 +217,7 @@ describe("Hermes doctor and config hash boundary", () => { 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")} ${stateLockPlanPath} ${path.join(libDir, "managed-gateway-control.py")} ${buildMcpDigestPath} ${hermesCronRestoreControlPath} ${mcpCredentialBoundaryPath}`, + `root:root ${path.join(binDir, "nemoclaw-gateway-control")} ${path.join(libDir, "gateway-supervisor.sh")} ${path.join(libDir, "state-dir-guard.py")} ${runtimeStateMutationControlPath} ${runtimeStateMutationStartupGatePath} ${runtimeStateMutationPublisherPath} ${stateLockPlanPath} ${runtimeStateMutationCapabilityPath} ${path.join(libDir, "managed-gateway-control.py")} ${buildMcpDigestPath} ${hermesCronRestoreControlPath} ${mcpCredentialBoundaryPath}`, `-R 0:0 ${preloadsDir}`, "", ].join("\n"), @@ -208,7 +234,11 @@ describe("Hermes doctor and config hash boundary", () => { expect(mode(buildMcpDigestPath)).toBe("444"); expect(mode(path.join(libDir, "gateway-supervisor.sh"))).toBe("444"); expect(mode(path.join(libDir, "state-dir-guard.py"))).toBe("500"); + expect(mode(runtimeStateMutationControlPath)).toBe("500"); + expect(mode(runtimeStateMutationStartupGatePath)).toBe("555"); + expect(mode(runtimeStateMutationPublisherPath)).toBe("500"); expect(mode(stateLockPlanPath)).toBe("444"); + expect(mode(runtimeStateMutationCapabilityPath)).toBe("444"); expect(mode(path.join(libDir, "managed-gateway-control.py"))).toBe("500"); expect(mode(preloadsDir)).toBe("755"); expect(mode(nestedDir)).toBe("755"); diff --git a/test/hermes-final-image-layout.test.ts b/test/hermes-final-image-layout.test.ts index a94567dd52d..c5643b4f692 100644 --- a/test/hermes-final-image-layout.test.ts +++ b/test/hermes-final-image-layout.test.ts @@ -299,7 +299,11 @@ describe("Hermes final image layout", () => { "COPY agents/hermes/cron-restore-control.py /usr/local/lib/nemoclaw/hermes-cron-restore-control.py", "COPY src/lib/actions/sandbox/openshell-child-visible-credentials.v0.0.101.json /usr/local/lib/nemoclaw/openshell-child-visible-credentials.v0.0.101.json", "COPY scripts/state-dir-guard.py /usr/local/lib/nemoclaw/state-dir-guard.py", + "COPY scripts/runtime-state-mutation-control.py /usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + "COPY scripts/runtime-state-mutation-startup-gate.py /usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py", + "COPY scripts/runtime_state_mutation_hermes_publisher.py /usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py", "COPY agents/hermes/state-lock-plan.json /usr/local/share/nemoclaw/state-lock-plan.json", + "COPY agents/hermes/runtime-state-mutation-publisher-v1.json /usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json", "COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/", ], }, @@ -450,6 +454,12 @@ describe("Hermes final image layout", () => { "/usr/local/lib/nemoclaw/hermes-cron-restore-control.py 'root:root 700'", "/sandbox/.nemoclaw 'root:root 1755'", "/usr/local/share/nemoclaw/state-lock-plan.json 'root:root 444'", + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py 'root:root 500'", + "/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py 'root:root 555'", + "/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py 'root:root 500'", + "/var/lib/nemoclaw/runtime-state-mutation 'root:root 711'", + "/run/nemoclaw/runtime-state-mutation-startup 'root:root 711'", + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json 'root:root 444'", "/usr/local/lib/nemoclaw/preloads/sandbox-safety-net.js 'root:root 444'", "/usr/local/lib/nemoclaw/hermes-wrapper.py 'root:root 755'", "/usr/local/lib/nemoclaw/validate-hermes-cli-adapter.py 'root:root 755'", @@ -457,6 +467,16 @@ describe("Hermes final image layout", () => { ]) { expect(finalStage).toContain(`check_metadata ${metadataContract}`); } + expect(finalStage).toContain("/opt/hermes/.venv/bin/python3 -I -c 'import runpy, yaml;"); + expect(finalStage).toContain( + 'runpy.run_path("/usr/local/lib/nemoclaw/runtime-state-mutation-control.py"', + ); + expect(finalStage).toContain( + 'runpy.run_path("/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"', + ); + expect(finalStage).toContain( + 'runpy.run_path("/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py"', + ); expect(doctorLayer).toContain( "HERMES_HOME=/sandbox/.hermes /usr/local/bin/hermes doctor --fix", ); diff --git a/test/hermes-gateway-supervisor-recovery.test.ts b/test/hermes-gateway-supervisor-recovery.test.ts index aa9b0da218f..0e5f23988ba 100644 --- a/test/hermes-gateway-supervisor-recovery.test.ts +++ b/test/hermes-gateway-supervisor-recovery.test.ts @@ -117,6 +117,7 @@ function runHermesStartupReadiness(gatewayInitStatus: 0 | 1) { '_HERMES_PYTHON="hermes-python"', '_HERMES_RUNTIME_CONFIG_GUARD="runtime-guard"', 'hermes-python() { printf "publish:%s\\n" "$*" >&2; return 0; }', + 'nemoclaw_runtime_state_mutation_checkpoint() { printf "state-mutation-checkpoint\\n" >&2; }', "print_dashboard_urls() { trace dashboard-urls; }", block, ]); @@ -128,6 +129,7 @@ describe("Hermes PID 1 supervisor recovery", () => { expect(result.status, result.stderr).toBe(0); expect(result.stdout.trim().split("\n")).toEqual(["gateway-control-init", "dashboard-urls"]); + expect(result.stderr).toContain("state-mutation-checkpoint"); expect(result.stderr).toContain( "publish:-I runtime-guard publish-startup-ready --hermes-dir /sandbox/.hermes --startup-owner", ); @@ -613,8 +615,10 @@ describe("Hermes supervised auxiliary recovery", () => { '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; }", + "finalize_tirith_marker_retry() { :; }", "commit_hermes_mcp_applied_if_pending() { return 0; }", 'refresh_hermes_supervised_child_pids() { trace "refresh:$GATEWAY_PID"; }', + "nemoclaw_runtime_state_mutation_checkpoint() { :; }", "hermes_gateway_healthy() { return 0; }", 'hermes_stop_tracked_role() { trace "unexpected-stop:$2"; return 1; }', extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), @@ -775,8 +779,10 @@ describe("Hermes supervised auxiliary recovery", () => { "hermes_tracked_role_is_current() { return 0; }", "hermes_gateway_healthy() { return 0; }", "ensure_hermes_supervised_auxiliaries() { return 0; }", + "finalize_tirith_marker_retry() { :; }", "commit_hermes_mcp_applied_if_pending() { return 0; }", "refresh_hermes_supervised_child_pids() { trace refresh; }", + "nemoclaw_runtime_state_mutation_checkpoint() { :; }", 'date() { trace unexpected-exit-record; printf "100\\n"; }', 'sleep() { trace "sleep:$1"; }', extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), @@ -817,6 +823,7 @@ describe("Hermes supervised auxiliary recovery", () => { '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"; }', + "nemoclaw_runtime_state_mutation_checkpoint() { :; }", 'date() { printf "100\\n"; }', 'sleep() { trace "sleep:$1"; }', extractShellFunction(source, "quarantine_hermes_managed_gateway_relaunch"), diff --git a/test/hermes-start.test.ts b/test/hermes-start.test.ts index 4f94c8426db..86ebe1f5a99 100644 --- a/test/hermes-start.test.ts +++ b/test/hermes-start.test.ts @@ -11,6 +11,7 @@ import { shellQuote } from "../src/lib/core/shell-quote"; import { bashPrintfQ, extractShellFunction as extractShellFunctionFromSource, + runHermesSandboxInitPreludeWithFakePath, } from "./support/hermes-shell-harness"; const START_SCRIPT = path.join(import.meta.dirname, "..", "agents", "hermes", "start.sh"); @@ -408,69 +409,6 @@ function runTirithFinalizerPathResolution(installed: boolean) { } } -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"); - fs.mkdirSync(fakeBin, { recursive: true }); - fs.writeFileSync( - path.join(fakeBin, "dirname"), - ["#!/usr/bin/env bash", `printf called > ${shellQuote(marker)}`, "exit 99"].join("\n"), - { mode: 0o700 }, - ); - fs.writeFileSync( - fakeInit, - [ - `printf "%s\\n" "$PATH" > ${shellQuote(sourcePathLog)}`, - "harden_resource_limits() { :; }", - ].join("\n"), - ); - fs.writeFileSync(fakeSupervisor, "# supervisor fixture\n"); - - const src = fs.readFileSync(START_SCRIPT, "utf-8"); - const start = src.indexOf( - "# SECURITY: Lock down PATH before resolving or sourcing root startup helpers.", - ); - const end = src.indexOf("\nif [ -d /opt/hermes/hermes_cli/web_dist ];", start); - const prelude = src - .slice(start, end) - .replaceAll("/usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh", ENV_WRAPPER) - .replaceAll("/usr/local/lib/nemoclaw/sandbox-init.sh", fakeInit) - .replaceAll("/usr/local/lib/nemoclaw/gateway-supervisor.sh", fakeSupervisor); - - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - "set -euo pipefail", - `export PATH=${shellQuote(`${fakeBin}:${process.env.PATH ?? ""}`)}`, - prelude, - ].join("\n"), - { mode: 0o700 }, - ); - - try { - const result = spawnSync("bash", [scriptPath], { - encoding: "utf-8", - timeout: 5000, - env: process.env, - }); - return { - result, - dirnameCalled: fs.existsSync(marker), - sourcePath: fs.existsSync(sourcePathLog) - ? fs.readFileSync(sourcePathLog, "utf-8").trim() - : "", - }; - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } -} - const LOCKED_HERMES_CONFIG_STAT_MOCK = [ "stat() {", ' if [ "${1:-}" = "-c" ] && [ "${2:-}" = "%U:%G" ] && [ "${3:-}" = "$HERMES_DIR" ]; then printf "root:root\\n"; return 0; fi', @@ -786,12 +724,30 @@ function runRuntimeShellEnvBootstrap() { describe("agents/hermes/start.sh sandbox init bootstrap", () => { it("locks the trusted PATH before sourcing shared sandbox init", () => { - const { result, dirnameCalled, sourcePath } = runHermesSandboxInitPreludeWithFakePath(); + const { result, dirnameCalled, sourcePath } = runHermesSandboxInitPreludeWithFakePath( + START_SCRIPT, + ENV_WRAPPER, + ); expect(result.status, result.stderr).toBe(0); expect(dirnameCalled).toBe(false); expect(sourcePath).toBe("/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); }); + + it("removes its temporary fixture when the prelude markers are absent", () => { + const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-missing-prelude-")); + const invalidStartScript = path.join(fixtureDir, "start.sh"); + fs.writeFileSync(invalidStartScript, "#!/usr/bin/env bash\n"); + + try { + expect(() => + runHermesSandboxInitPreludeWithFakePath(invalidStartScript, ENV_WRAPPER, fixtureDir), + ).toThrow("Hermes start.sh prelude markers not found"); + expect(fs.readdirSync(fixtureDir)).toEqual(["start.sh"]); + } finally { + fs.rmSync(fixtureDir, { recursive: true, force: true }); + } + }); }); describe("agents/hermes/start.sh runtime shell env", () => { diff --git a/test/install-npm-resolution.test.ts b/test/install-npm-resolution.test.ts index 56a14648022..50d35073815 100644 --- a/test/install-npm-resolution.test.ts +++ b/test/install-npm-resolution.test.ts @@ -1,10 +1,10 @@ // 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, expect, it } from "vitest"; @@ -171,6 +171,27 @@ function runVerifyNemoclaw( } describe("installer npm resolution", () => { + it("keeps an existing user-local npm PATH stable when fixing permissions", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-npm-path-")); + const fakeBin = path.join(tmp, "bin"); + const npmBin = path.join(tmp, ".npm-global", "bin"); + fs.mkdirSync(fakeBin, { recursive: true }); + fs.mkdirSync(npmBin, { recursive: true }); + writeExecutable(path.join(fakeBin, "uname"), "#!/usr/bin/env bash\nprintf 'Linux\\n'\n"); + writeExecutable( + path.join(fakeBin, "npm"), + '#!/usr/bin/env bash\nif [[ "$*" == "config get prefix" ]]; then printf \'/System/nemoclaw\\n\'; fi\n', + ); + const initialPath = [npmBin, fakeBin, TEST_SYSTEM_PATH].join(path.delimiter); + const result = runInstallerFunction('fix_npm_permissions; printf "%s\\n" "$PATH"', fakeBin, { + HOME: tmp, + PATH: initialPath, + }); + + expect(result.status, `${result.stdout}${result.stderr}`).toBe(0); + expect(result.stdout.trim().split("\n").at(-1)).toBe(initialPath); + }); + it("creates user-local shims for every packaged CLI alias during the default install path", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-package-shims-")); const fakeBin = path.join(tmp, "bin"); @@ -224,6 +245,68 @@ echo "${cliBin} v0.1.0" } }); + it("keeps PATH stable only when the generated shim resolves its selected Node", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-stable-shim-path-")); + const fakeBin = path.join(tmp, "bin"); + const prefix = path.join(tmp, "prefix"); + const prefixBin = path.join(prefix, "bin"); + fs.mkdirSync(fakeBin); + fs.mkdirSync(prefixBin, { recursive: true }); + + writeExecutable(path.join(fakeBin, "node"), "#!/usr/bin/env bash\nexit 0\n"); + writeExecutable( + path.join(fakeBin, "npm"), + `#!/usr/bin/env bash +if [ "$1" = "config" ] && [ "$2" = "get" ] && [ "$3" = "prefix" ]; then + echo "$ACTIVE_NPM_PREFIX" + exit 0 +fi +exit 99 +`, + ); + writeExecutable( + path.join(prefixBin, "nemoclaw"), + "#!/usr/bin/env bash\nprintf '%s\\n' \"$PATH\"\n", + ); + const initialPath = [path.join(tmp, "first"), fakeBin, TEST_SYSTEM_PATH].join(path.delimiter); + const create = runInstallerFunction('_CLI_BIN=nemoclaw; ensure_cli_shim "nemoclaw"', fakeBin, { + ACTIVE_NPM_PREFIX: prefix, + HOME: tmp, + PATH: initialPath, + }); + expect(create.status, `${create.stdout}${create.stderr}`).toBe(0); + + const shimPath = path.join(tmp, ".local", "bin", "nemoclaw"); + const existingNodePath = spawnSync(BASH_BIN, [shimPath], { + encoding: "utf-8", + env: { ...process.env, HOME: tmp, PATH: initialPath }, + }); + expect(existingNodePath.status, `${existingNodePath.stdout}${existingNodePath.stderr}`).toBe(0); + expect(existingNodePath.stdout.trim()).toBe(initialPath); + + const shadowBin = path.join(tmp, "shadow-bin"); + fs.mkdirSync(shadowBin); + writeExecutable(path.join(shadowBin, "node"), "#!/usr/bin/env bash\nexit 0\n"); + const shadowedPath = `${shadowBin}${path.delimiter}${initialPath}`; + const repairedShadowedPath = spawnSync(BASH_BIN, [shimPath], { + encoding: "utf-8", + env: { ...process.env, HOME: tmp, PATH: shadowedPath }, + }); + expect( + repairedShadowedPath.status, + `${repairedShadowedPath.stdout}${repairedShadowedPath.stderr}`, + ).toBe(0); + expect(repairedShadowedPath.stdout.trim()).toBe(`${fakeBin}${path.delimiter}${shadowedPath}`); + + const missingNodePath = TEST_SYSTEM_PATH; + const repairedNodePath = spawnSync(BASH_BIN, [shimPath], { + encoding: "utf-8", + env: { ...process.env, HOME: tmp, PATH: missingNodePath }, + }); + expect(repairedNodePath.status, `${repairedNodePath.stdout}${repairedNodePath.stderr}`).toBe(0); + expect(repairedNodePath.stdout.trim()).toBe(`${fakeBin}${path.delimiter}${missingNodePath}`); + }); + it("prefers the active npm on PATH over a hostile nvm environment", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-path-npm-")); const fakeBin = path.join(tmp, "bin"); diff --git a/test/install-preflight.test.ts b/test/install-preflight.test.ts index c9322c33378..d6b7058f56f 100644 --- a/test/install-preflight.test.ts +++ b/test/install-preflight.test.ts @@ -2710,18 +2710,18 @@ exit 1 const openshell = path.join(localBin, "openshell"); fs.mkdirSync(localBin, { recursive: true }); writeExecutable(openshell, "#!/usr/bin/env bash\nexit 0\n"); - const r = callInstallerPayloadFn( - 'prefer_user_local_openshell; printf "%s\\n%s\\n" "$NEMOCLAW_OPENSHELL_BIN" "$PATH"', + 'prefer_user_local_openshell; initial="$PATH"; prefer_user_local_openshell; printf "%s\\n%s\\n%s\\n" "$NEMOCLAW_OPENSHELL_BIN" "$initial" "$PATH"', { HOME: tmp, PATH: "/opt/homebrew/bin:/usr/bin:/bin", }, ); - const [resolved, pathValue] = r.stdout.trim().split("\n"); + const [resolved, initialPath, pathValue] = r.stdout.trim().split("\n"); expect(r.status).toBe(0); expect(resolved).toBe(openshell); expect(pathValue.startsWith(`${localBin}:`)).toBe(true); + expect(pathValue).toBe(initialPath); }); it("restore_onboard_forward_after_post_checks: restores Hermes forward from session", () => { diff --git a/test/llama-cpp-dgx-spark-qualification-runner.test.ts b/test/llama-cpp-dgx-spark-qualification-runner.test.ts index c382a81ccb1..147d224d983 100644 --- a/test/llama-cpp-dgx-spark-qualification-runner.test.ts +++ b/test/llama-cpp-dgx-spark-qualification-runner.test.ts @@ -21,6 +21,7 @@ import { parseQualificationInvocation, type QualificationInvocation, type QualificationPlan, + qualifyDockerLoopbackPublishAuthority, sha256Text, validateCandidateDockerfile, validateChatCompletionResponse, @@ -30,6 +31,10 @@ import { validateRuntimeLogRedaction, validateStartupLog, } from "../scripts/checks/run-llama-cpp-dgx-spark-qualification.mts"; +import { + consumeDockerLoopbackPublishAuthority, + type DockerLoopbackPublishAuthority, +} from "../src/lib/inference/llama-cpp/host-local-runtime"; const BASE_SHA = "b".repeat(40); const HEAD_SHA = "a".repeat(40); @@ -45,6 +50,9 @@ const config = loadLlamaCppImageConfig(); const planSource = config.publication_qualification_plan; const planDigest = config.publication_qualification_plan_sha256; const plan = validateQualificationPlan(planSource, planDigest); +function loopbackPublishAuthority(): ReturnType { + return qualifyDockerLoopbackPublishAuthority("28.3.3"); +} function trustedEnvironment(overrides: Record = {}) { return { @@ -123,6 +131,38 @@ function qualificationPlanForModel(content: Buffer): QualificationPlan { } describe("trusted llama.cpp DGX Spark qualification runner", () => { + it("requires a patched live Docker server before loopback publication (#8260)", () => { + for (const version of ["27.5.1", "28.0.0", "28.3.2", "28.3.3-rc.1", "", "client 29.0.0"]) { + expect(() => qualifyDockerLoopbackPublishAuthority(version)).toThrow( + /Docker Engine 28\.3\.3 or newer/u, + ); + } + expect(qualifyDockerLoopbackPublishAuthority("28.3.3\n").serverVersion).toBe("28.3.3"); + expect(qualifyDockerLoopbackPublishAuthority("28.3.3+ubuntu.1").serverVersion).toBe( + "28.3.3+ubuntu.1", + ); + expect(qualifyDockerLoopbackPublishAuthority("29.0.0").serverVersion).toBe("29.0.0"); + + const singleUseAuthority = qualifyDockerLoopbackPublishAuthority("28.3.3"); + for (const clonedAuthority of [ + Object.create(singleUseAuthority), + Object.assign({}, singleUseAuthority), + ] as DockerLoopbackPublishAuthority[]) { + expect(() => consumeDockerLoopbackPublishAuthority(clonedAuthority)).toThrow( + /authority is invalid/u, + ); + } + expect(() => consumeDockerLoopbackPublishAuthority(singleUseAuthority)).not.toThrow(); + expect(() => consumeDockerLoopbackPublishAuthority(singleUseAuthority)).toThrow( + /already consumed/u, + ); + expect(() => + consumeDockerLoopbackPublishAuthority({ + serverVersion: "29.0.0", + } as DockerLoopbackPublishAuthority), + ).toThrow(/authority is invalid/u); + }); + it("accepts only the canonical digest-bound declarative execution plan (#8260)", () => { expect(plan.contractVersion).toBe(1); expect(plan.recipe.id).toBe("llama-cpp.nemotron-3-nano-30b-a3b.spark-single.v1"); @@ -312,7 +352,10 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { runtimeGid: 1001, runtimeUid: 1001, } as const; - const argv = buildServerContainerArgv(testPlan, containerOptions); + const argv = buildServerContainerArgv(testPlan, { + ...containerOptions, + loopbackPublishAuthority: loopbackPublishAuthority(), + }); expect(argv).toEqual( expect.arrayContaining([ "--read-only", @@ -383,6 +426,7 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { const agentQualificationArgv = buildServerContainerArgv(testPlan, { ...containerOptions, hostPort: testPlan.recipe.serve.port, + loopbackPublishAuthority: loopbackPublishAuthority(), }); expect(valuesAfter(agentQualificationArgv, "--publish")).toEqual([ `127.0.0.1:${String(testPlan.recipe.serve.port)}:${String(testPlan.recipe.serve.port)}`, @@ -396,7 +440,10 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { serve: { ...testPlan.recipe.serve, port: alternateContainerPort }, }, } as unknown as QualificationPlan; - const alternatePortArgv = buildServerContainerArgv(alternatePortPlan, containerOptions); + const alternatePortArgv = buildServerContainerArgv(alternatePortPlan, { + ...containerOptions, + loopbackPublishAuthority: loopbackPublishAuthority(), + }); expect(valuesAfter(alternatePortArgv, "--publish")).toEqual([ `127.0.0.1::${String(alternateContainerPort)}`, ]); @@ -436,6 +483,7 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { registryOwner: expectedRegistryOwner(RUN_ID, RUN_ATTEMPT), runtimeGid: 1001, runtimeUid: 0, + loopbackPublishAuthority: loopbackPublishAuthority(), }), ).toThrow(/runtime uid/u); } finally { @@ -446,19 +494,40 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { it("rejects Docker publish aliases before inserting one loopback mapping at the image boundary (#8667)", () => { const imageReference = `localhost:5000/repo@sha256:${"d".repeat(64)}`; const containerPort = 9_081; - const options = { containerPort, imageReference }; - - expect(insertQualificationLoopbackPublishArgv(["run", imageReference], options)).toEqual([ - "run", - "--publish", - `127.0.0.1::${String(containerPort)}`, + const options = () => ({ + containerPort, imageReference, - ]); - expect(() => insertQualificationLoopbackPublishArgv(["run"], options)).toThrow( - /exactly one Docker image reference/u, - ); + loopbackPublishAuthority: loopbackPublishAuthority(), + }); + const consumedAuthority = loopbackPublishAuthority(); + + expect( + insertQualificationLoopbackPublishArgv(["run", imageReference], { + ...options(), + loopbackPublishAuthority: consumedAuthority, + }), + ).toEqual(["run", "--publish", `127.0.0.1::${String(containerPort)}`, imageReference]); expect(() => - insertQualificationLoopbackPublishArgv(["run", imageReference, imageReference], options), + insertQualificationLoopbackPublishArgv(["run", imageReference], { + ...options(), + loopbackPublishAuthority: consumedAuthority, + }), + ).toThrow(/already consumed/u); + const authorityAfterRejectedBoundary = loopbackPublishAuthority(); + expect(() => + insertQualificationLoopbackPublishArgv(["run"], { + ...options(), + loopbackPublishAuthority: authorityAfterRejectedBoundary, + }), + ).toThrow(/exactly one Docker image reference/u); + expect( + insertQualificationLoopbackPublishArgv(["run", imageReference], { + ...options(), + loopbackPublishAuthority: authorityAfterRejectedBoundary, + }), + ).toEqual(["run", "--publish", `127.0.0.1::${String(containerPort)}`, imageReference]); + expect(() => + insertQualificationLoopbackPublishArgv(["run", imageReference, imageReference], options()), ).toThrow(/exactly one Docker image reference/u); for (const publishArgv of [ ["--publish", "0.0.0.0:8081:8081"], @@ -471,11 +540,14 @@ describe("trusted llama.cpp DGX Spark qualification runner", () => { ["-P=true"], ]) { expect(() => - insertQualificationLoopbackPublishArgv(["run", ...publishArgv, imageReference], options), + insertQualificationLoopbackPublishArgv(["run", ...publishArgv, imageReference], options()), ).toThrow(/must not publish/u); } expect( - insertQualificationLoopbackPublishArgv(["run", imageReference, "-p", "guard-value"], options), + insertQualificationLoopbackPublishArgv( + ["run", imageReference, "-p", "guard-value"], + options(), + ), ).toEqual([ "run", "--publish", diff --git a/test/managed-image-protected-runtime-contract.test.ts b/test/managed-image-protected-runtime-contract.test.ts index 87c4b987029..acc546bd1fa 100644 --- a/test/managed-image-protected-runtime-contract.test.ts +++ b/test/managed-image-protected-runtime-contract.test.ts @@ -17,6 +17,8 @@ import { withManagedImageLocalInferenceProfile, } from "../scripts/checks/managed-image-protected-runtime-contract.ts"; import { + createProtectedManagedImageBootstrapInput, + MANAGED_IMAGE_OPENSHELL_SUPERVISOR_ARGV, managedImageLocalInferenceBaseUrl, managedImageOpenShellBasePolicyPath, managedImageOpenShellCommittedProbe, @@ -25,11 +27,50 @@ import { removeManagedImageGatewayStateIfSafe, resolveManagedImageOnboardModule, } from "../scripts/checks/run-managed-image-openshell-e2e.ts"; +import { resolveOnboardManagedBootstrapLaunch } from "../src/lib/onboard/managed-workload/onboard-orchestration.js"; const IMAGE = `localhost:5000/nemoclaw-managed-protected/openclaw@sha256:${"a".repeat(64)}`; const VALID_SANDBOX = "managed-openclaw"; describe("protected managed-image runtime contract", () => { + it("binds the public and protected managed-image plans to one supervisor argv (#7744)", () => { + const authorityStore = {}; + const publicLaunch = resolveOnboardManagedBootstrapLaunch({ + runtime: { + runtimeProvider: { + bootstrap: { + supported: true, + createAuthorityStore: () => authorityStore, + }, + }, + } as never, + workload: { + source: { + kind: "managed-image", + contract: { + agent: "openclaw", + image: "registry.example/nemoclaw/openclaw", + digest: `sha256:${"a".repeat(64)}`, + }, + }, + } as never, + stateRoot: "/tmp/nemoclaw-state", + bootstrapIdentity: "bootstrap-identity", + request: {} as never, + intendedWorkloadArgv: ["/usr/local/bin/nemoclaw-start"], + })!; + const protectedLaunch = createProtectedManagedImageBootstrapInput(publicLaunch); + + expect(protectedLaunch.expectedSupervisorArgv).toBe(publicLaunch.expectedSupervisorArgv); + expect(protectedLaunch.expectedSupervisorArgv).toBe(MANAGED_IMAGE_OPENSHELL_SUPERVISOR_ARGV); + expect(protectedLaunch.expectedSupervisorArgv).toEqual([ + "/opt/openshell/bin/openshell-sandbox", + "--workdir", + "/sandbox", + ]); + expect(Object.isFrozen(protectedLaunch.expectedSupervisorArgv)).toBe(true); + }); + it("loads every OpenShell operation required before protected image launch (#7744)", async () => { const onboard = resolveManagedImageOnboardModule(await import("../src/lib/onboard.ts")); diff --git a/test/package-contract/cli/config-set-prompt-eof.test.ts b/test/package-contract/cli/config-set-prompt-eof.test.ts index 541b3bd7da2..6d2d366d3f1 100644 --- a/test/package-contract/cli/config-set-prompt-eof.test.ts +++ b/test/package-contract/cli/config-set-prompt-eof.test.ts @@ -85,6 +85,7 @@ function runConfigSetWithInput(input: string) { "install(" + PRIVILEGED_EXEC_PATH + ", {", ' privilegedSandboxExecArgv: () => ["docker", "exec", "container-id"],', ' resolveDirectSandboxContainer: () => "container-id",', + " withPrivilegedSandboxExecutionLease: (_sandboxName, _operation, callback) => callback(),", "});", "", 'Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true });', diff --git a/test/package-contract/installer-host-preflight.test.ts b/test/package-contract/installer-host-preflight.test.ts index 9ff2c522e78..2ebeed13be2 100644 --- a/test/package-contract/installer-host-preflight.test.ts +++ b/test/package-contract/installer-host-preflight.test.ts @@ -57,6 +57,10 @@ exports.assessHost = () => host; exports.planHostAdvisories = () => []; `, ); + fs.writeFileSync( + path.join(onboardDir, "gateway-management.js"), + `exports.loadGatewayManagementDeclaration = () => ({ ok: true, declaration: null });\n`, + ); fs.writeFileSync( path.join(readinessDir, "host.js"), `exports.createHostReadinessReport = (_options, collection) => { diff --git a/test/repro-2681-group-writable.test.ts b/test/repro-2681-group-writable.test.ts index b0f24434a4e..0c26b804578 100644 --- a/test/repro-2681-group-writable.test.ts +++ b/test/repro-2681-group-writable.test.ts @@ -163,6 +163,7 @@ function withMockedDockerExecFileSync( options: { hermesLockedTransaction?: boolean; installedStateLockPlan?: AgentStateLockPlan; + registryAgent?: "hermes" | "openclaw"; symlinkedPaths?: ReadonlySet; } = {}, ): T { @@ -173,6 +174,13 @@ function withMockedDockerExecFileSync( }; const originalDockerExecFileSync = dockerExecModule.dockerExecFileSync; const originalDockerSpawnSync = dockerExecModule.dockerSpawnSync; + // eslint-disable-next-line @typescript-eslint/no-require-imports + const registryModule = + require("../src/lib/state/registry.js") as typeof import("../src/lib/state/registry"); + const getSandboxSpy = vi.spyOn(registryModule, "getSandbox").mockReturnValue({ + agent: options.registryAgent ?? "openclaw", + name: "sandbox-pod", + } as never); const shieldsModulePath = require.resolve("../src/lib/shields/index.js"); const privilegedExecPath = require.resolve("../src/lib/sandbox/privileged-exec.js"); const transitionLockPath = require.resolve("../src/lib/shields/transition-lock.js"); @@ -189,6 +197,11 @@ function withMockedDockerExecFileSync( loaded: true, exports: { privilegedSandboxExecArgv: (_sandboxName: string, cmd: readonly string[]) => [...cmd], + withPrivilegedSandboxExecutionLease: ( + _sandboxName: string, + _operation: string, + fn: () => T, + ): T => fn(), }, } as any; require.cache[transitionLockPath] = { @@ -369,6 +382,7 @@ function withMockedDockerExecFileSync( } finally { dockerExecModule.dockerExecFileSync = originalDockerExecFileSync; dockerExecModule.dockerSpawnSync = originalDockerSpawnSync; + getSandboxSpy.mockRestore(); delete require.cache[shieldsModulePath]; restoreCachedModule(privilegedExecPath, priorPrivilegedExec); restoreCachedModule(transitionLockPath, priorTransitionLock); @@ -643,7 +657,7 @@ describe("mutable agent config permissions", () => { stateLockPlanInImage: true, }); }, - { installedStateLockPlan: HERMES_STATE_LOCK_PLAN }, + { installedStateLockPlan: HERMES_STATE_LOCK_PLAN, registryAgent: "hermes" }, ); const hermesActions = commands @@ -704,6 +718,7 @@ describe("mutable agent config permissions", () => { { hermesLockedTransaction: true, installedStateLockPlan: HERMES_STATE_LOCK_PLAN, + registryAgent: "hermes", }, ); @@ -831,6 +846,9 @@ Module._load = function patchedLoad(request, parent, isMain) { privilegedSandboxExecArgv(_sandboxName, cmd) { return [...cmd]; }, + withPrivilegedSandboxExecutionLease(_sandboxName, _operation, fn) { + return fn(); + }, }; } return originalLoad.call(this, request, parent, isMain); diff --git a/test/runtime-provider-source-shape.test.ts b/test/runtime-provider-source-shape.test.ts index 3ea1be5ee3a..cec2eb5f6c3 100644 --- a/test/runtime-provider-source-shape.test.ts +++ b/test/runtime-provider-source-shape.test.ts @@ -171,6 +171,8 @@ describe("runtime provider central source boundary", () => { "src/lib/onboard/runtime-provider/docker-llama-cpp-operation.ts", "src/lib/onboard/runtime-provider/docker-llama-cpp-private-bridge-process.ts", "src/lib/onboard/runtime-provider/docker-llama-cpp-private-bridge.ts", + "src/lib/onboard/runtime-provider/docker-operation-authority.ts", + "src/lib/onboard/runtime-provider/docker-state-mutation.ts", "src/lib/onboard/runtime-provider/docker.ts", "src/lib/onboard/runtime-provider/host-local-create-journal.ts", "src/lib/onboard/runtime-provider/host-local-inference.ts", diff --git a/test/runtime-state-mutation-control.test.ts b/test/runtime-state-mutation-control.test.ts new file mode 100644 index 00000000000..0458f341edf --- /dev/null +++ b/test/runtime-state-mutation-control.test.ts @@ -0,0 +1,1475 @@ +// 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 { beforeAll, describe, expect, it } from "vitest"; + +const CONTROLLER = path.join( + import.meta.dirname, + "..", + "scripts", + "runtime-state-mutation-control.py", +); + +const HARNESS = String.raw` +import importlib.util +import fcntl +import json +import os +import select +import signal +import stat +import subprocess +import sys +import tempfile +import time +import types + +spec = importlib.util.spec_from_file_location("runtime_state_control", sys.argv[1]) +control = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = control +spec.loader.exec_module(control) +control.ROOT_UID = os.getuid() +control.ROOT_GID = os.getgid() +control.POLL_SECONDS = 0 +control.STABLE_SCANS = 3 + +real_apply_plan_posture = control._apply_plan_posture +real_assert_private_procfs = control._assert_private_procfs +real_discover_fence = control._discover_fence +real_exclude_writers = control._exclude_writers +real_hold_exact_processes = control._hold_exact_processes +real_activate_exact = control._activate_exact +real_start_activation_guard = control._start_activation_guard +real_kernel_pid_namespace_stop = control._kernel_pid_namespace_stop +real_activation_attempt_pending = control._activation_attempt_pending +real_cleanup_activation_protocol = control._cleanup_activation_protocol +real_unlink_control_file = control._unlink_control_file +real_publish_activation_receipt = control._publish_activation_receipt +real_verify_activation_receipt = control._verify_activation_receipt +real_release_activation_hold = control._release_activation_hold +real_parse_proc_uids = control._parse_proc_uids +real_recapture_reference = control._recapture_reference +real_signal_exact_process = control._signal_exact_process +real_wait_for_reference_running = control._wait_for_reference_running +real_prove_fence_shape = control._prove_fence_shape +real_resume_reference = control._resume_reference +real_prove_released_activation = control._prove_released_activation +control._assert_private_procfs = lambda: None +control._open_activation_guard_pidfd = lambda _reference: os.open( + os.devnull, os.O_RDONLY +) + +def code(call): + try: + call() + except control.ControlError as error: + return error.code + return "ok" + +def plan(projection, intent="protection-transition"): + if intent != "protection-transition": + return { + "schemaVersion": 2, + "intent": intent, + "stateRoot": "/sandbox/.hermes", + "selectors": [{"kind": "path", "path": "config.yaml"}], + "projectionSha256": projection, + } + return { + "schemaVersion": 2, + "intent": "protection-transition", + "target": "locked", + "rollback": "mutable", + "stateLockPlan": { + "version": 1, + "readOnlyRoots": ["cron"], + "confidentialRoots": ["credentials"], + "readOnlyPrefixes": ["workspace-"], + "confidentialPrefixes": [], + "writableSubpaths": ["cron/scratch"], + }, + "stateRoot": "/sandbox/.hermes", + "selectors": [ + {"kind": "path", "path": ".config-hash"}, + {"kind": "path", "path": ".env"}, + {"kind": "path", "path": "config.yaml"}, + {"kind": "path", "path": "credentials"}, + {"kind": "path", "path": "cron"}, + {"kind": "prefix", "prefix": "workspace-"}, + ], + "projectionSha256": projection, + } + +def acquire_value(nonce="d" * 64, selected_plan=None, lifecycle_generation="generation:7"): + projection = "b" * 64 + selected = plan(projection) if selected_plan is None else selected_plan + serialized = control._json_bytes(selected).decode() + request = control.AcquireRequest( + "0" * 64, + "docker", + "alpha", + lifecycle_generation, + "3" * 64, + "1" * 64, + 4812, + "4" * 64, + "5" * 64, + "/sandbox/.hermes", + "6" * 64, + control._sha256(serialized.encode()), + projection, + nonce, + selected, + serialized, + "locked", + "mutable", + ) + transaction = control._expected_transaction_id(request) + return { + "schemaVersion": 1, + "action": "acquire", + "transactionId": transaction, + "providerId": "docker", + "sandboxName": "alpha", + "lifecycleGeneration": lifecycle_generation, + "engineBindingSha256": "3" * 64, + "runtimeId": "1" * 64, + "runtimePid": 4812, + "sandboxIdentitySha256": "4" * 64, + "containerMountsSha256": "5" * 64, + "stateRoot": "/sandbox/.hermes", + "stateRootMountsSha256": "6" * 64, + "plan": serialized, + "planSha256": request.plan_sha256, + "projectionSha256": projection, + "nonce": nonce, + "target": "locked", + "rollback": "mutable", + } + +def status_value(action, acquire, provider_handle=None, activation_handle=None, completed=None): + value = { + "schemaVersion": 1, + "action": action, + "transactionId": acquire["transactionId"], + "providerId": "docker", + "sandboxName": "alpha", + "lifecycleGeneration": "generation:7", + "engineBindingSha256": "3" * 64, + "runtimeId": "1" * 64, + "runtimePid": 4812, + "sandboxIdentitySha256": "4" * 64, + "containerMountsSha256": "5" * 64, + } + if action != "recover": + value["providerHandle"] = provider_handle + if action == "release": + value["activationProviderHandle"] = activation_handle + value["completedLedgerSha256"] = completed + return value + +def parse(action, value): + return control._parse_request(action, control._json_bytes(value) + b"\n") + +def process(pid, state, parent, start, uid, command, inode): + return control.ProcessIdentity( + pid, + state, + parent, + start, + (uid, uid, uid, uid), + command, + 91, + inode, + ) + +root_uid = control.ROOT_UID +pid1 = process(1, "S", 0, "100", root_uid, (control.OPENSHELL_ARGV0,), 101) +start = process( + 10, + "S", + 1, + "200", + 1001, + (b"/bin/bash", control.NEMOCLAW_START_PATH), + 110, +) +gateway = process( + 77, + "S", + 10, + "707", + 1000, + (b"/usr/local/bin/hermes", b"gateway", b"run"), + 177, +) +auxiliary = process(78, "S", 10, "708", 1001, (b"tail", b"-F"), 178) +fence = control.FenceProof( + control._process_reference(pid1), + control._process_reference(start), + (1000, 1001), +) +activation = control.ActivationProof( + gateway.pid, + gateway.start_identity, + 1000, + "sha256:" + "a" * 64, + "tcp:18642:991", + "f" * 64, + "c" * 64, + (gateway.pid,), + (control._process_reference(gateway), control._process_reference(auxiliary)), +) + +results = {} +with tempfile.TemporaryDirectory() as atomic_root: + atomic_root_fd = os.open(atomic_root, os.O_RDONLY | os.O_DIRECTORY) + atomic_creation_modes = [] + real_os_open = control.os.open + def recording_os_open(path, flags, mode=0o777, *, dir_fd=None): + atomic_creation_modes.append(mode) + return real_os_open(path, flags, mode, dir_fd=dir_fd) + control.os.open = recording_os_open + try: + control._atomic_write( + atomic_root_fd, + "public-receipt.json", + b"{}\n", + mode=0o444, + ) + atomic_final_mode = stat.S_IMODE( + os.stat( + "public-receipt.json", + dir_fd=atomic_root_fd, + follow_symlinks=False, + ).st_mode + ) + finally: + control.os.open = real_os_open + os.close(atomic_root_fd) +results["atomic_write_modes"] = [atomic_creation_modes, atomic_final_mode] +results["sigcont"] = int(signal.SIGCONT) +results["sigstop"] = int(signal.SIGSTOP) +kernel_stop_calls = [] +real_os_kill = os.kill +os.kill = lambda pid, requested: kernel_stop_calls.append([pid, requested]) +try: + real_kernel_pid_namespace_stop() +finally: + os.kill = real_os_kill +results["kernel_namespace_broadcast"] = kernel_stop_calls +stopped_gateway = process( + gateway.pid, + "T", + gateway.parent_pid, + gateway.start_identity, + 1000, + gateway.command, + gateway.proc_inode, +) +results["state_transition_preserves_identity"] = ( + gateway.identity_key() == stopped_gateway.identity_key() +) +canonical_value = acquire_value() +results["canonical"] = parse("acquire", canonical_value).plan_sha256 +results["noncanonical"] = code( + lambda: control._parse_request( + "acquire", + json.dumps(canonical_value, sort_keys=True, separators=(",", ":")).encode() + b"\n", + ) +) +duplicate = control._json_bytes(canonical_value).replace( + b'{"schemaVersion":1,', b'{"schemaVersion":1,"schemaVersion":1,', 1 +) +results["duplicate"] = code(lambda: control._parse_request("acquire", duplicate + b"\n")) +boolean_version = dict(canonical_value) +boolean_version["schemaVersion"] = True +results["boolean_version"] = code(lambda: parse("acquire", boolean_version)) +wrong_transaction = dict(canonical_value) +wrong_transaction["transactionId"] = "9" * 64 +results["transaction"] = code(lambda: parse("acquire", wrong_transaction)) +restore = acquire_value(selected_plan=plan("b" * 64, "restore")) +results["restore"] = code(lambda: parse("acquire", restore)) +unsorted_plan = plan("b" * 64) +unsorted_plan["selectors"] = list(reversed(unsorted_plan["selectors"])) +unsorted = acquire_value(selected_plan=unsorted_plan) +results["unsorted_selectors"] = code(lambda: parse("acquire", unsorted)) +plus_generation = acquire_value(lifecycle_generation="generation+7") +results["plus_generation"] = parse("acquire", plus_generation).lifecycle_generation +punctuation_generation = acquire_value(lifecycle_generation=":generation") +results["punctuation_generation"] = code(lambda: parse("acquire", punctuation_generation)) + +with tempfile.TemporaryDirectory() as root: + durable = os.path.join(root, "durable") + runtime = os.path.join(root, "runtime") + os.mkdir(durable, 0o700) + os.mkdir(runtime, 0o700) + durable_fd = os.open(durable, os.O_RDONLY | os.O_DIRECTORY) + runtime_fd = os.open(runtime, os.O_RDONLY | os.O_DIRECTORY) + events = [] + control._capture_runtime_binding = lambda _root: ( + events.append(["capture"]) or ("mnt:[401]", "402", "403") + ) + control._discover_fence = lambda mount: events.append(["discover", mount]) or fence + control._hold_exact_processes = lambda selected, mount, proof: events.append( + ["hold", mount, selected.start.pid, None if proof is None else proof.service_pid] + ) + control._assert_active_state = lambda marker, _runtime_fd: events.append( + ["assert", marker["phase"], marker["activation"] is not None] + ) + control._apply_plan_posture = lambda _marker, posture: events.append(["posture", posture]) + control._activate_exact = lambda _durable_fd, _marker, _fence: events.append(["activate-exact"]) or activation + control._publish_activation_receipt = lambda _runtime_fd, marker: events.append( + ["activation-receipt", marker["phase"]] + ) + control._retire_activation_tree = lambda _marker, _runtime_fd, _proof: events.append( + [ + "retire", + control._load_marker(durable_fd)["phase"], + control._load_marker(durable_fd)["activation"] is not None, + ] + ) + control._cleanup_activation_protocol = lambda _durable_fd, marker: events.append( + ["protocol-cleanup", marker["phase"]] + ) + def release_hold(_durable_fd, _marker): + receipt = control._load_released_receipt(durable_fd) + events.append(["release-hold", receipt["releaseState"]]) + control._release_activation_hold = release_hold + try: + active_value = acquire_value() + active = parse("acquire", active_value) + marker = control._run_locked("acquire", active, durable_fd, runtime_fd) + results["acquire"] = marker["phase"] + results["acquire_fence"] = marker["fence"] + handle = control._provider_handle(marker) + results["assert"] = control._run_locked( + "assert", + parse("assert", status_value("assert", active_value, handle)), + durable_fd, + runtime_fd, + )["phase"] + publish = parse("publish", status_value("publish", active_value, handle)) + results["publish"] = control._run_locked( + "publish", publish, durable_fd, runtime_fd + )["phase"] + activate = parse("activate", status_value("activate", active_value, handle)) + activated = control._run_locked("activate", activate, durable_fd, runtime_fd) + results["activate"] = activated["phase"] + rollback = parse("rollback", status_value("rollback", active_value, handle)) + rolled_back = control._run_locked("rollback", rollback, durable_fd, runtime_fd) + results["rollback_after_activation"] = rolled_back["phase"] + results["rollback_retired"] = rolled_back["activation"] is None + activated = control._run_locked("activate", activate, durable_fd, runtime_fd) + activation_handle = control._activation_provider_handle(activated) + release = parse( + "release", + status_value("release", active_value, handle, activation_handle, "e" * 64), + ) + results["release"] = control._run_locked( + "release", release, durable_fd, runtime_fd + )["phase"] + results["released_marker"] = control._load_marker(durable_fd) is None + results["released_sentinel"] = ( + control._read_private_file(runtime_fd, control.SENTINEL_NAME, 1024) is None + ) + results["released_state"] = control._load_released_receipt(durable_fd)["releaseState"] + results["release_retry"] = control._run_locked( + "release", release, durable_fd, runtime_fd + )["phase"] + recover_released = parse("recover", status_value("recover", active_value)) + results["recover_released"] = control._run_locked( + "recover", recover_released, durable_fd, runtime_fd + )["phase"] + released_receipt = control._load_released_receipt(durable_fd) + results["released_reacquire"] = code( + lambda: control._run_locked("acquire", active, durable_fd, runtime_fd) + ) + + next_value = acquire_value(nonce="8" * 64) + next_request = parse("acquire", next_value) + next_marker = control._run_locked("acquire", next_request, durable_fd, runtime_fd) + next_handle = control._provider_handle(next_marker) + next_publish = parse("publish", status_value("publish", next_value, next_handle)) + control._run_locked("publish", next_publish, durable_fd, runtime_fd) + next_activate = parse("activate", status_value("activate", next_value, next_handle)) + next_activated = control._run_locked("activate", next_activate, durable_fd, runtime_fd) + control._atomic_write( + durable_fd, + control.RELEASED_RECEIPT_NAME, + control._json_bytes(released_receipt) + b"\n", + ) + control._run_locked("release", release, durable_fd, runtime_fd) + results["stale_release_preserves_active"] = ( + control._load_marker(durable_fd)["transactionId"] == next_request.transaction_id + ) + control._unlink_private(runtime_fd, control.SENTINEL_NAME) + recover = parse("recover", status_value("recover", next_value)) + recovered = control._run_locked("recover", recover, durable_fd, runtime_fd) + results["recover_activation"] = recovered["phase"] + wrong = status_value("recover", next_value) + wrong["sandboxIdentitySha256"] = "9" * 64 + results["wrong_binding"] = code( + lambda: control._run_locked( + "recover", parse("recover", wrong), durable_fd, runtime_fd + ) + ) + results["state_events"] = events + marker_for_helpers = next_activated + finally: + os.close(runtime_fd) + os.close(durable_fd) + +class PublisherError(RuntimeError): + def __init__(self, error_code): + super().__init__(error_code) + self.code = error_code + +publisher_calls = [] +def publisher_apply(marker, posture): + publisher_calls.append([marker["transactionId"], posture]) + return { + "schemaVersion": 1, + "protocol": control.PUBLISHER_PROTOCOL, + "transactionId": marker["transactionId"], + "nonce": marker["nonce"], + "planSha256": marker["planSha256"], + "projectionSha256": marker["projectionSha256"], + "posture": posture, + "verificationSha256": "9" * 64, + } +publisher_module = types.SimpleNamespace( + PublisherError=PublisherError, + apply_plan_posture=publisher_apply, +) +control._load_publisher_module = lambda: publisher_module +results["publisher_valid"] = code( + lambda: real_apply_plan_posture(marker_for_helpers, "locked") +) +results["publisher_calls"] = publisher_calls +publisher_module.apply_plan_posture = lambda _marker, _posture: { + "schemaVersion": 1, + "protocol": "wrong", + "transactionId": marker_for_helpers["transactionId"], + "nonce": marker_for_helpers["nonce"], + "planSha256": marker_for_helpers["planSha256"], + "projectionSha256": marker_for_helpers["projectionSha256"], + "posture": "locked", + "verificationSha256": "9" * 64, +} +results["publisher_bad_receipt"] = code( + lambda: real_apply_plan_posture(marker_for_helpers, "locked") +) +def publisher_refuse(_marker, _posture): + raise PublisherError("publisher-posture-refused") +publisher_module.apply_plan_posture = publisher_refuse +results["publisher_error"] = code( + lambda: real_apply_plan_posture(marker_for_helpers, "locked") +) + +control._supported_writer_uids = lambda: (1000, 1001) +control._sandbox_uid = lambda: 1001 +control._capture_process = lambda pid: {1: pid1, 10: start}.get(pid) +control._capture_writer_processes = lambda _uids: (start, gateway) +real_readlink = os.readlink +os.readlink = lambda selected: "mnt:[401]" if selected == control.MOUNT_NAMESPACE_PATH else real_readlink(selected) +try: + discovered = real_discover_fence("mnt:[401]") + results["discovered_pid1"] = discovered.supervisor.pid + results["discovered_start"] = discovered.start.pid + wrong_pid1 = process(1, "S", 0, "100", root_uid, (b"/bin/sh",), 101) + control._capture_process = lambda pid: {1: wrong_pid1, 10: start}.get(pid) + results["wrong_pid1"] = code(lambda: real_discover_fence("mnt:[401]")) +finally: + os.readlink = real_readlink + +hold_events = [] +control._prove_fence_shape = lambda _fence, _mount: (pid1, start) +control._stop_reference = lambda reference: hold_events.append(["stop", reference.pid]) +control._exclude_writers = lambda _uids, allowed: hold_events.append( + ["exclude", [reference.pid for reference in allowed]] +) +control._assert_writer_exclusion = lambda _uids, allowed: hold_events.append( + ["assert-writers", [reference.pid for reference in allowed]] +) +control._capture_process = lambda pid: { + 1: pid1, + 10: start, + 77: gateway, + 78: auxiliary, +}.get(pid) +real_hold_exact_processes(fence, "mnt:[401]", activation) +results["hold_events"] = hold_events + +stopped_start = process( + start.pid, + "T", + start.parent_pid, + start.start_identity, + 1001, + start.command, + start.proc_inode, +) +intruder = process(42, "S", 1, "222", 1000, (b"writer",), 142) +scans = [(stopped_start, intruder), (stopped_start,), (stopped_start,), (stopped_start,)] +writer_signals = [] +control._capture_writer_processes = lambda _uids: scans.pop(0) +control._signal_exact_process = lambda selected, requested: writer_signals.append( + [selected.pid, requested] +) +control.TERM_SECONDS = 5 +control.KILL_SECONDS = 5 +real_exclude_writers((1000, 1001), (control._process_reference(stopped_start),)) +results["writer_signals"] = writer_signals +results["writer_scans_remaining"] = len(scans) +control._capture_writer_processes = lambda _uids: (intruder,) +control.TERM_SECONDS = 0 +control.KILL_SECONDS = 0 +results["unstoppable_writer"] = code( + lambda: real_exclude_writers((1000, 1001), (control._process_reference(stopped_start),)) +) +results["unknown_writer"] = code(lambda: real_parse_proc_uids(b"Name:\tunknown\n")) + +class InjectedCleanupCrash(RuntimeError): + pass + +cleanup_faults = {} +original_handoff_directory = control.STARTUP_HANDOFF_DIRECTORY +original_sandbox_account = control._sandbox_account +original_cleanup_activation_protocol = control._cleanup_activation_protocol +control._cleanup_activation_protocol = real_cleanup_activation_protocol +real_os_unlink = os.unlink +real_os_rmdir = os.rmdir +with tempfile.TemporaryDirectory() as cleanup_root: + cleanup_root = os.path.realpath(cleanup_root) + for boundary in ( + control.ACTIVATION_PERMIT_NAME, + control.ACTIVATION_RELEASE_NAME, + control.ACTIVATION_RETRY_NAME, + control.STARTUP_CANDIDATE_NAME, + control.STARTUP_RETRY_ACK_NAME, + "candidate-directory", + control.ACTIVATION_CLEANUP_NAME, + ): + case_root = os.path.join(cleanup_root, boundary) + os.mkdir(case_root, 0o755) + durable_path = os.path.join(case_root, "durable") + os.mkdir(durable_path, 0o700) + control.STARTUP_HANDOFF_DIRECTORY = os.path.join(case_root, "handoff") + control._sandbox_account = lambda: (os.geteuid(), os.getegid()) + durable_fd = os.open(durable_path, os.O_RDONLY | os.O_DIRECTORY) + try: + opened = control._open_startup_candidate_directory( + marker_for_helpers, create=True + ) + assert opened is not None + handoff_fd, candidate_fd = opened + try: + candidate_payload = ( + control._canonical_protocol_payload( + control._startup_candidate_payload(marker_for_helpers, fence) + ) + ) + permit_payload = control._canonical_protocol_payload( + control._activation_permit_payload(marker_for_helpers, fence) + ) + retry_payload = control._canonical_protocol_payload( + control._activation_retry_payload( + marker_for_helpers, + fence, + permit_payload, + candidate_payload, + ) + ) + ack_payload = control._canonical_protocol_payload( + control._startup_retry_ack_payload( + marker_for_helpers, fence, retry_payload + ) + ) + for name, payload in ( + (control.STARTUP_CANDIDATE_NAME, candidate_payload), + (control.STARTUP_RETRY_ACK_NAME, ack_payload), + ): + fd = os.open( + name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, + dir_fd=candidate_fd, + ) + os.write(fd, payload) + os.close(fd) + finally: + os.close(candidate_fd) + os.close(handoff_fd) + control._atomic_write( + durable_fd, + control.ACTIVATION_PERMIT_NAME, + permit_payload, + mode=0o444, + ) + control._atomic_write( + durable_fd, + control.ACTIVATION_RELEASE_NAME, + control._canonical_protocol_payload( + control._activation_release_payload( + marker_for_helpers, fence, activation + ) + ), + mode=0o444, + ) + control._atomic_write( + durable_fd, + control.ACTIVATION_RETRY_NAME, + retry_payload, + mode=0o444, + ) + + faulted = False + def injected_unlink_control(directory_fd, name, *, mode): + real_unlink_control_file(directory_fd, name, mode=mode) + if name == boundary: + raise InjectedCleanupCrash(boundary) + def injected_os_unlink(name, *args, **kwargs): + real_os_unlink(name, *args, **kwargs) + if name == boundary: + raise InjectedCleanupCrash(boundary) + def injected_os_rmdir(name, *args, **kwargs): + real_os_rmdir(name, *args, **kwargs) + if boundary == "candidate-directory": + raise InjectedCleanupCrash(boundary) + control._unlink_control_file = injected_unlink_control + os.unlink = injected_os_unlink + os.rmdir = injected_os_rmdir + try: + real_cleanup_activation_protocol(durable_fd, marker_for_helpers) + except InjectedCleanupCrash: + faulted = True + finally: + control._unlink_control_file = real_unlink_control_file + os.unlink = real_os_unlink + os.rmdir = real_os_rmdir + + cleanup_progress = control._read_private_file( + durable_fd, control.ACTIVATION_CLEANUP_NAME, control.MAX_MARKER_BYTES + ) + pending = real_activation_attempt_pending( + durable_fd, marker_for_helpers, fence + ) + candidate_directory = control._startup_candidate_directory( + marker_for_helpers + ) + clean = ( + control._read_control_file( + durable_fd, + control.ACTIVATION_PERMIT_NAME, + control.MAX_MARKER_BYTES, + mode=0o444, + ) + is None + and control._read_control_file( + durable_fd, + control.ACTIVATION_RELEASE_NAME, + control.MAX_MARKER_BYTES, + mode=0o444, + ) + is None + and control._read_control_file( + durable_fd, + control.ACTIVATION_RETRY_NAME, + control.MAX_MARKER_BYTES, + mode=0o444, + ) + is None + and control._read_private_file( + durable_fd, + control.ACTIVATION_CLEANUP_NAME, + control.MAX_MARKER_BYTES, + ) + is None + and not os.path.exists(candidate_directory) + ) + cleanup_faults[boundary] = { + "faulted": faulted, + "progressRecorded": ( + cleanup_progress is not None + if boundary != control.ACTIVATION_CLEANUP_NAME + else cleanup_progress is None + ), + "pending": pending, + "clean": clean, + } + finally: + os.close(durable_fd) +control.STARTUP_HANDOFF_DIRECTORY = original_handoff_directory +control._sandbox_account = original_sandbox_account +control._cleanup_activation_protocol = original_cleanup_activation_protocol +results["cleanup_faults"] = cleanup_faults + +activation_events = [] +class FakeActivationGuard: + def disarm(self): + activation_events.append(["guard-disarm"]) + def fail_closed(self): + activation_events.append(["guard-hold"]) +control._activation_attempt_pending = lambda _fd, _marker, _fence: False +control._start_activation_guard = lambda _fence, _mount: ( + activation_events.append(["guard-start"]) or FakeActivationGuard() +) +control._assert_exact_process_fence = lambda *_args: activation_events.append(["assert-fence"]) +control._signal_reference = lambda reference, requested: activation_events.append( + ["signal", reference.pid, requested] +) +live_activation = control.ActivationProof( + gateway.pid, + gateway.start_identity, + 1000, + activation.configuration_generation, + activation.listener_identity, + activation.health_sha256, + activation.startup_checkpoint_sha256, + activation.persistent_pids, + (control._process_reference(gateway),), +) +control._publish_activation_permit = lambda _fd, _marker, _fence: activation_events.append(["permit"]) +control._wait_for_startup_checkpoint = lambda _marker, _fence: ( + activation_events.append(["checkpoint"]) or activation.startup_checkpoint_sha256 +) +control._wait_for_activation = lambda _marker, _fence, _checkpoint: activation_events.append(["wait-gateway"]) or live_activation +control._freeze_activation = lambda _marker, _fence, _proof: activation_events.append(["freeze-tree"]) or activation +control._verify_activation_checkpoint = lambda _marker, _fence, _proof: activation_events.append(["verify-checkpoint"]) +control._cleanup_activation_protocol = lambda _fd, _marker: activation_events.append(["protocol-cleanup"]) +with tempfile.TemporaryDirectory() as root: + durable_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + real_activate_exact(durable_fd, marker_for_helpers, fence) + results["activation_events"] = list(activation_events) + activation_events.clear() + control._wait_for_activation = lambda _marker, _fence, _checkpoint: control._fail("activation-timeout") + control._hold_exact_processes = lambda *_args: activation_events.append(["restore-hold"]) + results["activation_failure"] = code( + lambda: real_activate_exact(durable_fd, marker_for_helpers, fence) + ) + results["activation_failure_events"] = list(activation_events) + + activation_events.clear() + control._activation_attempt_pending = lambda _fd, _marker, _fence: True + control._hold_exact_processes = lambda *_args: activation_events.append(["restore-hold"]) + control._reset_activation_attempt = lambda _fd, _marker, _fence: activation_events.append(["retry-exec-ack"]) + control._wait_for_activation = lambda _marker, _fence, _checkpoint: activation_events.append(["wait-gateway"]) or live_activation + real_activate_exact(durable_fd, marker_for_helpers, fence) + results["activation_retry_events"] = list(activation_events) + finally: + os.close(durable_fd) + +control._configuration_generation = lambda: activation.configuration_generation +control._listener_identity = lambda _process: activation.listener_identity +control._health_status = lambda: 200 +control._recapture_reference = lambda _reference, _code="fenced-process-drift": gateway +live_proof = control._prove_live_activation( + marker_for_helpers, + fence, + gateway, + checkpoint_sha256=activation.startup_checkpoint_sha256, +) +results["live_proof"] = { + "service": live_proof.service_pid, + "generation": live_proof.configuration_generation, + "listener": live_proof.listener_identity, + "health": live_proof.health_sha256, + "checkpoint": live_proof.startup_checkpoint_sha256, +} + +with tempfile.TemporaryDirectory() as root: + runtime_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + real_publish_activation_receipt(runtime_fd, marker_for_helpers) + results["activation_receipt"] = code( + lambda: real_verify_activation_receipt(runtime_fd, marker_for_helpers) + ) + control._atomic_write(runtime_fd, control.ACTIVATION_RECEIPT_NAME, b"{}\n") + results["activation_receipt_tamper"] = code( + lambda: real_verify_activation_receipt(runtime_fd, marker_for_helpers) + ) + finally: + os.close(runtime_fd) + +release_states = {1: "T", 10: "T", 77: "T", 78: "T"} +release_events = [] +def state_process(original): + return control.ProcessIdentity( + original.pid, + release_states[original.pid], + original.parent_pid, + original.start_identity, + original.uids, + original.command, + original.proc_device, + original.proc_inode, + ) +by_release_pid = {1: pid1, 10: start, 77: gateway, 78: auxiliary} +control._prove_fence_shape = lambda _fence, _mount: ( + state_process(pid1), + state_process(start), +) +control._recapture_reference = lambda reference, _code="fenced-process-drift": state_process( + by_release_pid[reference.pid] +) +def resume_reference(reference): + release_events.append(["resume", reference.pid]) + release_states[reference.pid] = "S" + return state_process(by_release_pid[reference.pid]) +control._resume_reference = resume_reference +control._prove_released_activation = lambda *_args: release_events.append(["health"]) +control._verify_activation_checkpoint = lambda *_args: release_events.append(["verify-checkpoint"]) +control._publish_activation_release = lambda *_args: release_events.append(["release-receipt"]) +terminated_release_pids = set() +control._reference_is_terminated = lambda reference: reference.pid in terminated_release_pids +def signal_process(selected, requested): + release_events.append(["signal", selected.pid, requested]) + if requested == signal.SIGCONT: + release_states[selected.pid] = "S" +control._signal_exact_process = signal_process +control._wait_for_reference_running = lambda reference: state_process(by_release_pid[reference.pid]) +results["release_state_before"] = control._prove_fence_shape(fence, "mnt:[401]")[0].state +with tempfile.TemporaryDirectory() as root: + durable_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + try: + real_release_activation_hold(durable_fd, marker_for_helpers) + results["release_events"] = list(release_events) + release_events.clear() + real_release_activation_hold(durable_fd, marker_for_helpers) + results["release_retry_events"] = list(release_events) + + release_events.clear() + release_states.update({1: "T", 10: "T", 77: "T", 78: "T"}) + terminated_release_pids.add(78) + real_release_activation_hold(durable_fd, marker_for_helpers) + results["transient_exit_release_events"] = list(release_events) + + release_events.clear() + release_states.update({1: "T", 10: "T", 77: "T", 78: "T"}) + terminated_release_pids.clear() + terminated_release_pids.add(77) + results["persistent_exit_release"] = code( + lambda: real_release_activation_hold(durable_fd, marker_for_helpers) + ) + finally: + os.close(durable_fd) + +with tempfile.TemporaryDirectory() as root: + mutation_path = os.path.join(root, "writer-mutations") + held_path = os.path.join(root, "guardian-held") + lock_path = os.path.join(root, "controller.lock") + lock_seed_fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) + os.close(lock_seed_fd) + ready_read, ready_write = os.pipe() + writer_pid = os.fork() + if writer_pid == 0: + try: + os.close(ready_read) + os.close(ready_write) + while True: + fd = os.open(mutation_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.write(fd, b"x") + os.close(fd) + time.sleep(0.01) + finally: + os._exit(0) + controller_pid = os.fork() + if controller_pid == 0: + try: + os.close(ready_read) + lock_fd = os.open(lock_path, os.O_RDWR) + fcntl.flock(lock_fd, fcntl.LOCK_EX) + def guardian_hold(_fence, _mount, _activation): + os.kill(writer_pid, signal.SIGSTOP) + fd = os.open(held_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + os.write(fd, b"held") + os.close(fd) + time.sleep(0.25) + control._hold_exact_processes = guardian_hold + _guard = real_start_activation_guard(fence, "mnt:[401]", lock_fd) + os.write(ready_write, b"R") + while True: + signal.pause() + finally: + os._exit(0) + os.close(ready_write) + try: + results["guardian_controller_ready"] = os.read(ready_read, 1) == b"R" + deadline = time.monotonic() + 2 + while not os.path.exists(mutation_path) and time.monotonic() < deadline: + time.sleep(0.01) + os.kill(controller_pid, signal.SIGKILL) + os.waitpid(controller_pid, 0) + readable, _writable, _exceptional = select.select([ready_read], [], [], 2) + results["guardian_client_eof"] = bool(readable) and os.read(ready_read, 1) == b"" + deadline = time.monotonic() + 2 + while not os.path.exists(held_path) and time.monotonic() < deadline: + time.sleep(0.01) + results["guardian_held_after_sigkill"] = os.path.exists(held_path) + contender_fd = os.open(lock_path, os.O_RDWR) + try: + try: + fcntl.flock(contender_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + results["guardian_retains_controller_lock"] = False + except BlockingIOError: + results["guardian_retains_controller_lock"] = True + deadline = time.monotonic() + 2 + while True: + try: + fcntl.flock(contender_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + results["guardian_releases_controller_lock"] = True + break + except BlockingIOError: + if time.monotonic() >= deadline: + results["guardian_releases_controller_lock"] = False + break + time.sleep(0.01) + finally: + os.close(contender_fd) + before = os.path.getsize(mutation_path) + time.sleep(0.15) + after = os.path.getsize(mutation_path) + results["guardian_blocks_mutation"] = before == after + selected = 0 + status = 0 + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + selected, status = os.waitpid(writer_pid, os.WUNTRACED | os.WNOHANG) + if selected == writer_pid and os.WIFSTOPPED(status): + break + time.sleep(0.01) + results["guardian_writer_stopped"] = selected == writer_pid and os.WIFSTOPPED(status) + finally: + os.close(ready_read) + try: + os.kill(writer_pid, signal.SIGCONT) + os.kill(writer_pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + os.waitpid(writer_pid, 0) + except ChildProcessError: + pass + +with tempfile.TemporaryDirectory() as root: + mutation_path = os.path.join(root, "last-resort-writer-mutations") + parked_path = os.path.join(root, "last-resort-parked") + enumeration_path = os.path.join(root, "last-resort-enumeration") + guardian_pid_path = os.path.join(root, "last-resort-guardian-pid") + lock_path = os.path.join(root, "last-resort-controller.lock") + lock_seed_fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) + os.close(lock_seed_fd) + ready_read, ready_write = os.pipe() + writer_pid = os.fork() + if writer_pid == 0: + try: + os.close(ready_read) + os.close(ready_write) + while True: + fd = os.open(mutation_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.write(fd, b"x") + os.close(fd) + time.sleep(0.01) + finally: + os._exit(0) + controller_pid = os.fork() + if controller_pid == 0: + try: + os.close(ready_read) + lock_fd = os.open(lock_path, os.O_RDWR) + fcntl.flock(lock_fd, fcntl.LOCK_EX) + def failed_guardian_hold(_fence, _mount, _activation): + raise RuntimeError("injected hold failure") + enumeration_calls = [0] + def last_resort_pids(): + enumeration_calls[0] += 1 + fd = os.open( + enumeration_path, + os.O_WRONLY | os.O_CREAT | os.O_APPEND, + 0o600, + ) + if enumeration_calls[0] % 2: + os.write(fd, b"E") + os.close(fd) + raise OSError("injected procfs failure") + os.write(fd, b"0") + os.close(fd) + return () + def last_resort_broadcast(): + try: + fd = os.open( + parked_path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, + ) + except FileExistsError: + pass + else: + os.write(fd, b"parked") + os.close(fd) + os.kill(writer_pid, signal.SIGSTOP) + control._hold_exact_processes = failed_guardian_hold + control._pid_namespace_process_ids = last_resort_pids + control._kernel_pid_namespace_stop = last_resort_broadcast + guard = real_start_activation_guard(fence, "mnt:[401]", lock_fd) + fd = os.open(guardian_pid_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + os.write(fd, str(guard.pid).encode("ascii")) + os.close(fd) + os.write(ready_write, b"R") + while True: + signal.pause() + finally: + os._exit(0) + os.close(ready_write) + guardian_pid = None + try: + results["last_resort_controller_ready"] = os.read(ready_read, 1) == b"R" + deadline = time.monotonic() + 2 + while ( + not os.path.exists(mutation_path) + or not os.path.exists(guardian_pid_path) + ) and time.monotonic() < deadline: + time.sleep(0.01) + with open(guardian_pid_path, "r", encoding="ascii") as stream: + guardian_pid = int(stream.read(), 10) + os.kill(controller_pid, signal.SIGKILL) + os.waitpid(controller_pid, 0) + readable, _writable, _exceptional = select.select([ready_read], [], [], 2) + results["last_resort_client_eof"] = bool(readable) and os.read(ready_read, 1) == b"" + deadline = time.monotonic() + 2 + while not os.path.exists(parked_path) and time.monotonic() < deadline: + time.sleep(0.01) + selected = 0 + status = 0 + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + selected, status = os.waitpid(writer_pid, os.WUNTRACED | os.WNOHANG) + if selected == writer_pid and os.WIFSTOPPED(status): + break + time.sleep(0.01) + results["last_resort_writer_stopped"] = ( + selected == writer_pid and os.WIFSTOPPED(status) + ) + contender_fd = os.open(lock_path, os.O_RDWR) + try: + try: + fcntl.flock(contender_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + results["last_resort_retains_controller_lock"] = False + except BlockingIOError: + results["last_resort_retains_controller_lock"] = True + before = os.path.getsize(mutation_path) + time.sleep(0.15) + after = os.path.getsize(mutation_path) + results["last_resort_blocks_mutation"] = before == after + with open(enumeration_path, "rb") as stream: + enumeration_evidence = stream.read() + results["last_resort_procfs_independent"] = ( + b"E" in enumeration_evidence and b"0" in enumeration_evidence + ) + os.kill(guardian_pid, signal.SIGKILL) + deadline = time.monotonic() + 2 + while True: + try: + fcntl.flock(contender_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + results["last_resort_external_recovery"] = True + break + except BlockingIOError: + if time.monotonic() >= deadline: + results["last_resort_external_recovery"] = False + break + time.sleep(0.01) + finally: + os.close(contender_fd) + finally: + os.close(ready_read) + if guardian_pid is not None: + try: + os.kill(guardian_pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + os.kill(writer_pid, signal.SIGCONT) + os.kill(writer_pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + os.waitpid(writer_pid, 0) + except ChildProcessError: + pass + +with tempfile.TemporaryDirectory() as root: + retry_script = os.path.join(root, "exact-retry.sh") + retry_ready = os.path.join(root, "retry-ready") + retry_ack = os.path.join(root, "retry-exec-ack") + retry_trap = os.path.join(root, "retry-trap") + retry_state = os.path.join(root, "retry-state") + dollar = "$" + with open(retry_script, "w", encoding="utf-8") as stream: + stream.write( + "#!/usr/bin/env bash\n" + "set -eu\n" + f"printf '%s\\n' \"{dollar}{{RETRIED:-unset}}\" >>\"{retry_state}\"\n" + f"if [ \"{dollar}{{RETRIED:-0}}\" = 1 ]; then : >\"{retry_ack}\"; kill -STOP \"$$\"; while :; do sleep 1; done; fi\n" + f"trap ': >\"{retry_trap}\"; export RETRIED=1; exec \"$0\"' USR2\n" + f": >\"{retry_ready}\"\n" + "kill -STOP \"$$\"\n" + "while :; do sleep 1; done\n" + ) + os.chmod(retry_script, 0o700) + retry_process = subprocess.Popen( + [retry_script], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + def process_start_token(pid): + proc_stat = f"/proc/{pid}/stat" + if os.path.exists(proc_stat): + with open(proc_stat, "r", encoding="ascii") as stream: + return stream.read().rsplit(") ", 1)[1].split()[19] + return subprocess.check_output( + ["ps", "-o", "lstart=", "-p", str(pid)], text=True + ).strip() + def process_command_token(pid): + proc_command = f"/proc/{pid}/cmdline" + if os.path.exists(proc_command): + with open(proc_command, "rb") as stream: + return stream.read().hex() + return subprocess.check_output( + ["ps", "-o", "command=", "-p", str(pid)], text=True + ).strip() + def process_state_token(pid): + proc_stat = f"/proc/{pid}/stat" + if os.path.exists(proc_stat): + with open(proc_stat, "r", encoding="ascii") as stream: + return stream.read().rsplit(") ", 1)[1].split()[0] + return subprocess.check_output( + ["ps", "-o", "state=", "-p", str(pid)], text=True + ).strip()[:1] + try: + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + if os.path.exists(retry_ready) and process_state_token(retry_process.pid) in ("T", "t"): + break + time.sleep(0.01) + results["retry_stopped_before"] = ( + os.path.exists(retry_ready) + and process_state_token(retry_process.pid) in ("T", "t") + ) + retry_start_before = process_start_token(retry_process.pid) + retry_command_before = process_command_token(retry_process.pid) + os.kill(retry_process.pid, signal.SIGUSR2) + os.kill(retry_process.pid, signal.SIGCONT) + deadline = time.monotonic() + 2 + while not os.path.exists(retry_ack) and time.monotonic() < deadline: + time.sleep(0.01) + results["retry_trap_seen"] = os.path.exists(retry_trap) + results["retry_exec_ack"] = os.path.exists(retry_ack) + with open(retry_state, "r", encoding="utf-8") as stream: + results["retry_exec_states"] = stream.read() + results["retry_exec_pid_stable"] = retry_process.poll() is None + results["retry_exec_start_stable"] = ( + retry_start_before == process_start_token(retry_process.pid) + ) + results["retry_exec_command_stable"] = ( + retry_command_before == process_command_token(retry_process.pid) + ) + finally: + try: + os.kill(retry_process.pid, signal.SIGCONT) + os.kill(retry_process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + retry_process.wait(timeout=2) + except subprocess.TimeoutExpired: + retry_process.kill() + retry_process.wait(timeout=2) + +class Metadata: + def __init__(self, device, inode): + self.st_dev = device + self.st_ino = inode + self.st_mode = stat.S_IFDIR | 0o555 + +real_lstat = os.lstat +real_stat = os.stat +real_readlink = os.readlink +real_proc_root = control.PROC_ROOT +fake_proc = "/trusted-proc" +container_root = Metadata(10, 1) +proc_root = Metadata(20, 2) +pid_root = container_root +metadata = { + fake_proc: proc_root, + "/": container_root, + os.path.join(fake_proc, "1", "root"): pid_root, + os.path.join(fake_proc, "self", "root"): pid_root, +} +namespaces = { + os.path.join(fake_proc, "1", "ns", "pid"): "pid:[402]", + os.path.join(fake_proc, "self", "ns", "pid"): "pid:[402]", +} +try: + control.PROC_ROOT = fake_proc + os.lstat = lambda selected: metadata[selected] + os.stat = lambda selected: metadata[selected] + os.readlink = lambda selected: namespaces[selected] + results["private_proc"] = code(real_assert_private_procfs) + metadata[os.path.join(fake_proc, "1", "root")] = Metadata(99, 1) + results["host_proc"] = code(real_assert_private_procfs) + metadata[os.path.join(fake_proc, "1", "root")] = container_root + namespaces[os.path.join(fake_proc, "self", "ns", "pid")] = "pid:[999]" + results["foreign_pid_namespace"] = code(real_assert_private_procfs) +finally: + control.PROC_ROOT = real_proc_root + os.lstat = real_lstat + os.stat = real_stat + os.readlink = real_readlink + +print(json.dumps(results, sort_keys=True)) +`; + +let harnessResult: Record; + +beforeAll(() => { + const result = spawnSync("python3", ["-I", "-c", HARNESS, CONTROLLER], { + encoding: "utf8", + timeout: 15_000, + }); + expect(result.status, result.stderr).toBe(0); + harnessResult = JSON.parse(result.stdout) as Record; +}); + +describe("runtime state mutation controller", () => { + it("accepts only the canonical adapter request and recomputes its transaction binding (#7744)", () => { + expect(harnessResult.canonical).toMatch(/^[0-9a-f]{64}$/u); + expect(harnessResult).toMatchObject({ + noncanonical: "envelope-schema", + duplicate: "duplicate-json-field", + boolean_version: "envelope-version", + transaction: "transaction-binding-mismatch", + restore: "plan-schema", + unsorted_selectors: "plan-selector-order", + plus_generation: "generation+7", + punctuation_generation: "lifecycle-generation", + }); + }); + + it("holds exact OpenShell and entrypoint identities through recovery (#7744)", () => { + expect(harnessResult).toMatchObject({ + acquire: "fenced", + assert: "fenced", + acquire_fence: { + supervisor: { pid: 1, startIdentity: "100" }, + start: { pid: 10, startIdentity: "200", parentPid: 1 }, + writerUids: [1000, 1001], + }, + discovered_pid1: 1, + discovered_start: 10, + wrong_pid1: "supervisor-unavailable", + }); + expect(harnessResult.hold_events).toEqual([ + ["stop", 1], + ["stop", 10], + ["stop", 77], + ["stop", 78], + ["exclude", [10, 77, 78]], + ["assert-writers", [10, 77, 78]], + ]); + const events = harnessResult.state_events as unknown[][]; + expect(events.slice(0, 5)).toEqual([ + ["capture"], + ["discover", "mnt:[401]"], + ["hold", "mnt:[401]", 10, null], + ["capture"], + ["assert", "fenced", false], + ]); + expect(harnessResult.state_transition_preserves_identity).toBe(true); + }); + + it("terminates every other writer and preserves only exact stopped processes (#7744)", () => { + expect(harnessResult.writer_signals).toEqual([[42, 15]]); + expect(harnessResult.writer_scans_remaining).toBe(0); + expect(harnessResult.unstoppable_writer).toBe("writer-exclusion-timeout"); + expect(harnessResult.unknown_writer).toBe("unreadable-writer-process"); + }); + + it("publishes, rolls an activated fence back, and recovers every durable phase (#7744)", () => { + expect(harnessResult).toMatchObject({ + publish: "published", + activate: "activation-proven", + rollback_after_activation: "rolled-back", + rollback_retired: true, + recover_activation: "activation-proven", + wrong_binding: "active-fence-binding-mismatch", + stale_release_preserves_active: true, + }); + const events = harnessResult.state_events as unknown[][]; + expect(events).toContainEqual(["posture", "locked"]); + expect(events).toContainEqual(["posture", "mutable"]); + expect(events).toContainEqual(["retire", "rolled-back", true]); + expect(events).toContainEqual(["hold", "mnt:[401]", 10, 77]); + expect(events).toContainEqual(["activation-receipt", "activation-proven"]); + }); + + it("creates public protocol files privately before applying their final mode (#7744)", () => { + expect(harnessResult.atomic_write_modes).toEqual([[0o600], 0o444]); + }); + + it("uses the fixed publisher contract and rejects unbound evidence (#7744)", () => { + expect(harnessResult).toMatchObject({ + publisher_valid: "ok", + publisher_bad_receipt: "publisher-receipt-invalid", + publisher_error: "publisher-posture-refused", + }); + expect(harnessResult.publisher_calls).toEqual([ + [expect.stringMatching(/^[0-9a-f]{64}$/u), "locked"], + ]); + }); + + it("proves and freezes a fresh Hermes activation before it returns evidence (#7744)", () => { + const sigcont = harnessResult.sigcont as number; + expect(harnessResult.activation_events).toEqual([ + ["guard-start"], + ["assert-fence"], + ["permit"], + ["signal", 10, sigcont], + ["checkpoint"], + ["wait-gateway"], + ["freeze-tree"], + ["verify-checkpoint"], + ["guard-disarm"], + ]); + expect(harnessResult.activation_failure_events).toEqual([ + ["guard-start"], + ["assert-fence"], + ["permit"], + ["signal", 10, sigcont], + ["checkpoint"], + ["guard-hold"], + ]); + expect(harnessResult.activation_retry_events).toEqual([ + ["guard-start"], + ["restore-hold"], + ["retry-exec-ack"], + ["permit"], + ["signal", 10, sigcont], + ["checkpoint"], + ["wait-gateway"], + ["freeze-tree"], + ["verify-checkpoint"], + ["guard-disarm"], + ]); + expect(harnessResult.activation_failure).toBe("activation-timeout"); + expect(harnessResult.live_proof).toMatchObject({ + service: 77, + generation: `sha256:${"a".repeat(64)}`, + listener: "tcp:18642:991", + health: expect.stringMatching(/^[0-9a-f]{64}$/u), + checkpoint: "c".repeat(64), + }); + expect(harnessResult.activation_receipt).toBe("ok"); + expect(harnessResult.activation_receipt_tamper).toBe("activation-receipt-mismatch"); + }); + + it("resumes exact-process activation cleanup after every unlink boundary (#7744)", () => { + const faults = harnessResult.cleanup_faults as Record>; + expect(Object.keys(faults).sort()).toEqual( + [ + "activation-permit.json", + "activation-release.json", + "activation-retry.json", + "startup-complete.json", + "retry-ack.json", + "candidate-directory", + "activation-cleanup.json", + ].sort(), + ); + for (const result of Object.values(faults)) { + expect(result).toEqual({ + faulted: true, + progressRecorded: true, + pending: false, + clean: true, + }); + } + }); + + it("records release intent before resuming PID1 last and resolves retry ambiguity (#7744)", () => { + const sigcont = harnessResult.sigcont as number; + expect(harnessResult).toMatchObject({ + release: "activation-proven", + released_marker: true, + released_sentinel: true, + released_state: "complete", + release_retry: "activation-proven", + recover_released: "activation-proven", + released_reacquire: "transaction-already-released", + }); + expect(harnessResult.release_events).toEqual([ + ["verify-checkpoint"], + ["release-receipt"], + ["resume", 77], + ["resume", 78], + ["resume", 10], + ["health"], + ["signal", 1, sigcont], + ]); + expect(harnessResult.release_retry_events).toEqual([ + ["verify-checkpoint"], + ["release-receipt"], + ["health"], + ]); + expect(harnessResult.transient_exit_release_events).toEqual([ + ["verify-checkpoint"], + ["release-receipt"], + ["resume", 77], + ["resume", 10], + ["health"], + ["signal", 1, sigcont], + ]); + expect(harnessResult.persistent_exit_release).toBe("activation-process-drift"); + const events = harnessResult.state_events as unknown[][]; + expect(events).toContainEqual(["release-hold", "intent"]); + expect(events).toContainEqual(["protocol-cleanup", "activation-proven"]); + }); + + it("re-holds a real writer when the activation controller is SIGKILLed (#7744)", () => { + const sigstop = harnessResult.sigstop as number; + expect(harnessResult.kernel_namespace_broadcast).toEqual([[-1, sigstop]]); + expect(harnessResult).toMatchObject({ + guardian_controller_ready: true, + guardian_client_eof: true, + guardian_held_after_sigkill: true, + guardian_retains_controller_lock: true, + guardian_releases_controller_lock: true, + guardian_blocks_mutation: true, + guardian_writer_stopped: true, + last_resort_controller_ready: true, + last_resort_client_eof: true, + last_resort_writer_stopped: true, + last_resort_retains_controller_lock: true, + last_resort_blocks_mutation: true, + last_resort_procfs_independent: true, + last_resort_external_recovery: true, + retry_exec_ack: true, + retry_exec_states: "unset\n1\n", + retry_trap_seen: true, + retry_stopped_before: true, + retry_exec_pid_stable: true, + retry_exec_start_stable: true, + retry_exec_command_stable: true, + }); + }); + + it("refuses procfs outside the container PID namespace (#7744)", () => { + expect(harnessResult.private_proc).toBe("ok"); + expect(harnessResult.host_proc).toBe("unsafe-proc-namespace"); + expect(harnessResult.foreign_pid_namespace).toBe("unsafe-proc-namespace"); + }); +}); diff --git a/test/runtime-state-mutation-hermes-publisher.test.ts b/test/runtime-state-mutation-hermes-publisher.test.ts new file mode 100644 index 00000000000..61cb74201d3 --- /dev/null +++ b/test/runtime-state-mutation-hermes-publisher.test.ts @@ -0,0 +1,380 @@ +// 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 ROOT = path.join(import.meta.dirname, ".."); +const PUBLISHER = path.join(ROOT, "scripts", "runtime_state_mutation_hermes_publisher.py"); +const CAPABILITY = path.join(ROOT, "agents", "hermes", "runtime-state-mutation-publisher-v1.json"); +const STATE_PLAN = path.join(ROOT, "agents", "hermes", "state-lock-plan.json"); +const START = path.join(ROOT, "agents", "hermes", "start.sh"); +const STARTUP_GATE = path.join(ROOT, "scripts", "runtime-state-mutation-startup-gate.py"); + +const HARNESS = String.raw` +import hashlib +import importlib.util +import json +import os +import shutil +import sys +import tempfile + +spec = importlib.util.spec_from_file_location("hermes_publisher", sys.argv[1]) +publisher = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = publisher +spec.loader.exec_module(publisher) +publisher.ROOT_UID = os.getuid() +publisher.ROOT_GID = os.getgid() + +with open(sys.argv[2], "r", encoding="utf-8") as stream: + installed_value = json.load(stream) +installed_plan = {key: value for key, value in installed_value.items() if key != "$comment"} + +def canonical(value): + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + +def marker(nonce="d" * 64, selectors=None): + expected = [ + *["path:" + value for value in (".config-hash", ".env", "config.yaml")], + *["path:" + value for value in installed_plan["readOnlyRoots"]], + *["path:" + value for value in installed_plan["confidentialRoots"]], + *["prefix:" + value for value in installed_plan["readOnlyPrefixes"]], + *["prefix:" + value for value in installed_plan["confidentialPrefixes"]], + ] + expected.sort(key=lambda value: value.encode()) + selected = selectors or [ + ({"kind": "path", "path": value.removeprefix("path:")} + if value.startswith("path:") + else {"kind": "prefix", "prefix": value.removeprefix("prefix:")}) + for value in expected + ] + plan = { + "schemaVersion": 2, + "intent": "protection-transition", + "target": "locked", + "rollback": "mutable", + "stateLockPlan": installed_plan, + "stateRoot": "/sandbox/.hermes", + "selectors": selected, + "projectionSha256": "b" * 64, + } + plan_text = canonical(plan) + return { + "schemaVersion": 1, + "phase": "fenced", + "transactionId": "a" * 64, + "providerId": "docker", + "stateRoot": "/sandbox/.hermes", + "plan": plan_text, + "planSha256": hashlib.sha256(plan_text.encode()).hexdigest(), + "projectionSha256": "b" * 64, + "nonce": nonce, + "target": "locked", + "rollback": "mutable", + } + +def code(call): + try: + call() + except publisher.PublisherError as error: + return error.code + return "ok" + +results = {} +with tempfile.TemporaryDirectory() as temporary: + durable = os.path.join(temporary, "durable") + os.mkdir(durable, 0o711) + plan_path = os.path.join(temporary, "state-lock-plan.json") + shutil.copyfile(sys.argv[2], plan_path) + os.chmod(plan_path, 0o444) + publisher.DURABLE_DIRECTORY = durable + publisher.STATE_LOCK_PLAN_PATH = plan_path + publisher._verify_final_posture = lambda posture, plan_json: ( + events.append(["verify", posture, json.loads(plan_json)]) or ("f" * 64) + ) + events = [] + token_index = 0 + + def write_guard_state(posture, rollback, token, phase="shields-transition-pending"): + state = { + "version": 1, + "phase": phase, + "mutation_lock_token": token, + "mutation_lock_path": os.path.join(durable, "hermes-config-mutation.lock"), + "hermes_dir": "/sandbox/.hermes", + "hash_file": "/etc/nemoclaw/hermes.config-hash", + "shields_transition": {"mode": posture, "rollback_mode": rollback}, + } + with open(os.path.join(durable, publisher.GUARD_STATE_NAME), "w", encoding="utf-8") as stream: + json.dump(state, stream, separators=(",", ":")) + os.chmod(os.path.join(durable, publisher.GUARD_STATE_NAME), 0o600) + + def fake_guard(action, arguments): + nonlocal_token = None + global token_index + events.append([action, list(arguments)]) + if action == "begin-shields-transition": + token_index += 1 + nonlocal_token = format(token_index, "064x") + posture = arguments[arguments.index("--shields-mode") + 1] + rollback = arguments[arguments.index("--rollback-shields-mode") + 1] + write_guard_state(posture, rollback, nonlocal_token) + return f"lock_token={nonlocal_token} original_locked=0\n" + if action == "prepare-shields-abort": + state_path = os.path.join(durable, publisher.GUARD_STATE_NAME) + with open(state_path, "r", encoding="utf-8") as stream: + state = json.load(stream) + transition = state["shields_transition"] + transition["mode"] = transition["rollback_mode"] + state["phase"] = "shields-transition-aborting" + with open(state_path, "w", encoding="utf-8") as stream: + json.dump(state, stream, separators=(",", ":")) + os.chmod(state_path, 0o600) + if action in ("finish-shields-transition", "abort-shields-transition"): + os.unlink(os.path.join(durable, publisher.GUARD_STATE_NAME)) + return "ok\n" + + publisher._run_guard = fake_guard + selected = marker() + first = publisher.apply_plan_posture(selected, "locked") + results["first"] = first + first_event_count = len(events) + retry = publisher.apply_plan_posture(selected, "locked") + results["retry"] = retry + results["retry_events"] = events[first_event_count:] + rollback = publisher.apply_plan_posture(selected, "mutable") + results["rollback"] = rollback + results["events"] = events + + extra = marker() + plan = json.loads(extra["plan"]) + plan["selectors"].append({"kind": "path", "path": "unexpected"}) + plan["selectors"].sort( + key=lambda value: (value["kind"] + ":" + value.get("path", value.get("prefix", ""))).encode() + ) + extra["plan"] = canonical(plan) + extra["planSha256"] = hashlib.sha256(extra["plan"].encode()).hexdigest() + results["extra_selector"] = code( + lambda: publisher.apply_plan_posture(extra, "locked") + ) + +with tempfile.TemporaryDirectory() as temporary: + durable = os.path.join(temporary, "durable") + os.mkdir(durable, 0o711) + plan_path = os.path.join(temporary, "state-lock-plan.json") + shutil.copyfile(sys.argv[2], plan_path) + os.chmod(plan_path, 0o444) + publisher.DURABLE_DIRECTORY = durable + publisher.STATE_LOCK_PLAN_PATH = plan_path + events = [] + publisher._verify_final_posture = lambda posture, plan_json: ( + events.append(["verify", posture]) or ("e" * 64) + ) + begin_failed = False + finish_failed = False + + def recovering_guard(action, arguments): + global begin_failed, finish_failed + events.append([action]) + token = "7" * 64 + if action == "begin-shields-transition": + posture = arguments[arguments.index("--shields-mode") + 1] + rollback = arguments[arguments.index("--rollback-shields-mode") + 1] + state = { + "version": 1, + "phase": "shields-transition-pending", + "mutation_lock_token": token, + "mutation_lock_path": os.path.join(durable, "hermes-config-mutation.lock"), + "hermes_dir": "/sandbox/.hermes", + "hash_file": "/etc/nemoclaw/hermes.config-hash", + "shields_transition": {"mode": posture, "rollback_mode": rollback}, + } + with open(os.path.join(durable, publisher.GUARD_STATE_NAME), "w", encoding="utf-8") as stream: + json.dump(state, stream, separators=(",", ":")) + os.chmod(os.path.join(durable, publisher.GUARD_STATE_NAME), 0o600) + if not begin_failed: + begin_failed = True + raise publisher.PublisherError("simulated-begin-response-loss") + return f"lock_token={token} original_locked=0\n" + if action == "finish-shields-transition": + os.unlink(os.path.join(durable, publisher.GUARD_STATE_NAME)) + if not finish_failed: + finish_failed = True + raise publisher.PublisherError("simulated-finish-response-loss") + return "ok\n" + + publisher._run_guard = recovering_guard + selected = marker(nonce="8" * 64) + results["begin_loss"] = code( + lambda: publisher.apply_plan_posture(selected, "locked") + ) + results["finish_loss"] = code( + lambda: publisher.apply_plan_posture(selected, "locked") + ) + results["recovered"] = publisher.apply_plan_posture(selected, "locked") + results["recovery_events"] = events + +with tempfile.TemporaryDirectory() as temporary: + durable = os.path.join(temporary, "durable") + os.mkdir(durable, 0o711) + plan_path = os.path.join(temporary, "state-lock-plan.json") + shutil.copyfile(sys.argv[2], plan_path) + os.chmod(plan_path, 0o444) + publisher.DURABLE_DIRECTORY = durable + publisher.STATE_LOCK_PLAN_PATH = plan_path + events = [] + publisher._verify_final_posture = lambda posture, plan_json: ( + events.append(["verify", posture]) or ("9" * 64) + ) + begin_lost = False + + def rollback_after_loss_guard(action, arguments): + global begin_lost + events.append([action]) + token = "6" * 64 + state_path = os.path.join(durable, publisher.GUARD_STATE_NAME) + if action == "begin-shields-transition": + posture = arguments[arguments.index("--shields-mode") + 1] + rollback = arguments[arguments.index("--rollback-shields-mode") + 1] + state = { + "version": 1, + "phase": "shields-transition-pending", + "mutation_lock_token": token, + "mutation_lock_path": os.path.join(durable, "hermes-config-mutation.lock"), + "hermes_dir": "/sandbox/.hermes", + "hash_file": "/etc/nemoclaw/hermes.config-hash", + "shields_transition": {"mode": posture, "rollback_mode": rollback}, + } + with open(state_path, "w", encoding="utf-8") as stream: + json.dump(state, stream, separators=(",", ":")) + os.chmod(state_path, 0o600) + begin_lost = True + raise publisher.PublisherError("simulated-begin-response-loss") + if action == "prepare-shields-abort": + with open(state_path, "r", encoding="utf-8") as stream: + state = json.load(stream) + state["phase"] = "shields-transition-aborting" + transition = state["shields_transition"] + transition["mode"] = transition["rollback_mode"] + with open(state_path, "w", encoding="utf-8") as stream: + json.dump(state, stream, separators=(",", ":")) + os.chmod(state_path, 0o600) + if action == "abort-shields-transition": + os.unlink(state_path) + return "ok\n" + + publisher._run_guard = rollback_after_loss_guard + selected = marker(nonce="5" * 64) + results["rollback_begin_loss"] = code( + lambda: publisher.apply_plan_posture(selected, "locked") + ) + results["rollback_after_begin_loss"] = publisher.apply_plan_posture( + selected, "mutable" + ) + results["rollback_recovery_events"] = events + +print(json.dumps(results, sort_keys=True)) +`; + +function runHarness(): Record { + const result = spawnSync("python3", ["-I", "-c", HARNESS, PUBLISHER, STATE_PLAN], { + encoding: "utf8", + timeout: 20_000, + }); + expect(result.status, result.stderr).toBe(0); + return JSON.parse(result.stdout) as Record; +} + +describe("Hermes runtime state mutation publisher", () => { + it("publishes and rolls back only the exact installed full plan (#7744)", () => { + const result = runHarness(); + expect(result.first).toMatchObject({ + protocol: "nemoclaw-runtime-state-mutation-publisher-v1", + posture: "locked", + nonce: "d".repeat(64), + }); + expect(result.retry).toMatchObject({ posture: "locked" }); + expect(result.rollback).toMatchObject({ posture: "mutable" }); + const expectedStatePlan = JSON.parse(fs.readFileSync(STATE_PLAN, "utf8")) as Record< + string, + unknown + >; + delete expectedStatePlan.$comment; + expect(result.retry_events).toEqual([["verify", "locked", expectedStatePlan]]); + expect(result.extra_selector).toBe("publisher-plan-selector-mismatch"); + const events = result.events as Array<[string, string[]?]>; + expect(events.filter(([action]) => action === "begin-shields-transition")).toHaveLength(2); + expect(events).toContainEqual([ + "run-state-dir-transition", + expect.arrayContaining(["--state-action", "lock"]), + ]); + expect(events).toContainEqual([ + "run-state-dir-transition", + expect.arrayContaining(["--state-action", "unlock"]), + ]); + }); + + it("recovers nonce-bound begin and finish response loss without replaying them (#7744)", () => { + const result = runHarness(); + expect(result).toMatchObject({ + begin_loss: "simulated-begin-response-loss", + finish_loss: "simulated-finish-response-loss", + recovered: { posture: "locked", nonce: "8".repeat(64) }, + }); + const events = result.recovery_events as Array<[string]>; + expect(events.filter(([action]) => action === "begin-shields-transition")).toHaveLength(1); + expect(events.filter(([action]) => action === "finish-shields-transition")).toHaveLength(1); + expect(events.filter(([action]) => action === "verify")).toHaveLength(1); + }); + + it("can publish the exact rollback after a target begin response is lost (#7744)", () => { + const result = runHarness(); + expect(result).toMatchObject({ + rollback_begin_loss: "simulated-begin-response-loss", + rollback_after_begin_loss: { posture: "mutable", nonce: "5".repeat(64) }, + }); + expect(result.rollback_recovery_events).toEqual([ + ["begin-shields-transition"], + ["prepare-shields-abort"], + ["run-state-dir-transition"], + ["abort-shields-transition"], + ["verify", "mutable"], + ]); + }); + + it("publishes one exact image capability and checks the durable root gate before startup code", () => { + expect(fs.readFileSync(CAPABILITY, "utf8")).toBe( + '{"schemaVersion":1,"protocol":"nemoclaw-runtime-state-mutation-publisher-v1","agent":"hermes","providerId":"docker","stateRoot":"/sandbox/.hermes","planSchemaVersion":2,"entrypoint":"/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py"}\n', + ); + const start = fs.readFileSync(START, "utf8"); + const gate = start.indexOf( + 'NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_HELPER="/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py"', + ); + expect(gate).toBeGreaterThan(0); + expect(gate).toBeLessThan(start.indexOf("# managed-entrypoint-env-wrapper begin")); + expect(gate).toBeLessThan(start.indexOf('source "$_SANDBOX_INIT"')); + expect(gate).toBeLessThan(start.indexOf('migrate_legacy_layout "/sandbox/.hermes"')); + expect(start).not.toContain("/sandbox/.nemoclaw/runtime-state-mutation-hold-v1.json"); + expect(start).toContain( + 'NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_PYTHON="/opt/hermes/.venv/bin/python3"', + ); + expect(start).toContain('NEMOCLAW_RUNTIME_STATE_MUTATION_GATE_SETPRIV="/usr/bin/setpriv"'); + expect(start).toContain("--reuid=sandbox --regid=sandbox --init-groups --"); + expect(start).toContain("nemoclaw_runtime_state_mutation_checkpoint || return 1"); + expect(start).toContain("trap nemoclaw_runtime_state_mutation_retry_exec USR2"); + expect(start).toContain("exec /usr/local/bin/nemoclaw-start"); + expect(start).toContain("nemoclaw_runtime_state_mutation_gate resume"); + + const startupGate = fs.readFileSync(STARTUP_GATE, "utf8"); + expect(startupGate).toContain('DURABLE_DIRECTORY = "/var/lib/nemoclaw/runtime-state-mutation"'); + expect(startupGate).toContain('"permitted": 10'); + expect(startupGate).toContain('"activation-ready": 11'); + expect(startupGate).toContain('"retry": 12'); + expect(fs.readFileSync(PUBLISHER, "utf8")).toContain( + 'PYTHON_PATH = "/opt/hermes/.venv/bin/python3"', + ); + }); +}); diff --git a/test/runtime-state-mutation-startup-gate.test.ts b/test/runtime-state-mutation-startup-gate.test.ts new file mode 100644 index 00000000000..9b21bbf239b --- /dev/null +++ b/test/runtime-state-mutation-startup-gate.test.ts @@ -0,0 +1,220 @@ +// 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 GATE = path.join( + import.meta.dirname, + "..", + "scripts", + "runtime-state-mutation-startup-gate.py", +); + +const HARNESS = String.raw` +import hashlib +import importlib.util +import json +import os +import sys +import tempfile + +spec = importlib.util.spec_from_file_location("runtime_state_startup_gate", sys.argv[1]) +gate = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = gate +spec.loader.exec_module(gate) +gate.ROOT_UID = os.getuid() +gate.ROOT_GID = os.getgid() + +start = { + "pid": 41, + "startIdentity": "9001", + "parentPid": 1, + "uids": [1001, 1001, 1001, 1001], + "commandSha256": "a" * 64, + "procDevice": "22", + "procInode": "33", +} +gate._capture_parent = lambda: start + +def write(path, value, mode): + if os.path.exists(path): + os.chmod(path, 0o600) + with open(path, "wb") as stream: + stream.write(gate._canonical(value) + b"\n") + os.chmod(path, mode) + +def code(call): + try: + return call() + except gate.GateError as error: + return str(error) + +results = {} +results["uses_o_path_when_available"] = not hasattr(os, "O_PATH") or bool( + gate._directory_flags() & os.O_PATH +) +results["readable_final_is_read_only"] = ( + gate._directory_flags(readable=True) & os.O_ACCMODE +) == os.O_RDONLY +results["readable_final_excludes_o_path"] = not hasattr(os, "O_PATH") or not bool( + gate._directory_flags(readable=True) & os.O_PATH +) +with tempfile.TemporaryDirectory() as root: + root = os.path.realpath(root) + durable = os.path.join(root, "durable") + handoff = os.path.join(root, "handoff") + os.mkdir(durable, 0o711) + os.chmod(durable, 0o711) + os.mkdir(handoff, 0o711) + os.chmod(handoff, 0o711) + gate.DURABLE_DIRECTORY = durable + gate.HANDOFF_ROOT = handoff + + results["inactive"] = gate._run("admit") + write(os.path.join(durable, gate.ACTIVE_NAME), {"active": True}, 0o600) + results["unpermitted"] = code(lambda: gate._run("admit")) + + nonce = "b" * 64 + candidate_directory = os.path.join(handoff, nonce) + os.mkdir(candidate_directory, 0o700) + os.chmod(candidate_directory, 0o700) + permit = { + "schemaVersion": 1, + "protocol": gate.PERMIT_PROTOCOL, + "transactionId": "c" * 64, + "nonce": nonce, + "markerSha256": "d" * 64, + "start": start, + "candidateDirectory": candidate_directory, + } + write(os.path.join(durable, gate.PERMIT_NAME), permit, 0o444) + results["admitted"] = gate._run("admit") + + orphan = os.path.join(candidate_directory, ".startup-complete.json.91.interrupted") + with open(orphan, "wb") as stream: + stream.write(b"interrupted") + os.chmod(orphan, 0o600) + results["checkpoint"] = gate._run("checkpoint") + results["checkpoint_retry"] = gate._run("checkpoint") + candidate_path = os.path.join(candidate_directory, gate.CANDIDATE_NAME) + with open(candidate_path, "rb") as stream: + candidate = stream.read() + results["candidate"] = json.loads(candidate) + + permit_path = os.path.join(durable, gate.PERMIT_NAME) + with open(permit_path, "rb") as stream: + permit_payload = stream.read() + retry = { + "schemaVersion": 1, + "protocol": gate.RETRY_PROTOCOL, + "transactionId": permit["transactionId"], + "nonce": nonce, + "permitSha256": hashlib.sha256(permit_payload).hexdigest(), + "checkpointSha256": hashlib.sha256(candidate).hexdigest(), + "start": start, + "candidateDirectory": candidate_directory, + } + retry_path = os.path.join(durable, gate.RETRY_NAME) + write(retry_path, retry, 0o444) + results["restart"] = gate._run("restart") + results["resume_retry"] = gate._run("resume") + results["retry_wait"] = gate._run("admit") + with open(os.path.join(candidate_directory, gate.RETRY_ACK_NAME), "rb") as stream: + results["retry_ack"] = json.load(stream) + wrong_retry = {**retry, "transactionId": "e" * 64} + write(retry_path, wrong_retry, 0o444) + results["retry_wrong_transaction"] = code(lambda: gate._run("restart")) + os.unlink(retry_path) + os.unlink(os.path.join(candidate_directory, gate.RETRY_ACK_NAME)) + + release = { + "schemaVersion": 1, + "protocol": gate.RELEASE_PROTOCOL, + "transactionId": permit["transactionId"], + "nonce": nonce, + "checkpointSha256": hashlib.sha256(candidate).hexdigest(), + "start": start, + "candidateDirectory": candidate_directory, + } + write(os.path.join(durable, gate.RELEASE_NAME), release, 0o444) + results["released"] = gate._run("admit") + with open(candidate_path, "ab") as stream: + stream.write(b"tamper") + results["tampered_release"] = code(lambda: gate._run("admit")) + +with tempfile.TemporaryDirectory() as root: + root = os.path.realpath(root) + real = os.path.join(root, "real") + linked = os.path.join(root, "linked") + os.mkdir(real, 0o711) + os.chmod(real, 0o711) + os.symlink(real, linked) + gate.DURABLE_DIRECTORY = linked + results["symlink_directory"] = code(lambda: gate._run("admit")) + +with tempfile.TemporaryDirectory() as root: + root = os.path.realpath(root) + invalid = os.path.join(root, "invalid") + os.mkdir(invalid, 0o700) + os.chmod(invalid, 0o700) + gate.DURABLE_DIRECTORY = invalid + results["invalid_present_directory"] = code(lambda: gate._run("admit")) + +print(json.dumps(results, sort_keys=True)) +`; + +describe("runtime state mutation startup gate", () => { + it("fails closed and authenticates an interruption-safe startup checkpoint (#7744)", () => { + const result = spawnSync("python3", ["-I", "-c", HARNESS, GATE], { + encoding: "utf8", + timeout: 10_000, + }); + expect(result.status, result.stderr).toBe(0); + const value = JSON.parse(result.stdout) as Record; + const expectedStart = { + pid: 41, + startIdentity: "9001", + parentPid: 1, + uids: [1001, 1001, 1001, 1001], + commandSha256: "a".repeat(64), + procDevice: "22", + procInode: "33", + }; + expect(value).toMatchObject({ + uses_o_path_when_available: true, + readable_final_is_read_only: true, + readable_final_excludes_o_path: true, + inactive: "inactive", + unpermitted: "activation-not-permitted", + admitted: "permitted", + checkpoint: "activation-ready", + checkpoint_retry: "activation-ready", + restart: "retry", + resume_retry: "retry", + retry_wait: "retry-wait", + retry_wrong_transaction: "retry-permit-mismatch", + released: "released", + tampered_release: "release-candidate-mismatch", + symlink_directory: "unsafe-directory", + invalid_present_directory: "gate-directory-invalid", + candidate: { + schemaVersion: 1, + protocol: "nemoclaw-runtime-state-mutation-startup-complete-v1", + transactionId: "c".repeat(64), + nonce: "b".repeat(64), + markerSha256: "d".repeat(64), + start: expectedStart, + }, + retry_ack: { + schemaVersion: 1, + protocol: "nemoclaw-runtime-state-mutation-retry-ack-v1", + transactionId: "c".repeat(64), + nonce: "b".repeat(64), + retrySha256: expect.stringMatching(/^[0-9a-f]{64}$/u), + start: expectedStart, + }, + }); + }); +}); diff --git a/test/sandbox-provisioning.test.ts b/test/sandbox-provisioning.test.ts index 1469c2be250..8a80ad8b356 100644 --- a/test/sandbox-provisioning.test.ts +++ b/test/sandbox-provisioning.test.ts @@ -1048,6 +1048,18 @@ describe("Hermes sandbox provisioning", () => { const managedPolicyReaderPath = path.join(localLib, "managed_policy.py"); const mcpManifest = path.join(localLib, "openshell-child-visible-credentials.v0.0.101.json"); const stateDirGuardPath = path.join(localLib, "state-dir-guard.py"); + const runtimeStateMutationControlPath = path.join( + localLib, + "runtime-state-mutation-control.py", + ); + const runtimeStateMutationStartupGatePath = path.join( + localLib, + "runtime-state-mutation-startup-gate.py", + ); + const runtimeStateMutationPublisherPath = path.join( + localLib, + "runtime_state_mutation_hermes_publisher.py", + ); const stateLockPlanPath = path.join( tmp, "usr", @@ -1056,6 +1068,14 @@ describe("Hermes sandbox provisioning", () => { "nemoclaw", "state-lock-plan.json", ); + const runtimeStateMutationCapabilityPath = path.join( + tmp, + "usr", + "local", + "share", + "nemoclaw", + "runtime-state-mutation-publisher-v1.json", + ); const managedGatewayControlPath = path.join(localLib, "managed-gateway-control.py"); const hermesCronRestoreControlPath = path.join(localLib, "hermes-cron-restore-control.py"); const files = [ @@ -1080,7 +1100,11 @@ describe("Hermes sandbox provisioning", () => { mcpManifest, gatewaySupervisorPath, stateDirGuardPath, + runtimeStateMutationControlPath, + runtimeStateMutationStartupGatePath, + runtimeStateMutationPublisherPath, stateLockPlanPath, + runtimeStateMutationCapabilityPath, managedGatewayControlPath, hermesCronRestoreControlPath, path.join(localLib, "sandbox-rlimits.sh"), @@ -1092,7 +1116,12 @@ describe("Hermes sandbox provisioning", () => { ) .replaceAll("/usr/local/bin", localBin) .replaceAll("/usr/local/lib/nemoclaw", localLib) + .replaceAll("/opt/hermes/.venv/bin/python3", "python3") .replaceAll("/usr/local/share/nemoclaw/state-lock-plan.json", stateLockPlanPath) + .replaceAll( + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json", + runtimeStateMutationCapabilityPath, + ) .replaceAll("/etc/profile.d", profileDir) .replaceAll("/etc/bash.bashrc", bashrcPath); try { @@ -1108,7 +1137,7 @@ describe("Hermes sandbox provisioning", () => { expect(result.status, result.stderr).toBe(0); expect(calls).toContain( - `chown root:root ${gatewayControlPath} ${gatewaySupervisorPath} ${stateDirGuardPath} ${stateLockPlanPath} ${managedGatewayControlPath} ${buildMcpDigestPath} ${hermesCronRestoreControlPath} ${mcpManifest}`, + `chown root:root ${gatewayControlPath} ${gatewaySupervisorPath} ${stateDirGuardPath} ${runtimeStateMutationControlPath} ${runtimeStateMutationStartupGatePath} ${runtimeStateMutationPublisherPath} ${stateLockPlanPath} ${runtimeStateMutationCapabilityPath} ${managedGatewayControlPath} ${buildMcpDigestPath} ${hermesCronRestoreControlPath} ${mcpManifest}`, ); expect((fs.statSync(gatewayControlPath).mode & 0o777).toString(8)).toBe("700"); expect((fs.statSync(hermesCronRestoreControlPath).mode & 0o777).toString(8)).toBe("700"); @@ -1119,7 +1148,15 @@ describe("Hermes sandbox provisioning", () => { expect((fs.statSync(managedPolicyReaderPath).mode & 0o777).toString(8)).toBe("444"); expect((fs.statSync(gatewaySupervisorPath).mode & 0o777).toString(8)).toBe("444"); expect((fs.statSync(stateDirGuardPath).mode & 0o777).toString(8)).toBe("500"); + expect((fs.statSync(runtimeStateMutationControlPath).mode & 0o777).toString(8)).toBe("500"); + expect((fs.statSync(runtimeStateMutationStartupGatePath).mode & 0o777).toString(8)).toBe( + "555", + ); + expect((fs.statSync(runtimeStateMutationPublisherPath).mode & 0o777).toString(8)).toBe("500"); expect((fs.statSync(stateLockPlanPath).mode & 0o777).toString(8)).toBe("444"); + expect((fs.statSync(runtimeStateMutationCapabilityPath).mode & 0o777).toString(8)).toBe( + "444", + ); expect((fs.statSync(managedGatewayControlPath).mode & 0o777).toString(8)).toBe("500"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); diff --git a/test/sandbox-rlimit-hooks.test.ts b/test/sandbox-rlimit-hooks.test.ts index 27be5b54350..dee6d2576f3 100644 --- a/test/sandbox-rlimit-hooks.test.ts +++ b/test/sandbox-rlimit-hooks.test.ts @@ -534,7 +534,20 @@ describe("sandbox rlimit system hooks (#2173)", () => { const ciaoGuard = path.join(preloadDir, "ciao-network-guard.js"); const gatewaySupervisor = path.join(localLib, "gateway-supervisor.sh"); const stateDirGuard = path.join(localLib, "state-dir-guard.py"); + const runtimeStateMutationControl = path.join(localLib, "runtime-state-mutation-control.py"); + const runtimeStateMutationStartupGate = path.join( + localLib, + "runtime-state-mutation-startup-gate.py", + ); + const runtimeStateMutationPublisher = path.join( + localLib, + "runtime_state_mutation_hermes_publisher.py", + ); const stateLockPlan = path.join(tmp, "state-lock-plan.json"); + const runtimeStateMutationCapability = path.join( + tmp, + "runtime-state-mutation-publisher-v1.json", + ); const managedGatewayControl = path.join(localLib, "managed-gateway-control.py"); const hermesCronRestoreControl = path.join(localLib, "hermes-cron-restore-control.py"); const startBin = path.join(tmp, "nemoclaw-start"); @@ -571,7 +584,11 @@ describe("sandbox rlimit system hooks (#2173)", () => { fs.chmodSync(ciaoGuard, 0o666); fs.writeFileSync(gatewaySupervisor, "# gateway supervisor fixture\n"); fs.writeFileSync(stateDirGuard, "# state-dir guard fixture\n"); + fs.writeFileSync(runtimeStateMutationControl, "# runtime mutation control fixture\n"); + fs.writeFileSync(runtimeStateMutationStartupGate, "# runtime mutation gate fixture\n"); + fs.writeFileSync(runtimeStateMutationPublisher, "# runtime mutation publisher fixture\n"); fs.writeFileSync(stateLockPlan, "{}\n"); + fs.writeFileSync(runtimeStateMutationCapability, "{}\n"); fs.writeFileSync(managedGatewayControl, "# managed gateway control fixture\n"); fs.writeFileSync(hermesCronRestoreControl, "# Hermes cron restore control fixture\n"); fs.writeFileSync(startBin, "#!/usr/bin/env bash\n"); @@ -628,7 +645,24 @@ describe("sandbox rlimit system hooks (#2173)", () => { .replaceAll("/usr/local/lib/nemoclaw/preloads/ciao-network-guard.js", ciaoGuard) .replaceAll("/usr/local/lib/nemoclaw/preloads", preloadDir) .replaceAll("/usr/local/lib/nemoclaw/state-dir-guard.py", stateDirGuard) + .replaceAll( + "/usr/local/lib/nemoclaw/runtime-state-mutation-control.py", + runtimeStateMutationControl, + ) + .replaceAll( + "/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py", + runtimeStateMutationStartupGate, + ) + .replaceAll( + "/usr/local/lib/nemoclaw/runtime_state_mutation_hermes_publisher.py", + runtimeStateMutationPublisher, + ) .replaceAll("/usr/local/share/nemoclaw/state-lock-plan.json", stateLockPlan) + .replaceAll( + "/usr/local/share/nemoclaw/runtime-state-mutation-publisher-v1.json", + runtimeStateMutationCapability, + ) + .replaceAll("/opt/hermes/.venv/bin/python3", "python3") .replaceAll("/usr/local/lib/nemoclaw/managed-gateway-control.py", managedGatewayControl) .replaceAll( "/usr/local/lib/nemoclaw/hermes-cron-restore-control.py", @@ -660,7 +694,11 @@ describe("sandbox rlimit system hooks (#2173)", () => { expect(fs.statSync(langfuseCredentialPatcher).mode & 0o777).toBe(0o444); expect(fs.statSync(mcpCredentialBoundary).mode & 0o777).toBe(0o444); expect(fs.statSync(buildMcpDigest).mode & 0o777).toBe(0o444); + expect(fs.statSync(runtimeStateMutationControl).mode & 0o777).toBe(0o500); + expect(fs.statSync(runtimeStateMutationStartupGate).mode & 0o777).toBe(0o555); + expect(fs.statSync(runtimeStateMutationPublisher).mode & 0o777).toBe(0o500); expect(fs.statSync(stateLockPlan).mode & 0o777).toBe(0o444); + expect(fs.statSync(runtimeStateMutationCapability).mode & 0o777).toBe(0o444); expect(fs.statSync(hermesCronRestoreControl).mode & 0o777).toBe(0o700); expect(hardenedDir.uid).toBe(fixtureOwner.uid); expect(hardenedDir.gid).toBe(fixtureOwner.gid); diff --git a/test/shields-up-runtime-perms.test.ts b/test/shields-up-runtime-perms.test.ts index e0b61f5bf03..11bb10af729 100644 --- a/test/shields-up-runtime-perms.test.ts +++ b/test/shields-up-runtime-perms.test.ts @@ -132,6 +132,9 @@ Module._load = function patchedLoad(request, parent, isMain) { privilegedSandboxExecArgv(_sandboxName, cmd) { return [...cmd]; }, + withPrivilegedSandboxExecutionLease(_sandboxName, _operation, fn) { + return fn(); + }, }; } return originalLoad.call(this, request, parent, isMain); diff --git a/test/support/hermes-shell-harness.ts b/test/support/hermes-shell-harness.ts index 1768934a6d5..05b46df22bc 100644 --- a/test/support/hermes-shell-harness.ts +++ b/test/support/hermes-shell-harness.ts @@ -1,10 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { shellQuote } from "../../src/lib/core/shell-quote"; function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -54,3 +56,91 @@ export function runHermesBashHarness( fs.rmSync(tmpDir, { recursive: true, force: true }); } } + +export function runHermesSandboxInitPreludeWithFakePath( + startScript: string, + envWrapper: string, + temporaryRoot = os.tmpdir(), +) { + const tmpDir = fs.mkdtempSync(path.join(temporaryRoot, "nemoclaw-hermes-init-path-")); + try { + const fakeBin = path.join(tmpDir, "bin"); + const fakeInit = path.join(tmpDir, "sandbox-init.sh"); + const fakeSupervisor = path.join(tmpDir, "gateway-supervisor.sh"); + const fakeGatePython = path.join(tmpDir, "gate-python"); + const fakeGateHelper = path.join(tmpDir, "runtime-state-mutation-startup-gate.py"); + const fakeSetpriv = path.join(tmpDir, "setpriv"); + const marker = path.join(tmpDir, "dirname-called"); + const sourcePathLog = path.join(tmpDir, "source-path.log"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(fakeBin, { recursive: true }); + fs.writeFileSync( + path.join(fakeBin, "dirname"), + ["#!/usr/bin/env bash", `printf called > ${shellQuote(marker)}`, "exit 99"].join("\n"), + { mode: 0o700 }, + ); + fs.writeFileSync( + fakeInit, + [ + `printf "%s\\n" "$PATH" > ${shellQuote(sourcePathLog)}`, + "harden_resource_limits() { :; }", + ].join("\n"), + ); + fs.writeFileSync(fakeSupervisor, "# supervisor fixture\n"); + fs.writeFileSync(fakeGatePython, "#!/usr/bin/env bash\nexit 0\n", { mode: 0o700 }); + fs.writeFileSync(fakeGateHelper, "# startup gate fixture\n"); + fs.writeFileSync( + fakeSetpriv, + [ + "#!/usr/bin/env bash", + 'while [ "$#" -gt 0 ]; do', + ' if [ "$1" = "--" ]; then shift; break; fi', + " shift", + "done", + 'exec "$@"', + ].join("\n"), + { mode: 0o700 }, + ); + + const src = fs.readFileSync(startScript, "utf-8"); + const start = src.indexOf( + "# SECURITY: Lock down PATH before resolving or sourcing root startup helpers.", + ); + const end = src.indexOf("\nif [ -d /opt/hermes/hermes_cli/web_dist ];", start); + assert(start >= 0 && end >= 0, "Hermes start.sh prelude markers not found"); + const prelude = src + .slice(start, end) + .replaceAll("/opt/hermes/.venv/bin/python3", fakeGatePython) + .replaceAll("/usr/local/lib/nemoclaw/runtime-state-mutation-startup-gate.py", fakeGateHelper) + .replaceAll("/usr/bin/setpriv", fakeSetpriv) + .replaceAll("/usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh", envWrapper) + .replaceAll("/usr/local/lib/nemoclaw/sandbox-init.sh", fakeInit) + .replaceAll("/usr/local/lib/nemoclaw/gateway-supervisor.sh", fakeSupervisor); + + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `export PATH=${shellQuote(`${fakeBin}:${process.env.PATH ?? ""}`)}`, + prelude, + ].join("\n"), + { mode: 0o700 }, + ); + + const result = spawnSync("bash", [scriptPath], { + encoding: "utf-8", + timeout: 5000, + env: process.env, + }); + return { + result, + dirnameCalled: fs.existsSync(marker), + sourcePath: fs.existsSync(sourcePathLog) + ? fs.readFileSync(sourcePathLog, "utf-8").trim() + : "", + }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}