Skip to content

The agent that grows with you

fix(gateway): never stop/restart/start another install's systemd unit from a sandbox home

Luke Chinyamaf02efc45397b
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 99fa990b77c..3608069b373 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1253,6 +1253,62 @@ def _hermes_home_from_systemd_unit_file(system: bool = False) -> str | None:
return _hermes_home_pinned_by_unit(get_systemd_unit_path(system=system))
+def _account_default_hermes_home() -> Path | None:
+ """``<account home>/.hermes`` from the passwd database — NOT ``$HOME``, which test harnesses and
+ profile isolation repoint. None where the account is unknown."""
+ try:
+ import pwd
+ return Path(pwd.getpwuid(os.geteuid()).pw_dir) / ".hermes"
+ except (ImportError, KeyError, OSError):
+ return None
+
+
+def _foreign_systemd_unit_home(system: bool) -> str | None:
+ """``HERMES_HOME`` of the unit at this scope when it belongs to ANOTHER install, else None.
+
+ The service name only encodes the home relative to the process's own ``$HOME``, so a process whose
+ ``HERMES_HOME`` is ``$HOME/.hermes`` under a throwaway ``HOME`` (test harnesses, CI sandboxes,
+ scripted installs) resolves the bare ``hermes-gateway`` name — and a system unit is global, so it
+ resolves the PRODUCTION unit. ``_sync_hermes_home_from_systemd_unit`` would then adopt that unit's
+ home and ``stop``/``restart`` would take the live gateway down. Must be evaluated BEFORE that sync.
+
+ Foreign means: the unit pins a home, it differs from this process's home, and this process's home
+ is not the account's own default root. The last clause keeps the ``sudo`` remap (#108674): root's
+ default home operating a unit that pins the invoking user's home is the operator, not a stranger.
+ """
+ unit_home = _hermes_home_pinned_by_unit(get_systemd_unit_path(system=system))
+ if not unit_home:
+ return None
+ try:
+ unit = Path(unit_home).expanduser().resolve()
+ mine = get_hermes_home().resolve()
+ except OSError:
+ return None
+ if unit == mine:
+ return None
+ account_default = _account_default_hermes_home()
+ if account_default is not None:
+ try:
+ if mine == account_default.resolve():
+ return None
+ except OSError:
+ pass
+ return unit_home
+
+
+def _refuse_foreign_systemd_unit(action: str, system: bool) -> None:
+ """Exit non-zero instead of operating another install's unit (see ``_foreign_systemd_unit_home``)."""
+ unit_home = _foreign_systemd_unit_home(system)
+ if unit_home is None:
+ return
+ print_error(
+ f"Refusing to {action} {get_service_name()}: that {_service_scope_label(system)} unit runs "
+ f"HERMES_HOME={unit_home}, but this process has HERMES_HOME={get_hermes_home()}.\n"
+ f"It belongs to another Hermes install. Run this from that install's HERMES_HOME."
+ )
+ sys.exit(1)
+
+
def _sync_hermes_home_from_systemd_unit(system: bool) -> None:
"""Adopt a system-scope unit's ``HERMES_HOME``: under ``sudo`` it is stripped and HOME=/root, so
get_hermes_home() would pick the wrong profile for runtime-status/PID reads."""
@@ -3652,6 +3708,13 @@ def _systemd_scope_preamble(
def _systemd_unit_belongs_to_current_home(system: bool = False) -> bool:
"""False (with a warning) when the installed unit pins a HERMES_HOME other than this process's: the
service name then resolved to ANOTHER install's gateway, and stop/disable/unlink would take it down."""
+ foreign = _foreign_systemd_unit_home(system) # before the sync below rewrites this process's home
+ if foreign is not None:
+ print_warning(
+ f"Refusing to remove {get_systemd_unit_path(system=system)}: it runs HERMES_HOME={foreign}, "
+ f"but this process has HERMES_HOME={get_hermes_home()}"
+ )
+ return False
_sync_hermes_home_from_systemd_unit(system=system) # sudo strips HERMES_HOME; adopt the unit's first
unit_home = _hermes_home_from_systemd_unit_file(system=system)
if unit_home is None or Path(unit_home).expanduser().resolve() == get_hermes_home().resolve():
@@ -3693,6 +3756,7 @@ def _require_service_installed(action: str, system: bool = False) -> None:
def systemd_start(system: bool = False):
system = _systemd_scope_preamble("start", system, preflight_user=True)
+ _refuse_foreign_systemd_unit("start", system)
# HERMES_HOME sync happens in refresh's systemd_unit_is_current gate; the unit is guaranteed to exist here.
refresh_systemd_unit_if_needed(system=system)
_run_systemctl(["start", get_service_name()], system=system, check=True, timeout=30)
@@ -3701,6 +3765,7 @@ def systemd_start(system: bool = False):
def systemd_stop(system: bool = False):
system = _systemd_scope_preamble("stop", system)
+ _refuse_foreign_systemd_unit("stop", system)
_sync_hermes_home_from_systemd_unit(system=system)
_mark_planned_stop()
try:
@@ -3716,6 +3781,7 @@ def systemd_stop(system: bool = False):
def systemd_restart(system: bool = False):
system = _systemd_scope_preamble("restart", system, preflight_user=True)
+ _refuse_foreign_systemd_unit("restart", system)
# HERMES_HOME sync happens in refresh's systemd_unit_is_current gate; its os.environ mutation
# persists for the get_running_pid / drain-timeout reads below.
refresh_systemd_unit_if_needed(system=system)
@@ -4750,9 +4816,13 @@ def _running_under_s6() -> bool:
def _systemd_unit_installed() -> bool:
- return supports_systemd_services() and (
- get_systemd_unit_path(system=False).exists() or get_systemd_unit_path(system=True).exists()
- )
+ """A unit at either scope that serves THIS home. A unit pinned to another install's home is not
+ ours, so stop/restart/start fall through to this home's own gateway (PID path) instead of
+ operating the other install's service."""
+ if not supports_systemd_services():
+ return False
+ return any(get_systemd_unit_path(system=s).exists() and _foreign_systemd_unit_home(s) is None
+ for s in (False, True))
def _is_service_installed() -> bool:
diff --git a/tests/hermes_cli/test_gateway_foreign_unit_guard.py b/tests/hermes_cli/test_gateway_foreign_unit_guard.py
new file mode 100644
index 00000000000..c2d162f4193
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_foreign_unit_guard.py
@@ -0,0 +1,94 @@
+"""`hermes gateway stop|restart|start` from a sandbox home must never operate ANOTHER install's systemd unit.
+
+Real incident: an e2e helper ran `hermes gateway stop` with a throwaway ``HOME`` and
+``HERMES_HOME=$HOME/.hermes`` on a host whose production gateway is the system unit
+``hermes-gateway.service`` (``Environment=HERMES_HOME=/root/.hermes``). The sandbox home is the
+"default" home relative to its own ``HOME``, so the service name resolved to the bare
+``hermes-gateway``; system units are global, so that unit "existed"; ``_sync_hermes_home_from_systemd_unit``
+then adopted the production home and ``systemctl stop hermes-gateway`` took every bot offline.
+"""
+import os
+from pathlib import Path
+
+import pytest
+
+import hermes_cli.gateway as gateway_cli
+
+
+def host(tmp_path, monkeypatch):
+ """A production system unit pinned to ``prod``; the account's own default root is ``account``."""
+ prod = tmp_path / "prod" / ".hermes"
+ account = tmp_path / "account" / ".hermes"
+ sandbox_home = tmp_path / "sandbox"
+ for p in (prod, account, sandbox_home / ".hermes"):
+ p.mkdir(parents=True)
+ unit_dir = tmp_path / "systemd"
+ unit_dir.mkdir()
+ (unit_dir / f"{gateway_cli._SERVICE_BASE}.service").write_text(
+ f'[Service]\nEnvironment="HERMES_HOME={prod}"\nExecStart=/bin/true\n', encoding="utf-8")
+ monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir)
+ monkeypatch.setattr(gateway_cli, "user_systemd_unit_dir", lambda: tmp_path / "no-user-units")
+ monkeypatch.setattr(gateway_cli, "supports_systemd_services", lambda: True)
+ monkeypatch.setattr(gateway_cli, "_account_default_hermes_home", lambda: account, raising=False)
+ monkeypatch.setattr(os, "geteuid", lambda: 0)
+ # Never reach a real systemd: preamble/privilege checks are not under test, systemctl is recorded.
+ monkeypatch.setattr(gateway_cli, "_systemd_scope_preamble", lambda action, system, **_k: system)
+ monkeypatch.setattr(gateway_cli, "refresh_systemd_unit_if_needed", lambda system=False: None)
+ monkeypatch.setattr(gateway_cli, "_systemctl_show", lambda props, system=False: {})
+ monkeypatch.setattr(gateway_cli, "_mark_planned_stop", lambda *a, **k: None)
+ calls = []
+ monkeypatch.setattr(gateway_cli, "_run_systemctl", lambda args, **kw: calls.append(list(args)))
+ return {"prod": prod, "account": account, "sandbox_home": sandbox_home, "calls": calls}
+
+
+def _sandbox(monkeypatch, host):
+ monkeypatch.setenv("HOME", str(host["sandbox_home"]))
+ monkeypatch.setenv("HERMES_HOME", str(host["sandbox_home"] / ".hermes"))
+
+
+def test_sandbox_home_resolves_the_bare_name_but_the_unit_is_not_installed_for_it(host, monkeypatch):
+ _sandbox(monkeypatch, host)
+ assert gateway_cli.get_service_name() == gateway_cli._SERVICE_BASE # the hazard's precondition
+ assert gateway_cli._foreign_systemd_unit_home(True) == str(host["prod"])
+ assert gateway_cli._systemd_unit_installed() is False # `gateway stop` -> PID path
+ assert gateway_cli._installed_service_kind_for(lambda: False) is None
+
+
[email protected]("verb", ["stop", "restart", "start"])
+def test_direct_service_verbs_refuse_a_foreign_unit_without_touching_systemd(host, monkeypatch, verb):
+ _sandbox(monkeypatch, host)
+ with pytest.raises(SystemExit) as exc:
+ getattr(gateway_cli, f"systemd_{verb}")(system=True)
+ assert exc.value.code == 1
+ assert host["calls"] == []
+ assert os.environ["HERMES_HOME"] == str(host["sandbox_home"] / ".hermes") # never adopted prod's home
+
+
+def test_uninstall_guard_checks_before_the_home_sync(host, monkeypatch):
+ _sandbox(monkeypatch, host)
+ assert gateway_cli._systemd_unit_belongs_to_current_home(system=True) is False
+ assert os.environ["HERMES_HOME"] == str(host["sandbox_home"] / ".hermes")
+
+
+def test_sudo_from_the_account_default_home_still_operates_the_unit(host, monkeypatch):
+ """#108674: root's default home driving a unit that pins the invoking user's home is the operator."""
+ monkeypatch.setenv("HOME", str(host["account"].parent))
+ monkeypatch.setenv("HERMES_HOME", str(host["account"]))
+ assert gateway_cli._foreign_systemd_unit_home(True) is None
+ gateway_cli.systemd_stop(system=True)
+ assert host["calls"] == [["stop", gateway_cli.get_service_name()]]
+ assert Path(os.environ["HERMES_HOME"]) == host["prod"] # adopted, as before
+
+
+def test_the_units_own_home_operates_it(host, monkeypatch):
+ monkeypatch.setenv("HOME", str(host["prod"].parent))
+ monkeypatch.setenv("HERMES_HOME", str(host["prod"]))
+ assert gateway_cli._systemd_unit_installed() is True
+ gateway_cli.systemd_stop(system=True)
+ assert host["calls"] == [["stop", gateway_cli._SERVICE_BASE]]