Skip to content

The agent that grows with you

fix: verify effective systemd profile and account before ensure starts

Tekniumefadac8de2e9
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.py
index 7134b759a82..05fc5a1a62e 100644
--- a/hermes_cli/gateway_runtime_service.py
+++ b/hermes_cli/gateway_runtime_service.py
@@ -67,6 +67,7 @@ def _exists(path: Path) -> bool:
def _systemd(home: Path, deadline: float) -> ExistingService | None:
from hermes_cli import gateway as gw
from hermes_cli.service_manager import _s6_running
+ from hermes_cli.gateway_runtime_service_identity import SYSTEMD_IDENTITY_PROPERTIES, verify_systemd
if _s6_running():
raise RuntimeStartError("external_supervisor")
suffix = service_suffix(home)
@@ -82,7 +83,7 @@ def _systemd(home: Path, deadline: float) -> ExistingService | None:
for system in (False, True):
command = gw._systemctl_cmd(system)
result = _run([*command, "show", unit, "--no-pager",
- "--property=LoadState,ActiveState,SubState,UnitFileState"], deadline)
+ "--property=LoadState,ActiveState,SubState,UnitFileState," + ",".join(SYSTEMD_IDENTITY_PROPERTIES)], deadline)
props = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
if props.get("LoadState") == "not-found" and not _exists(paths[int(system)]):
continue
@@ -97,6 +98,16 @@ def _systemd(home: Path, deadline: float) -> ExistingService | None:
raise RuntimeStartError("service_state_unknown")
if state == "failed":
raise RuntimeStartError("service_failed")
+ environment = _run([*command, "show-environment"], deadline)
+ if environment.returncode:
+ raise RuntimeStartError("service_identity_unverified")
+ try:
+ verify_systemd(props, environment.stdout, home, system=system)
+ except ValueError as exc:
+ reason = str(exc)
+ raise RuntimeStartError(reason if reason in {
+ "profile_mismatch", "service_account_mismatch"
+ } else "service_identity_unverified") from None
found.append(ExistingService("systemd", tuple([*command, "--no-ask-password", "start", unit]),
state != "inactive"))
if len(found) > 1:
diff --git a/hermes_cli/gateway_runtime_service_identity.py b/hermes_cli/gateway_runtime_service_identity.py
new file mode 100644
index 00000000000..1cd545cd677
--- /dev/null
+++ b/hermes_cli/gateway_runtime_service_identity.py
@@ -0,0 +1,142 @@
+"""Read-only binding checks; unknown supervisor syntax is not profile absence.
+
+These checks recognize the installed Hermes launch formats, not arbitrary shell
+programs. Manager-loaded values take precedence over filenames and disk copies.
+"""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import re
+import shlex
+from typing import NoReturn
+
+
+SYSTEMD_IDENTITY_PROPERTIES = (
+ "User", "DynamicUser", "ExecStart", "Environment", "EnvironmentFiles",
+ "PassEnvironment", "UnsetEnvironment", "PAMName", "RootDirectory", "RootImage",
+ "ExecStartPre", "ExecCondition", "DropInPaths",
+)
+
+
+def _unverified() -> NoReturn:
+ raise ValueError("service_identity_unverified")
+
+
+def _absolute(value: str) -> Path:
+ if not value or not Path(value).is_absolute():
+ _unverified()
+ return Path(value).resolve()
+
+
+def verify_home(home: Path, configured: str) -> None:
+ if os.path.normcase(str(_absolute(configured))) != os.path.normcase(str(home.resolve())):
+ raise ValueError("profile_mismatch")
+
+
+def verify_gateway_argv(argv: list[str], home: Path) -> None:
+ from gateway.status import looks_like_gateway_command_line
+
+ # The installer wraps launchd stderr with this fixed, non-shell module.
+ if len(argv) > 7 and argv[1:4] == ["-m", "hermes_cli.stderr_timestamp", "--error-log"] and argv[5] == "--":
+ argv = argv[6:]
+ if not argv or not looks_like_gateway_command_line(subprocess_command(argv)):
+ _unverified()
+ executable = Path(argv[0]).name.lower()
+ if re.fullmatch(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?", executable):
+ if argv[1:3] != ["-m", "hermes_cli.main"]:
+ _unverified()
+ args = argv[3:]
+ elif executable in {"hermes", "hermes.exe"}:
+ args = argv[1:]
+ else:
+ _unverified()
+ profiles = []
+ filtered = []
+ index = 0
+ while index < len(args):
+ token = args[index]
+ if token in {"--profile", "-p"}:
+ index += 1
+ if index == len(args):
+ _unverified()
+ profiles.append(args[index])
+ elif token.startswith("--profile="):
+ profiles.append(token.split("=", 1)[1])
+ else:
+ filtered.append(token)
+ index += 1
+ if len(profiles) > 1:
+ _unverified()
+ if profiles:
+ # An explicit selector must agree with the pinned environment. This
+ # preserves custom-root profiles without borrowing the caller's root.
+ expected = home.name if home.parent.name == "profiles" else "default"
+ if profiles[0] != expected:
+ raise ValueError("profile_mismatch")
+ if filtered[:2] != ["gateway", "run"] or any(
+ arg not in {"--quiet", "--external-supervisor"} for arg in filtered[2:]
+ ):
+ _unverified()
+
+
+def subprocess_command(argv: list[str]) -> str:
+ # The canonical matcher is quote-aware on both hosts.
+ import subprocess
+ return subprocess.list2cmdline(argv)
+
+
+def environment_pairs(value: str) -> dict[str, str]:
+ # systemctl uses C escapes for unusual bytes. Do not silently reinterpret
+ # those with shell escaping (not the same grammar).
+ if "\\" in value:
+ _unverified()
+ result = {}
+ for item in shlex.split(value):
+ key, separator, val = item.partition("=")
+ if not separator:
+ _unverified()
+ result[key] = val
+ return result
+
+
+def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, system: bool) -> None:
+ import pwd
+
+ if not all(key in props for key in SYSTEMD_IDENTITY_PROPERTIES):
+ _unverified()
+ # These can change the execution account, environment, mount namespace, or
+ # definitions at start time; show does not expose their resulting identity.
+ if props["DynamicUser"] != "no" or any(props[key] for key in (
+ "EnvironmentFiles", "PAMName", "RootDirectory", "RootImage", "ExecStartPre", "ExecCondition",
+ )):
+ _unverified()
+ user = props["User"]
+ uid = os.getuid() # windows-footgun: ok — native systemd only
+ if user:
+ try:
+ service_uid = int(user) if user.isdecimal() else pwd.getpwnam(user).pw_uid
+ except KeyError:
+ _unverified()
+ else:
+ service_uid = 0 if system else uid
+ if service_uid != uid:
+ raise ValueError("service_account_mismatch")
+ inherited = environment_pairs(manager_env)
+ env = inherited if not system else {k: v for k, v in inherited.items() if k in props["PassEnvironment"].split()}
+ env.update(environment_pairs(props["Environment"]))
+ for item in shlex.split(props["UnsetEnvironment"]):
+ key, sep, value = item.partition("=")
+ if not sep or env.get(key) == value:
+ env.pop(key, None)
+ configured = env.get("HERMES_HOME", "").strip()
+ if not configured:
+ configured = str(_absolute(env.get("HOME") or pwd.getpwuid(uid).pw_dir) / ".hermes")
+ verify_home(home, configured)
+ match = re.fullmatch(r"\{ path=(.*?) ; argv\[\]=(.*?) ; ignore_errors=(?:yes|no) ;(?:.*?)\}", props["ExecStart"])
+ if not match or any(char in match[2] for char in ("$", "\\", "{", "}")):
+ _unverified()
+ argv = shlex.split(match[2])
+ if not argv or match[1] != argv[0]:
+ _unverified()
+ verify_gateway_argv(argv, home)
diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.py
index e00b374adcf..5929d6763ea 100644
--- a/tests/hermes_cli/test_gateway_runtime_ensure.py
+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py
@@ -65,13 +65,20 @@ def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(
original = unit.read_bytes()
calls = tmp_path / "calls.jsonl"
helper = tmp_path / "inert-supervisor"
+ from hermes_cli.gateway_runtime_service_identity import SYSTEMD_IDENTITY_PROPERTIES
+ identity = {key: "" for key in SYSTEMD_IDENTITY_PROPERTIES}
+ identity.update(User=str(os.getuid()), DynamicUser="no",
+ Environment=f'"HERMES_HOME={home}"',
+ ExecStart=f'{{ path={sys.executable} ; argv[]={sys.executable} -m hermes_cli.main gateway run ; ignore_errors=no ; }}')
+ effective = "\n".join(f"{key}={value}" for key, value in identity.items())
helper.write_text('#!' + sys.executable + '\nimport json,sys,time\nfrom pathlib import Path\n'
+ f'p=Path({str(calls)!r})\n'
+ 'with p.open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
+ 'if (p.parent/"stall").exists(): time.sleep(5)\n'
+ 'if (p.parent/"fail").exists(): print("private-supervisor-token"); sys.exit(3)\n'
+ 'if "show" in sys.argv and "system" in sys.argv and (p.parent/"single").exists():\n print("LoadState=not-found")\n'
- + 'elif "show" in sys.argv:\n print("LoadState=loaded\\nActiveState=inactive\\nSubState=dead\\nUnitFileState=enabled")\n'
+ + 'elif "show-environment" in sys.argv: print("")\n'
+ + 'elif "show" in sys.argv:\n print("LoadState=loaded\\nActiveState=inactive\\nSubState=dead\\nUnitFileState=enabled"); print(' + repr(effective) + ')\n'
+ 'elif "start" in sys.argv: sys.exit(0)\n'
+ 'else: sys.exit(91)\n', encoding="utf-8")
helper.chmod(0o700)
@@ -81,7 +88,7 @@ def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(
assert result.state == "conflict"
assert unit.read_bytes() == original
assert not (home / "logs").exists()
- assert all("show" in json.loads(line) for line in calls.read_text().splitlines())
+ assert all(any(arg in {"show", "show-environment"} for arg in json.loads(line)) for line in calls.read_text().splitlines())
(tmp_path / "single").touch()
result = runtime.ensure_gateway_runtime(home, timeout=0.5)
assert result.state == "starting" and result.reason_code == "deadline"
diff --git a/tests/hermes_cli/test_gateway_runtime_service.py b/tests/hermes_cli/test_gateway_runtime_service.py
new file mode 100644
index 00000000000..f466e8e12d7
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_runtime_service.py
@@ -0,0 +1,101 @@
+"""Installed identity proofs at inert native supervisor executable boundaries."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+import pytest
+
+
[email protected]("case,reason", [
+ ("custom", "deadline"), ("named", "deadline"), ("alias", "deadline"),
+ ("default", "deadline"),
+ ("wrong_home", "profile_mismatch"), ("wrong_user", "service_account_mismatch"),
+ ("missing_identity", "service_identity_unverified"),
+ ("env_file", "service_identity_unverified"), ("dynamic_user", "service_identity_unverified"),
+ ("wrong_command", "service_identity_unverified"), ("command_profile", "profile_mismatch"),
+ ("dropin_home", "profile_mismatch"), ("manager_home", "profile_mismatch"),
+])
+def test_ensure_checks_effective_service_binding_before_start(tmp_path, monkeypatch, case, reason):
+ from hermes_cli import gateway_runtime as runtime
+ from hermes_cli.gateway_runtime_service import service_suffix
+ import pwd
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ home = tmp_path / (".hermes" if case == "default" else "custom root")
+ if case == "named":
+ home = home / "profiles" / "worker"
+ home.mkdir(mode=0o700, parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ suffix = service_suffix(home)
+ unit = tmp_path / ".config/systemd/user" / f"hermes-gateway{'-' + suffix if suffix else ''}.service"
+ unit.parent.mkdir(parents=True)
+ unit.write_text(f'[Service]\nExecStart={sys.executable} -m hermes_cli.main gateway run\nEnvironment="HERMES_HOME={home}"\n', encoding="utf-8")
+ original = unit.read_bytes()
+ configured = home
+ if case in {"wrong_home", "dropin_home"}:
+ configured = tmp_path / "unrequested"
+ if case == "alias":
+ configured = tmp_path / "alias"
+ configured.symlink_to(home, target_is_directory=True)
+ command = f'{sys.executable} -m hermes_cli.main gateway run'
+ if case == "named":
+ command += " --profile worker"
+ if case == "command_profile":
+ command += " --profile stranger"
+ if case == "wrong_command":
+ command = '/bin/echo hermes_cli.main gateway run'
+ props = dict(LoadState="loaded", ActiveState="inactive", SubState="dead", UnitFileState="enabled",
+ User=str(os.getuid()), DynamicUser="no", Environment=f'"HERMES_HOME={configured}" "HERMES_SUPERVISED_CHILD=1"',
+ EnvironmentFiles="", PassEnvironment="", UnsetEnvironment="", PAMName="",
+ RootDirectory="", RootImage="", ExecStartPre="", ExecCondition="",
+ ExecStart=f'{{ path={command.split()[0]} ; argv[]={command} ; ignore_errors=no ; }}',
+ DropInPaths=str(unit.parent / (unit.name + '.d') / 'override.conf') if case == "dropin_home" else "")
+ manager_env = ""
+ if case == "wrong_user":
+ props['User'] = str(os.getuid() + 1)
+ if case == "missing_identity":
+ props = {k: props[k] for k in ("LoadState", "ActiveState", "SubState", "UnitFileState")}
+ if case == "env_file":
+ env_file = tmp_path / "override.env"
+ env_file.write_text(f'HERMES_HOME={tmp_path / "other"}\n', encoding="utf-8")
+ props['EnvironmentFiles'] = f'{env_file} (ignore_errors=no)'
+ if case == "dynamic_user":
+ props['DynamicUser'] = 'yes'
+ if case == "manager_home":
+ props['Environment'] = 'HERMES_SUPERVISED_CHILD=1'
+ manager_env = f'HERMES_HOME={tmp_path / "other"}\n'
+ if case == "default":
+ # An older default install may rely on the user manager's HOME.
+ props['Environment'] = 'HERMES_SUPERVISED_CHILD=1'
+ manager_env = f'HOME={tmp_path}\n'
+ if case == "system":
+ props['User'] = pwd.getpwuid(os.getuid()).pw_name
+ definition = tmp_path / "effective.json"
+ definition.write_text(json.dumps({'props': props, 'system': case == 'system', 'env': manager_env}), encoding="utf-8")
+ calls = tmp_path / 'calls.jsonl'
+ executable = tmp_path / 'inert-supervisor'
+ executable.write_text('#!' + sys.executable + '\nimport json,sys\nfrom pathlib import Path\n'
+ + f'p=Path({str(tmp_path)!r})\nd=json.loads((p/"effective.json").read_text())\n'
+ + 'with (p/"calls.jsonl").open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
+ + 'if "show-environment" in sys.argv: print(d["env"])\n'
+ + 'elif "show" in sys.argv:\n'
+ + ' if ("--user" not in sys.argv) == d["system"]: print("\\n".join(k+"="+v for k,v in d["props"].items()))\n'
+ + ' else: print("LoadState=not-found")\n'
+ + 'elif "start" not in sys.argv: sys.exit(91)\n', encoding='utf-8')
+ executable.chmod(0o700)
+ monkeypatch.setenv('PATH', str(tmp_path) + os.pathsep + os.environ['PATH'])
+ from hermes_cli import gateway as gw
+ monkeypatch.setattr(gw, "_systemctl_cmd", lambda system=False: [str(executable)] + ([] if system else ["--user"]))
+ result = runtime.ensure_gateway_runtime(home, timeout=0.5)
+ assert result.reason_code == reason
+ commands = [json.loads(line) for line in calls.read_text().splitlines()]
+ starts = [cmd for cmd in commands if 'start' in cmd]
+ assert len(starts) == (1 if reason == 'deadline' else 0)
+ assert all('--no-ask-password' in cmd for cmd in starts)
+ if case != 'system':
+ assert unit.read_bytes() == original
+ assert not (home / 'logs').exists()