Skip to content

The agent that grows with you

refactor(gateway): service-definition guards live in gateway_service_owner

Teknium1e0c7730d791
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 57587df1dbd..40c59694128 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -19,7 +19,7 @@ import textwrap
import time
from dataclasses import dataclass
from pathlib import Path
-from hermes_cli import setup_platforms
+from hermes_cli import gateway_service_owner, setup_platforms
# UV's bundled Python ships a minimal PATH; ensure launchctl/systemctl are discoverable.
if os.name == "posix":
@@ -3398,40 +3398,6 @@ def systemd_unit_is_current(system: bool = False) -> bool:
return norm(installed) == norm(expected)
-def _temp_home_in_service_definition(definition: str) -> str | None:
- """Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a
- test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""
- import re
- import tempfile
- candidates = re.findall(r'HERMES_HOME=([^"\n]+)', definition)
- candidates += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.DOTALL)
- temp_roots = {
- Path(tempfile.gettempdir()).resolve(),
- Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions
- }
- for raw in candidates:
- try:
- resolved = Path(raw.strip().strip('"')).resolve()
- except (OSError, ValueError):
- continue
- if any(resolved == root or root in resolved.parents for root in temp_roots):
- return raw.strip()
- return None
-
-
-def _refuse_temp_home_service_write(definition: str, kind: str) -> bool:
- """Refuse (with guidance) when a service definition carries a temp HERMES_HOME."""
- temp_home = _temp_home_in_service_definition(definition)
- if temp_home is None:
- return False
- print(f"✗ Refusing to write the gateway {kind}: HERMES_HOME resolves to a temporary directory ({temp_home}).")
- print(
- " This usually means a test/E2E environment exported HERMES_HOME. "
- "Unset it (or run from a clean shell) and retry."
- )
- return True
-
-
def _retire_hermes_replace_dropin(system: bool = False) -> bool:
"""Remove only the legacy ``--replace`` drop-in written by Hermes."""
unit_path = get_systemd_unit_path(system=system)
@@ -3452,11 +3418,10 @@ def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
if not unit_path.exists():
return False
- # Runs on every gateway boot/start/restart. A home whose service name collides with another install's
- # (``<root>/profiles/x`` vs ``~/.hermes/profiles/x``) must not rewrite that install's unit. Checked on
- # the caller's own home, before systemd_unit_is_current adopts the unit's home into os.environ.
- from hermes_cli.gateway_service_owner import definition_belongs_to_home, service_home_for_unit
- if not definition_belongs_to_home(unit_path, service_home_for_unit(unit_path, system), "rewrite"):
+ # Every boot/start/restart lands here: never rewrite a unit pinning another home (checked before
+ # systemd_unit_is_current adopts the unit's home into os.environ).
+ from hermes_cli.gateway_service_owner import unit_belongs_to_caller
+ if not unit_belongs_to_caller(unit_path, system, "rewrite"):
return False
# systemd_unit_is_current is the HERMES_HOME-sync chokepoint; its env mutation persists for the regenerate below.
current = systemd_unit_is_current(system=system)
@@ -3477,7 +3442,7 @@ def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
return False
# Structural variant: refuse ANY temp-dir HERMES_HOME (manual E2E homes lack the pytest markers).
- if _refuse_temp_home_service_write(new_unit, "systemd unit"):
+ if gateway_service_owner.refuse_temp_home_service_write(new_unit, "systemd unit"):
return False
_prepare_service_launcher(system=system, run_as_user=expected_user)
@@ -3651,19 +3616,11 @@ def systemd_install(
if system:
_require_root_for_system_service("install")
- # A unit pinning another home is another install's gateway: refuse before any removal, sync or write,
- # --force included. --force-unit-path is the explicit repoint.
+ # A unit pinning another home is another install's gateway, --force included; --force-unit-path repoints.
unit_path = get_systemd_unit_path(system=system)
- if not force_unit_path:
- from hermes_cli.gateway_service_owner import definition_belongs_to_home, service_home_for_unit
- target_home = service_home_for_unit(unit_path, system)
- if system and run_as_user:
- try:
- target_home = Path(_hermes_home_for_target_user(_system_service_identity(run_as_user)[2]))
- except ValueError:
- pass # unknown account: generate_systemd_unit refuses it below with the real error
- if not definition_belongs_to_home(unit_path, target_home, "overwrite"):
- sys.exit(1)
+ from hermes_cli.gateway_service_owner import unit_belongs_to_caller
+ if not force_unit_path and not unit_belongs_to_caller(unit_path, system, "overwrite", run_as_user):
+ sys.exit(1)
# Offer to remove legacy units first: alongside the new unit they flap-fight for the bot token.
if has_legacy_hermes_units():
@@ -3712,7 +3669,7 @@ def systemd_install(
unit_path.parent.mkdir(parents=True, exist_ok=True)
new_unit = generate_systemd_unit(system=system, run_as_user=run_as_user)
- if _refuse_temp_home_service_write(new_unit, "systemd unit"):
+ if gateway_service_owner.refuse_temp_home_service_write(new_unit, "systemd unit"):
return
print(f"Installing {scope_label} systemd service to: {unit_path}")
_prepare_service_launcher(system=system, run_as_user=run_as_user)
@@ -5288,14 +5245,13 @@ def _cmd_install(args):
if _service_mgmt_blocked():
_no_backend_exit("install", "termux")
backend = _service_backend()
- force_unit_path = getattr(args, "force_unit_path", False)
- if backend == "systemd" and refuses_container_user_scope_install(system):
- sys.exit(1)
if backend == "systemd":
+ if refuses_container_user_scope_install(system):
+ sys.exit(1)
_install_systemd_from_cli(args, force=force, system=system, run_as_user=run_as_user)
elif backend == "launchd":
launchd_install(force, start_now=getattr(args, "start_now", None) is not False,
- force_unit_path=force_unit_path)
+ force_unit_path=getattr(args, "force_unit_path", False))
elif backend == "windows":
_gw_windows().install(
force=force,
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.py
index 608ad9b48fb..8ffc3d4929f 100644
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@ -16,6 +16,8 @@ import sys
import time
from xml.sax.saxutils import escape
+from hermes_cli import gateway_service_owner
+
def _gw():
from hermes_cli import gateway # late: the facade imports this module
@@ -546,7 +548,7 @@ def refresh_launchd_plist_if_needed() -> bool:
return False
new_plist = _gw().generate_launchd_plist()
- if _gw()._refuse_temp_home_service_write(new_plist, "launchd plist"):
+ if gateway_service_owner.refuse_temp_home_service_write(new_plist, "launchd plist"):
return False
_gw()._prepare_service_launcher()
@@ -636,7 +638,7 @@ def launchd_install(force: bool = False, *, start_now: bool = True, force_unit_p
plist_path.parent.mkdir(parents=True, exist_ok=True)
new_plist = _gw().generate_launchd_plist()
- if _gw()._refuse_temp_home_service_write(new_plist, "launchd plist"):
+ if gateway_service_owner.refuse_temp_home_service_write(new_plist, "launchd plist"):
return
print(f"Installing launchd service to: {plist_path}")
_gw()._prepare_service_launcher()
@@ -691,7 +693,7 @@ def launchd_start():
# Self-heal if the plist is missing entirely (e.g., manual cleanup, failed upgrade)
if not plist_path.exists():
new_plist = _gw().generate_launchd_plist()
- if _gw()._refuse_temp_home_service_write(new_plist, "launchd plist"):
+ if gateway_service_owner.refuse_temp_home_service_write(new_plist, "launchd plist"):
sys.exit(1)
print("↻ launchd plist missing; regenerating service definition")
plist_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/hermes_cli/gateway_service_owner.py b/hermes_cli/gateway_service_owner.py
index 1c48caaf737..9801438d616 100644
--- a/hermes_cli/gateway_service_owner.py
+++ b/hermes_cli/gateway_service_owner.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import os
import plistlib
from pathlib import Path
+from xml.parsers.expat import ExpatError
def pinned_home(definition_path: Path) -> str | None:
@@ -24,7 +25,7 @@ def pinned_home(definition_path: Path) -> str | None:
try:
with definition_path.open("rb") as fh:
data = plistlib.load(fh)
- except Exception: # unreadable / not a plist (hand-edited, truncated): pins nobody
+ except (OSError, ValueError, ExpatError): # unreadable / not a plist: pins nobody
return None
env = data.get("EnvironmentVariables") if isinstance(data, dict) else None
value = env.get("HERMES_HOME") if isinstance(env, dict) else None
@@ -80,3 +81,51 @@ def definition_belongs_to_home(definition_path: Path, home: Path, action: str) -
print(" That file is another install's gateway. Use that install, or pass --force-unit-path")
print(" to `hermes gateway install` if you really mean to repoint it at this home.")
return False
+
+
+def unit_belongs_to_caller(unit_path: Path, system: bool, action: str, run_as_user: str | None = None) -> bool:
+ """``definition_belongs_to_home`` for the systemd unit at *unit_path*, judged against the home this
+ process would pin there (``run_as_user``'s for an explicit ``--system --run-as-user`` install)."""
+ from hermes_cli import gateway as gw
+
+ home = service_home_for_unit(unit_path, system)
+ if system and run_as_user:
+ try:
+ home = Path(gw._hermes_home_for_target_user(gw._system_service_identity(run_as_user)[2]))
+ except ValueError:
+ pass # unknown account: generate_systemd_unit refuses it later with the real error
+ return definition_belongs_to_home(unit_path, home, action)
+
+
+def temp_home_in_service_definition(definition: str) -> str | None:
+ """Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a
+ test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""
+ import re
+ import tempfile
+ candidates = re.findall(r'HERMES_HOME=([^"\n]+)', definition)
+ candidates += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.DOTALL)
+ temp_roots = {
+ Path(tempfile.gettempdir()).resolve(),
+ Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions
+ }
+ for raw in candidates:
+ try:
+ resolved = Path(raw.strip().strip('"')).resolve()
+ except (OSError, ValueError):
+ continue
+ if any(resolved == root or root in resolved.parents for root in temp_roots):
+ return raw.strip()
+ return None
+
+
+def refuse_temp_home_service_write(definition: str, kind: str) -> bool:
+ """Refuse (with guidance) when a service definition carries a temp HERMES_HOME."""
+ temp_home = temp_home_in_service_definition(definition)
+ if temp_home is None:
+ return False
+ print(f"✗ Refusing to write the gateway {kind}: HERMES_HOME resolves to a temporary directory ({temp_home}).")
+ print(
+ " This usually means a test/E2E environment exported HERMES_HOME. "
+ "Unset it (or run from a clean shell) and retry."
+ )
+ return True
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 2850557cc71..3fd55a9eeeb 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -157,24 +157,6 @@ class TestSystemdServiceRefresh:
), "daemon-reload must not run when write was refused"
-class TestTempHomeServiceDefinitionGuard:
- """_temp_home_in_service_definition() — structural temp-dir detection."""
-
- def test_detects_tmp_home_in_systemd_unit(self):
- unit = '[Service]\nEnvironment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
- assert (
- gateway_cli._temp_home_in_service_definition(unit)
- == "/tmp/hermes-e2e-41264"
- )
-
- def test_detects_tempdir_env_home(self, monkeypatch, tmp_path):
- import tempfile as _tempfile
-
- monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(tmp_path))
- unit = f'[Service]\nEnvironment="HERMES_HOME={tmp_path}/hermes-home"\n'
- assert gateway_cli._temp_home_in_service_definition(unit) is not None
-
-
class TestRequireServiceInstalled:
def test_exits_with_install_hint_when_unit_missing(self, tmp_path, monkeypatch, capsys):
unit_path = tmp_path / "hermes-gateway.service"
diff --git a/tests/hermes_cli/test_gateway_service_owner.py b/tests/hermes_cli/test_gateway_service_owner.py
index 92bc7f4cc86..05f2e16d6c3 100644
--- a/tests/hermes_cli/test_gateway_service_owner.py
+++ b/tests/hermes_cli/test_gateway_service_owner.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
import pytest
import hermes_cli.gateway as gw
+from hermes_cli import gateway_service_owner
UNIT = (
"[Service]\n"
@@ -31,7 +32,7 @@ def unit(tmp_path, monkeypatch):
path.write_text(UNIT.format(home=real), encoding="utf-8")
calls = []
# The temp-root guard only sees homes under a temp dir; scratch homes elsewhere are what slipped past.
- monkeypatch.setattr(gw, "_refuse_temp_home_service_write", lambda definition, kind: False)
+ monkeypatch.setattr(gateway_service_owner, "refuse_temp_home_service_write", lambda definition, kind: False)
monkeypatch.setattr(gw, "get_systemd_unit_path", lambda system=False: path)
monkeypatch.setattr(gw, "systemd_unit_is_current", lambda system=False: False)
monkeypatch.setattr(gw, "_retire_hermes_replace_dropin", lambda system=False: False)
@@ -56,3 +57,21 @@ def test_refresh_from_the_pinned_home_still_rewrites_a_stale_unit(unit, monkeypa
assert gw.refresh_systemd_unit_if_needed(system=False) is True
assert unit.path.read_text(encoding="utf-8") == "ExecStart=new\n"
assert ("daemon-reload",) in unit.calls
+
+
+class TestTempHomeServiceDefinitionGuard:
+ """temp_home_in_service_definition() — structural temp-dir detection."""
+
+ def test_detects_tmp_home_in_systemd_unit(self):
+ unit = '[Service]\nEnvironment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
+ assert (
+ gateway_service_owner.temp_home_in_service_definition(unit)
+ == "/tmp/hermes-e2e-41264"
+ )
+
+ def test_detects_tempdir_env_home(self, monkeypatch, tmp_path):
+ import tempfile as _tempfile
+
+ monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(tmp_path))
+ unit = f'[Service]\nEnvironment="HERMES_HOME={tmp_path}/hermes-home"\n'
+ assert gateway_service_owner.temp_home_in_service_definition(unit) is not None
diff --git a/tests/hermes_cli/test_launchd_install_start_now.py b/tests/hermes_cli/test_launchd_install_start_now.py
index 7ead1f1b13d..8842bd334ea 100644
--- a/tests/hermes_cli/test_launchd_install_start_now.py
+++ b/tests/hermes_cli/test_launchd_install_start_now.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
import pytest
import hermes_cli.gateway as gateway_cli
+from hermes_cli import gateway_service_owner
from hermes_cli.subcommands.gateway import build_gateway_parser
LABEL = "ai.hermes.gateway"
@@ -40,7 +41,7 @@ def launchd(tmp_path, monkeypatch):
monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: state.plist)
monkeypatch.setattr(gateway_cli, "get_launchd_label", lambda: LABEL)
monkeypatch.setattr(gateway_cli, "_launchd_domain", lambda: DOMAIN)
- monkeypatch.setattr(gateway_cli, "_refuse_temp_home_service_write", lambda *a: False)
+ monkeypatch.setattr(gateway_service_owner, "refuse_temp_home_service_write", lambda *a: False)
monkeypatch.setattr(gateway_cli, "_clear_launchd_unsupported_marker", lambda: None)
monkeypatch.setattr(gateway_cli, "_launchctl_supervised_pid", lambda label: state.supervised_pid)
monkeypatch.setattr(gateway_cli, "_launchctl_bootstrap", lambda *a, **k: state.bootstraps.append(a))
diff --git a/tests/hermes_cli/test_launchd_refresh_reporting.py b/tests/hermes_cli/test_launchd_refresh_reporting.py
index 73c8a1f7937..e2832ebc1b6 100644
--- a/tests/hermes_cli/test_launchd_refresh_reporting.py
+++ b/tests/hermes_cli/test_launchd_refresh_reporting.py
@@ -3,6 +3,7 @@ import subprocess
from unittest.mock import MagicMock
from hermes_cli import gateway as gw
+from hermes_cli import gateway_service_owner
def _stale_plist(tmp_path, monkeypatch, *, registered: bool):
plist_path = tmp_path / "com.hermes.plist"
@@ -10,7 +11,7 @@ def _stale_plist(tmp_path, monkeypatch, *, registered: bool):
monkeypatch.setattr(gw, "get_launchd_plist_path", lambda: plist_path)
monkeypatch.setattr(gw, "launchd_plist_is_current", lambda: False)
monkeypatch.setattr(gw, "generate_launchd_plist", lambda: "<new/>")
- monkeypatch.setattr(gw, "_refuse_temp_home_service_write", lambda *a: False)
+ monkeypatch.setattr(gateway_service_owner, "refuse_temp_home_service_write", lambda *a: False)
monkeypatch.setattr(gw, "get_launchd_label", lambda: "com.hermes.agent")
monkeypatch.setattr(gw, "_launchd_domain", lambda: "gui/501")
monkeypatch.setattr(gw, "_append_launchd_reload_log", lambda msg: None)