diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index b5e6664f534..0a9aa028cfb 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -788,9 +788,9 @@ RUN node --experimental-strip-types \ # file has to also rewrite the Dockerfile-committed hash, which reviewers gate). # Regenerate with `sha256sum agents/hermes/{hermes-wrapper.py,hermes-cli-adapter-v1.json,validate-cli-adapter.py,validate-env-secret-boundary.py,finalize-tirith-marker.py,cron-restore-control.py}`. ARG NEMOCLAW_HERMES_CLI_ADAPTER_SHA256=3c769f05292b840424a8feec9a9eb441e393a48bf0212bd824b0db8a33a66331 -ARG NEMOCLAW_HERMES_WRAPPER_SHA256=b008a27a53c8ddc1189d3ba03490e29e48c5a026f412deeb73b0bc3098923214 +ARG NEMOCLAW_HERMES_WRAPPER_SHA256=20de8ca3316dcd1e606ffb34a8adfd82f39e558882d3fbfa221da699cae712cc ARG NEMOCLAW_HERMES_CLI_ADAPTER_VALIDATOR_SHA256=db4046e79e513eab67b069a8eda20167b8b65529cf26842531d2ad673c670330 -ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=6937ddb650532e473b84a5e56fb26573491d1bc20230ba6c2bfd2e6f6d777edb +ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=007f49a2d0e107adeacc63e67d541d3308e2964cb6fc1b74c1e38de78d799f76 ARG NEMOCLAW_HERMES_TIRITH_FINALIZER_SHA256=a1e6b1c53ab297569abb87c29d15c294d729e46005bfd022136b4c447a791819 ARG NEMOCLAW_HERMES_CRON_RESTORE_CONTROLLER_SHA256=dbd32832383f174878c08529947f5d81911152e1516b6f960824db3c7f7ac1e9 # hadolint ignore=DL4006 diff --git a/agents/hermes/hermes-wrapper.py b/agents/hermes/hermes-wrapper.py index ce4f99de9c7..0c62bf4ad60 100755 --- a/agents/hermes/hermes-wrapper.py +++ b/agents/hermes/hermes-wrapper.py @@ -110,7 +110,6 @@ _GATEWAY_PACKAGE_ENV = { "UV_NO_CONFIG": "1", "UV_NO_CACHE": "1", - "UV_CACHE_DIR": f"{_GATEWAY_LAZY_INSTALL_TARGET}/.uv-cache", "PIP_CONFIG_FILE": "/dev/null", "PIP_DISABLE_PIP_VERSION_CHECK": "1", "PYTHONSAFEPATH": "1", @@ -352,16 +351,30 @@ def _run_gateway_guard(guard_path: str) -> int: file=sys.stderr, ) return 127 - return subprocess.call([python3, "-I", guard_path, "runtime-env"]) - - -def _harden_root_separated_gateway_package_env() -> None: + logical_env = dict(os.environ) + env = dict(logical_env) + for key in tuple(env): + if key in _GATEWAY_PACKAGE_ENV_KEYS or key.startswith(_GATEWAY_PACKAGE_ENV_PREFIXES): + env.pop(key, None) + payload = json.dumps( + logical_env, ensure_ascii=True, separators=(",", ":") + ).encode("ascii") + return subprocess.run( + [python3, "-I", guard_path, "runtime-env-json"], + input=payload, + env=env, + check=False, + ).returncode + + +def _harden_gateway_package_env(lazy_install_target: str) -> None: """Remove sandbox-controlled installer inputs before gateway exec.""" for key in tuple(os.environ): if key in _GATEWAY_PACKAGE_ENV_KEYS or key.startswith(_GATEWAY_PACKAGE_ENV_PREFIXES): os.environ.pop(key, None) os.environ.update(_GATEWAY_PACKAGE_ENV) + os.environ["UV_CACHE_DIR"] = f"{lazy_install_target}/.uv-cache" _SUPPORTED_CLI_ADAPTER_VERSION = 1 @@ -784,12 +797,11 @@ def main(argv: list[str]) -> int: return 1 os.environ["HERMES_HOME"] = _MANAGED_HERMES_HOME os.environ["HERMES_BUNDLED_PLUGINS"] = _MANAGED_BUNDLED_PLUGINS - os.environ["HERMES_LAZY_INSTALL_TARGET"] = _GATEWAY_LAZY_INSTALL_TARGET os.environ["HOME"] = _MANAGED_HOME - _harden_root_separated_gateway_package_env() rc = _run_gateway_guard(guard_path) if rc != 0: return rc + _harden_gateway_package_env(os.environ["HERMES_LAZY_INSTALL_TARGET"]) try: adapter = _load_cli_adapter(_resolve_cli_adapter()) adapter_result, exec_argv = _adapt_cli_argv(argv, adapter) diff --git a/agents/hermes/validate-env-secret-boundary.py b/agents/hermes/validate-env-secret-boundary.py index 63aa78f78b6..9c3f05e4652 100755 --- a/agents/hermes/validate-env-secret-boundary.py +++ b/agents/hermes/validate-env-secret-boundary.py @@ -19,6 +19,7 @@ import argparse import errno import grp +import json import os import pwd import re @@ -26,7 +27,7 @@ import sys from collections.abc import Iterator from contextlib import contextmanager -from typing import Iterable, TextIO +from typing import BinaryIO, Iterable, TextIO SECRET_KEY_RE = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|API)(_|$)") PLACEHOLDER_RE = re.compile( @@ -608,20 +609,48 @@ def validate_runtime_env(env: dict[str, str] | None = None) -> int: return _validate_runtime_env(source, _expected_lazy_install_target()) +def validate_runtime_env_json(stream: BinaryIO) -> int: + """Validate a bounded environment snapshot received on an anonymous pipe.""" + + payload = stream.read(MAX_ENV_BYTES + 1) + if len(payload) > MAX_ENV_BYTES: + print( + f"[SECURITY] Refusing Hermes startup because the process environment exceeds the {MAX_ENV_BYTES}-byte limit", + file=sys.stderr, + ) + return 1 + try: + source = json.loads(payload) + except (UnicodeDecodeError, json.JSONDecodeError): + print( + "[SECURITY] Refusing Hermes startup because the process environment snapshot is invalid", + file=sys.stderr, + ) + return 1 + if not isinstance(source, dict) or any( + not isinstance(key, str) or not isinstance(value, str) + for key, value in source.items() + ): + print( + "[SECURITY] Refusing Hermes startup because the process environment snapshot is invalid", + file=sys.stderr, + ) + return 1 + return validate_runtime_env(source) + + def validate_managed_gateway_env(supervisor_env: dict[str, str]) -> int: - """Validate the environment that the managed launcher gives Hermes.""" + """Validate the supervisor environment with managed launcher paths applied.""" - runtime_env = dict(supervisor_env) - # PID 1 exposes the shell's initial environment. The trusted launcher pins - # these values after startup and again on the Hermes gateway command. - runtime_env.update( + gateway_env = dict(supervisor_env) + gateway_env.update( { - "HERMES_LAZY_INSTALL_TARGET": GATEWAY_LAZY_INSTALL_TARGET, + "HERMES_LAZY_INSTALL_TARGET": SANDBOX_LAZY_INSTALL_TARGET, "HERMES_HOME": MANAGED_HERMES_HOME, "HERMES_BUNDLED_PLUGINS": MANAGED_BUNDLED_PLUGINS, } ) - return _validate_runtime_env(runtime_env, GATEWAY_LAZY_INSTALL_TARGET) + return _validate_runtime_env(gateway_env, SANDBOX_LAZY_INSTALL_TARGET) # Config-output masking layer for the wrapper-installed `hermes config show` @@ -795,6 +824,10 @@ def main(argv: list[str]) -> int: "runtime-env", help="Validate the current process environment", ) + sub.add_parser( + "runtime-env-json", + help=argparse.SUPPRESS, + ) sub.add_parser( "mask-config-output", help="Mask secret-shaped fields on stdin; print to stdout", @@ -804,6 +837,8 @@ def main(argv: list[str]) -> int: return validate_env_file(args.path) if args.mode == "mask-config-output": return mask_config_output(sys.stdin, sys.stdout) + if args.mode == "runtime-env-json": + return validate_runtime_env_json(sys.stdin.buffer) assert args.mode == "runtime-env", ( f"unreachable: argparse subparsers are required ({args.mode!r})" ) diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 97317bbc81a..a0bdef95a75 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -221,6 +221,11 @@ "test": "binds the runtime environment validator to its source digest", "category": "security" }, + { + "file": "test/agents/hermes/hermes-image-build-probes.test.ts", + "test": "binds the Hermes wrapper to its source digest", + "category": "security" + }, { "file": "test/agents/hermes/reviewed-hermes-platform-action.test.ts", "test": "publishes the verified native manifest digest", diff --git a/docs/manage-sandboxes/install-plugins-hermes.mdx b/docs/manage-sandboxes/install-plugins-hermes.mdx index 3176396012a..0a7cb9bd96b 100644 --- a/docs/manage-sandboxes/install-plugins-hermes.mdx +++ b/docs/manage-sandboxes/install-plugins-hermes.mdx @@ -31,8 +31,13 @@ After an upgrade, root-separated startup warns when preserved user plugins are p ## Configure the Bundled Hindsight Plugin The stock Hermes image provides `/sandbox/.hermes/lazy-packages` for lazy dependencies used by interactive sandbox commands. -The separated gateway never loads code from that sandbox-writable directory. -Instead, gateway startup installs the bundled Hindsight dependency into a gateway-owned runtime directory under `/run/nemoclaw` and loads it only from there. +The gateway target depends on the container process topology. + +| Topology | Gateway process | Gateway lazy-install target | Access and replacement boundary | +|---|---|---|---| +| Direct root-entrypoint topology | Root PID 1 launches the gateway under the separate `gateway` UID. | `/run/nemoclaw/hermes-gateway-lazy-packages` | The directory is gateway-owned with mode `0700`, so the `sandbox` UID cannot read or modify it. A rebuild or replacement container receives a newly created private directory, and Hindsight startup reinstalls the supported client. | +| OpenShell-managed same-UID topology | OpenShell is PID 1 and launches `nemoclaw-start`, the gateway, and the agent under the `sandbox` UID. | `/sandbox/.hermes/lazy-packages` | The gateway and agent share access because they use the same UID. NemoClaw declares the directory as Hermes state and preserves it across rebuilds and transactional container replacements. | + Neither target modifies the root virtual environment, and neither target is declared in the generated `.env` file. NemoClaw supports `hindsight-client==0.6.1` for this workflow. @@ -69,10 +74,10 @@ nemohermes gateway restart ``` The setup command installs `hindsight-client==0.6.1` under `/sandbox/.hermes/lazy-packages` for the sandbox-side command. -When `memory.provider` is `hindsight`, gateway startup independently installs the supported client into `/run/nemoclaw/hermes-gateway-lazy-packages` as the gateway user before it launches. -The sandbox user cannot read or modify that gateway-owned tree, and the gateway does not activate the sandbox-owned tree. +In the direct root-entrypoint topology, gateway startup independently installs the supported client into `/run/nemoclaw/hermes-gateway-lazy-packages` as the `gateway` user. +The gateway does not activate the sandbox-owned tree in that topology. +In the OpenShell-managed topology, gateway startup uses `/sandbox/.hermes/lazy-packages` under the shared `sandbox` UID. Both directories are outside the generated `.env`, `config.yaml`, and `.config-hash` files. -The sandbox copy is part of the Hermes durable state plan; the gateway copy lasts for the container runtime and is recreated after a rebuild or container replacement. Verify the provider and dependency after the restart: @@ -92,7 +97,8 @@ nemohermes rebuild --yes ``` A rebuild replaces the root virtual environment and preserves the sandbox lazy-install directory as declared Hermes state. -Gateway startup always recreates its private runtime target when the container has been replaced and reinstalls the supported client as the gateway user when Hindsight is selected. +Direct root-entrypoint startup recreates its private runtime target when the container has been replaced and reinstalls the supported client as the `gateway` user when Hindsight is selected. +OpenShell-managed startup uses the preserved sandbox target under the shared `sandbox` UID. Do not edit `/sandbox/.hermes/.env` to set `HERMES_LAZY_INSTALL_TARGET`. Do not install the dependency into `/opt/hermes/.venv`. diff --git a/scripts/managed-gateway-control.py b/scripts/managed-gateway-control.py index b9565cd197d..e62f554a049 100755 --- a/scripts/managed-gateway-control.py +++ b/scripts/managed-gateway-control.py @@ -1592,7 +1592,7 @@ def _run_fixed_validator( def _validate_managed_gateway_environment( script: str, supervisor_environment: dict[str, str] ) -> None: - """Validate the Hermes gateway environment without executing under untrusted input.""" + """Validate supervisor input after the validator applies managed launcher paths.""" _validate_trusted_regular(script) spec = importlib.util.spec_from_file_location( @@ -1724,7 +1724,9 @@ def _hermes_preflight( MAX_ENV_BYTES, recovery_deadline, ) - _validate_managed_gateway_environment(validator, _parse_environment(raw_environment)) + _validate_managed_gateway_environment( + validator, _parse_environment(raw_environment) + ) _require_recovery_time(recovery_deadline) _verify_locked_hermes_hash() _require_recovery_time(recovery_deadline) diff --git a/test/agents/hermes/hermes-env-secret-boundary-hardening.test.ts b/test/agents/hermes/hermes-env-secret-boundary-hardening.test.ts index 8ae598368d2..d4bbe769c09 100644 --- a/test/agents/hermes/hermes-env-secret-boundary-hardening.test.ts +++ b/test/agents/hermes/hermes-env-secret-boundary-hardening.test.ts @@ -144,6 +144,15 @@ function runDirectRuntimeEnvValidation(envOverrides: Record) { +function runManagedGatewayEnvValidation( + envOverrides: Record, + includeCanonicalPaths = true, +) { const environment: Record = { PATH: "/usr/bin", - HERMES_LAZY_INSTALL_TARGET: "/sandbox/.hermes/lazy-packages", + ...(includeCanonicalPaths + ? { + HERMES_LAZY_INSTALL_TARGET: "/sandbox/.hermes/lazy-packages", + HERMES_HOME: "/sandbox/.hermes", + HERMES_BUNDLED_PLUGINS: "/opt/hermes/plugins", + } + : {}), ...envOverrides, }; return spawnSync( @@ -524,6 +542,51 @@ wait "$child" }); describe("Hermes durable lazy-install target", () => { + it("accepts a valid environment snapshot at the JSON payload limit", () => { + const environment = { + HERMES_LAZY_INSTALL_TARGET: "/sandbox/.hermes/lazy-packages", + HERMES_HOME: "/sandbox/.hermes", + HERMES_BUNDLED_PLUGINS: "/opt/hermes/plugins", + SAFE_PADDING: "", + }; + const emptyPayload = JSON.stringify(environment); + environment.SAFE_PADDING = "x".repeat(MAX_ENV_BYTES - Buffer.byteLength(emptyPayload)); + const payload = JSON.stringify(environment); + + expect(Buffer.byteLength(payload)).toBe(MAX_ENV_BYTES); + const result = runRuntimeEnvJsonValidation(payload); + expect(result.status, result.stderr).toBe(0); + expect(result.stderr).toBe(""); + }); + + it("rejects malformed JSON environment snapshots", () => { + const result = runRuntimeEnvJsonValidation("{"); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("process environment snapshot is invalid"); + }); + + it("rejects non-string JSON environment values", () => { + const result = runRuntimeEnvJsonValidation( + JSON.stringify({ + HERMES_LAZY_INSTALL_TARGET: "/sandbox/.hermes/lazy-packages", + HERMES_HOME: "/sandbox/.hermes", + HERMES_BUNDLED_PLUGINS: "/opt/hermes/plugins", + SAFE_VALUE: 1, + }), + ); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("process environment snapshot is invalid"); + }); + + it("rejects JSON environment snapshots over the payload limit", () => { + const result = runRuntimeEnvJsonValidation(Buffer.alloc(MAX_ENV_BYTES + 1, 0x20)); + + expect(result.status).toBe(1); + expect(result.stderr).toContain(`${MAX_ENV_BYTES}-byte limit`); + }); + it("accepts the provider-assigned Hermes API port in the runtime environment", () => { const result = runRuntimeEnvValidation({ NEMOCLAW_HERMES_API_PORT: "8645" }); @@ -572,8 +635,22 @@ describe("Hermes durable lazy-install target", () => { expect(refused.stderr).toContain("HERMES_LAZY_INSTALL_TARGET"); }); - it("uses launcher-owned paths when the supervisor environment predates shell exports", () => { - const result = runManagedGatewayEnvValidation({}); + it("derives launcher-owned sandbox paths for managed restart validation", () => { + const result = runManagedGatewayEnvValidation({}, false); + + expect(result.status, result.stderr).toBe(0); + expect(result.stderr).toBe(""); + }); + + it("replaces supervisor path values with the canonical managed-restart paths (#10963)", () => { + const result = runManagedGatewayEnvValidation( + { + HERMES_LAZY_INSTALL_TARGET: "/tmp/untrusted-packages", + HERMES_HOME: "/sandbox/other-home", + HERMES_BUNDLED_PLUGINS: "/sandbox/hostile-plugins", + }, + false, + ); expect(result.status, result.stderr).toBe(0); expect(result.stderr).toBe(""); diff --git a/test/agents/hermes/hermes-gateway-wrapper.test.ts b/test/agents/hermes/hermes-gateway-wrapper.test.ts index 56c493ee1d7..a66c3aabedf 100644 --- a/test/agents/hermes/hermes-gateway-wrapper.test.ts +++ b/test/agents/hermes/hermes-gateway-wrapper.test.ts @@ -93,20 +93,19 @@ describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py", () => { }); it("allows `gateway` when only resolver placeholders / allow-listed keys are present", () => { - const run = runWrapper( - ["gateway", "run"], - { - SLACK_BOT_TOKEN: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", - TELEGRAM_BOT_TOKEN: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", - OPENCLAW_GATEWAY_TOKEN: "raw-gateway-token", - }, - { validatorScript: "raise SystemExit(0)\n" }, - ); + const run = runWrapper(["gateway", "run"], { + SLACK_BOT_TOKEN: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + TELEGRAM_BOT_TOKEN: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + OPENCLAW_GATEWAY_TOKEN: "raw-gateway-token", + }); expect(run.status).toBe(0); expect(run.stderr).toBe(""); expect(run.realInvoked).toBe(true); expect(run.realArgs).toBe("gateway run"); + expect(run.realEnv.HERMES_LAZY_INSTALL_TARGET).toBe( + "/sandbox/.hermes/lazy-packages", + ); }); it("scrubs package-manager and Python startup inputs before a root-separated gateway exec", () => { @@ -130,7 +129,21 @@ describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py", () => { VIRTUAL_ENV: "/sandbox/venv", PATH: "/sandbox/bin", }, - { validatorScript: "raise SystemExit(0)\n" }, + { + validatorScript: [ + "import json, os, sys", + "logical_env = json.load(sys.stdin)", + "assert logical_env.get('PIP_CONFIG_FILE') == '/sandbox/pip.conf'", + "assert logical_env.get('LD_PRELOAD') == '/sandbox/hostile.so'", + "assert os.environ.get('HERMES_LAZY_INSTALL_TARGET') == '/run/nemoclaw/hermes-gateway-lazy-packages'", + "blocked = ('BASH_ENV', 'ENV', 'PATH', 'VIRTUAL_ENV')", + "prefixes = ('DYLD_', 'LD_', 'UV_', 'PIP_', 'PYTHON')", + "assert not any(key in os.environ for key in blocked)", + "assert not any(key.startswith(prefixes) for key in os.environ)", + "raise SystemExit(0)", + "", + ].join("\n"), + }, ); expect(run.status, run.stderr).toBe(0); @@ -164,32 +177,78 @@ describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py", () => { }); }); - it.each([ - ["sandbox-owned", "/sandbox/.hermes/lazy-packages"], - ["arbitrary", "/tmp/attacker-controlled-python"], - ])("replaces a %s lazy target before gateway validation and exec", (_label, lazyTarget) => { - const run = runWrapper( - ["gateway", "run"], - { - HERMES_LAZY_INSTALL_TARGET: lazyTarget, - UV_CONFIG_FILE: "/sandbox/uv.toml", - PIP_CONFIG_FILE: "/sandbox/pip.conf", - PYTHONPATH: "/sandbox/python", - }, - { validatorScript: "raise SystemExit(0)\n" }, - ); + it("uses only managed package-manager and Python startup values for a same-identity gateway exec", () => { + const run = runWrapper(["gateway", "run"], { + UV_CONFIG_FILE: "/sandbox/uv.toml", + UV_INDEX_URL: "file:///sandbox/wheels", + UV_NO_CONFIG: "0", + PIP_CONFIG_FILE: "/sandbox/pip.conf", + PIP_INDEX_URL: "file:///sandbox/wheels", + PIP_DISABLE_PIP_VERSION_CHECK: "0", + PYTHONPATH: "/sandbox/python", + PYTHONHOME: "/sandbox/python-home", + PYTHONSAFEPATH: "0", + PYTHONNOUSERSITE: "0", + PYTHONUTF8: "0", + LD_PRELOAD: "/sandbox/hostile.so", + BASH_ENV: "/sandbox/bash-env", + VIRTUAL_ENV: "/sandbox/venv", + PATH: "/sandbox/bin", + }); expect(run.status, run.stderr).toBe(0); expect(run.realInvoked).toBe(true); expect(run.realEnv.HERMES_HOME).toBe("/sandbox/.hermes"); expect(run.realEnv.HERMES_BUNDLED_PLUGINS).toBe("/opt/hermes/plugins"); expect(run.realEnv.HERMES_LAZY_INSTALL_TARGET).toBe( - "/run/nemoclaw/hermes-gateway-lazy-packages", + "/sandbox/.hermes/lazy-packages", ); expect(run.realEnv.HOME).toBe("/sandbox"); - expect(run.realEnv.UV_CONFIG_FILE).toBeUndefined(); - expect(run.realEnv.PIP_CONFIG_FILE).toBe("/dev/null"); - expect(run.realEnv.PYTHONPATH).toBeUndefined(); + const packageEnvironment = Object.fromEntries( + Object.entries(run.realEnv).filter( + ([name]) => + name.startsWith("UV_") || + name.startsWith("PIP_") || + name.startsWith("PYTHON") || + name.startsWith("LD_") || + ["BASH_ENV", "VIRTUAL_ENV", "PATH"].includes(name), + ), + ); + expect(packageEnvironment).toEqual({ + UV_NO_CONFIG: "1", + UV_NO_CACHE: "1", + UV_CACHE_DIR: "/sandbox/.hermes/lazy-packages/.uv-cache", + PIP_CONFIG_FILE: "/dev/null", + PIP_DISABLE_PIP_VERSION_CHECK: "1", + PYTHONSAFEPATH: "1", + PYTHONNOUSERSITE: "1", + PYTHONUTF8: "1", + PATH: "/usr/local/bin:/opt/hermes/.venv/bin:/usr/sbin:/usr/bin:/sbin:/bin", + }); + }); + + it("rejects an arbitrary gateway lazy target without exposing its value", () => { + const arbitraryTarget = "/tmp/attacker-controlled-python"; + const run = runWrapper(["gateway", "run"], { + HERMES_LAZY_INSTALL_TARGET: arbitraryTarget, + }); + + expect(run.status).toBe(1); + expect(run.stderr).toContain("HERMES_LAZY_INSTALL_TARGET"); + expect(run.stderr).not.toContain(arbitraryTarget); + expect(run.stdout).not.toContain(arbitraryTarget); + expect(run.realInvoked).toBe(false); + }); + + it("rejects a package-prefixed raw secret without exposing its value", () => { + const secret = "pypi-secret-value-that-must-not-leak"; + const run = runWrapper(["gateway", "run"], { PIP_API_KEY: secret }); + + expect(run.status).toBe(1); + expect(run.stderr).toContain("PIP_API_KEY"); + expect(run.stderr).not.toContain(secret); + expect(run.stdout).not.toContain(secret); + expect(run.realInvoked).toBe(false); }); it("refuses a direct root gateway before invoking the real binary", () => { @@ -270,7 +329,7 @@ describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py", () => { expect(run.status).not.toBe(0); const argv = fs.readFileSync(argvLog, "utf-8").trim().split("\n"); expect(argv[0]).toBe("-I"); - expect(argv[argv.length - 1]).toBe("runtime-env"); + expect(argv[argv.length - 1]).toBe("runtime-env-json"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } diff --git a/test/agents/hermes/hermes-image-build-probes.test.ts b/test/agents/hermes/hermes-image-build-probes.test.ts index 64597db7e80..013bde1a97b 100644 --- a/test/agents/hermes/hermes-image-build-probes.test.ts +++ b/test/agents/hermes/hermes-image-build-probes.test.ts @@ -187,11 +187,11 @@ describe("Hermes image build probes", () => { // source-shape-contract: security -- The final image must execute the reviewed runtime environment validator bytes it("binds the runtime environment validator to its source digest", () => { const imageDockerfile = fs.readFileSync( - path.join(process.cwd(), "agents", "hermes", "Dockerfile"), + path.join(import.meta.dirname, "../../../agents/hermes/Dockerfile"), "utf8", ); const runtimeEnvValidator = fs.readFileSync( - path.join(process.cwd(), "agents", "hermes", "validate-env-secret-boundary.py"), + path.join(import.meta.dirname, "../../../agents/hermes/validate-env-secret-boundary.py"), ); const digest = createHash("sha256").update(runtimeEnvValidator).digest("hex"); const digestBinding = `ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=${digest}`; @@ -207,6 +207,29 @@ describe("Hermes image build probes", () => { ); }); + // source-shape-contract: security -- The final image must execute the reviewed Hermes wrapper bytes + it("binds the Hermes wrapper to its source digest", () => { + const imageDockerfile = fs.readFileSync( + path.join(import.meta.dirname, "../../../agents/hermes/Dockerfile"), + "utf8", + ); + const hermesWrapper = fs.readFileSync( + path.join(import.meta.dirname, "../../../agents/hermes/hermes-wrapper.py"), + ); + const digest = createHash("sha256").update(hermesWrapper).digest("hex"); + const digestBinding = `ARG NEMOCLAW_HERMES_WRAPPER_SHA256=${digest}`; + const integrityCheck = + '"$NEMOCLAW_HERMES_WRAPPER_SHA256" /usr/local/lib/nemoclaw/hermes-wrapper.py'; + const bindingIndex = imageDockerfile.indexOf(digestBinding); + const integrityCheckIndex = imageDockerfile.indexOf(integrityCheck, bindingIndex); + + expect(bindingIndex).toBeGreaterThan(-1); + expect(integrityCheckIndex).toBeGreaterThan(bindingIndex); + expect(imageDockerfile.indexOf("| sha256sum -c -", integrityCheckIndex)).toBeGreaterThan( + integrityCheckIndex, + ); + }); + it("removes the Hindsight probe wheel after staging its temporary copy", () => { const probeWheel = "/opt/nemoclaw-hermes-config/hindsight-probe-aiohttp-retry.whl"; const copyIndex = dockerfile.indexOf(`cp ${probeWheel}`); diff --git a/test/e2e/live/mcp-bridge-hermes-lifecycle.ts b/test/e2e/live/mcp-bridge-hermes-lifecycle.ts index 0bfc59da848..99e1b291aa0 100644 --- a/test/e2e/live/mcp-bridge-hermes-lifecycle.ts +++ b/test/e2e/live/mcp-bridge-hermes-lifecycle.ts @@ -48,7 +48,8 @@ export async function assertHermesConfig( /** * Focused #7499 live regression after the supported managed add has executed * the real unprivileged Hermes transaction: restart the real gateway, then - * prove the config and transaction state remain current. + * prove the strict baseline remains root-owned while the compatibility hash + * matches the managed config and transaction state. */ export async function assertHermesManagedAddSurvivesGatewayRestartAndStateLayout( host: HostCliClient, @@ -66,26 +67,38 @@ export async function assertHermesManagedAddSurvivesGatewayRestartAndStateLayout expect(resultText(restart)).toContain("Gateway restarted"); expect(resultText(restart)).toContain("health passed"); - const integrity = await sandbox.execShell( + const compatibilityIntegrity = await sandbox.execShell( sandboxName, trustedSandboxShellScript( [ - "set -eu", - "cmp -s /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", - "sha256sum -c /etc/nemoclaw/hermes.config-hash --status", - "sha256sum -c /sandbox/.hermes/.config-hash --status", - "echo HERMES_MCP_INTEGRITY_CURRENT", + "set -u", + "echo HERMES_MCP_STRICT_HASH", + "cat /etc/nemoclaw/hermes.config-hash", + "echo HERMES_MCP_COMPAT_HASH", + "cat /sandbox/.hermes/.config-hash", + "strict_status=0; sha256sum -c /etc/nemoclaw/hermes.config-hash || strict_status=$?", + "compat_status=0; sha256sum -c /sandbox/.hermes/.config-hash || compat_status=$?", + 'printf "HERMES_MCP_HASH_STATUS strict=%s compat=%s\\n" "$strict_status" "$compat_status"', + "set -e", + 'test "$(stat -c \'%u:%g:%a\' /etc/nemoclaw/hermes.config-hash)" = "0:0:444"', + "! cmp -s /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + 'test "$strict_status" -ne 0', + 'test "$compat_status" -eq 0', + "echo HERMES_MCP_COMPAT_INTEGRITY_CURRENT", ].join("\n"), ), { - artifactName: "hermes-mcp-integrity-after-add-gateway-restart", + artifactName: "hermes-mcp-compat-integrity-after-add-gateway-restart", env: buildAvailabilityProbeEnv(), redactionValues: [HOST_SECRET, ROTATED_HOST_SECRET], timeoutMs: 60_000, }, ); - expectExitZero(integrity, "Hermes MCP integrity anchors after gateway restart"); - expect(integrity.stdout).toContain("HERMES_MCP_INTEGRITY_CURRENT"); + expectExitZero( + compatibilityIntegrity, + "Hermes MCP strict baseline and compatibility integrity after gateway restart", + ); + expect(compatibilityIntegrity.stdout).toContain("HERMES_MCP_COMPAT_INTEGRITY_CURRENT"); const list = await host.nemoclaw([sandboxName, "mcp", "list", "--json"], { artifactName: "hermes-mcp-list-after-add-gateway-restart", diff --git a/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts b/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts index d666412d8f9..544eb6435f5 100644 --- a/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts +++ b/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts @@ -189,7 +189,7 @@ describe("Hermes MCP managed configuration assertion", () => { }); describe("Hermes MCP gateway restart", () => { - it("preserves managed config and integrity through restart", async () => { + it("keeps the strict baseline root-owned and compatibility integrity current", async () => { const mcpUrl = "https://mcp.example.test/mcp"; const hostRunner = new RecordingRunner([ shellResult(0, "Gateway restarted\nhealth passed\n"), @@ -201,7 +201,7 @@ describe("Hermes MCP gateway restart", () => { ), ]); const sandboxRunner = new RecordingRunner([ - shellResult(0, "HERMES_MCP_INTEGRITY_CURRENT\n"), + shellResult(0, "HERMES_MCP_COMPAT_INTEGRITY_CURRENT\n"), shellResult(0, `${JSON.stringify({ state: "matched" })}\n`), ]); @@ -222,5 +222,10 @@ describe("Hermes MCP gateway restart", () => { args: ["hermes-e2e", "mcp", "list", "--json"], }), ]); + expect(sandboxRunner.calls[0]?.args.at(-1)).toContain( + "! cmp -s /etc/nemoclaw/hermes.config-hash /sandbox/.hermes/.config-hash", + ); + expect(sandboxRunner.calls[0]?.args.at(-1)).toContain('test "$strict_status" -ne 0'); + expect(sandboxRunner.calls[0]?.args.at(-1)).toContain('test "$compat_status" -eq 0'); }); }); diff --git a/test/inference/managed/managed-gateway-control.test.ts b/test/inference/managed/managed-gateway-control.test.ts index d3a68fa2daa..638bb3b4307 100644 --- a/test/inference/managed/managed-gateway-control.test.ts +++ b/test/inference/managed/managed-gateway-control.test.ts @@ -416,7 +416,6 @@ with tempfile.TemporaryDirectory() as root: # The preceding cases recreate fake PIDs 40 and 41, so refresh their # inode-bound identities before testing stable reads and signals. supervisor = control._discover_supervisor(reader) - preflight_steps = [] real_validator = control._run_fixed_validator real_runtime_validator = control._validate_managed_gateway_environment @@ -429,6 +428,7 @@ with tempfile.TemporaryDirectory() as root: "script": script, "arguments": ["runtime-env"], "runtime_port": environment.get("NEMOCLAW_DASHBOARD_PORT"), + "managed_paths_present": any(key in environment for key in ("HERMES_LAZY_INSTALL_TARGET", "HERMES_HOME", "HERMES_BUNDLED_PLUGINS")), }) control._verify_locked_hermes_hash = lambda: preflight_steps.append({"hash": "checked"}) try: @@ -495,9 +495,9 @@ with tempfile.TemporaryDirectory() as root: reader.capture = real_capture control.time.monotonic = real_monotonic control.time.sleep = real_sleep + supervisor_environment_path = os.path.join(proc_root, "40", "environ") control._validate_managed_gateway_environment = real_runtime_validator control._hermes_preflight(reader, supervisor) - supervisor_environment_path = os.path.join(proc_root, "40", "environ") with open(supervisor_environment_path, "wb") as stream: stream.write( b"PATH=/usr/bin\0HERMES_ENABLE_PROJECT_PLUGINS=1\0" ) @@ -515,7 +515,6 @@ with tempfile.TemporaryDirectory() as root: control._run_fixed_validator = real_validator control._validate_managed_gateway_environment = real_runtime_validator control._verify_locked_hermes_hash = real_hash_check - write_process( proc_root, namespace_path, @@ -1337,6 +1336,7 @@ describe("managed gateway root control", () => { ), arguments: ["runtime-env"], runtime_port: "18789", + managed_paths_present: false, }, { hash: "checked" }, ],