Skip to content

The agent that grows with you

fix(gateway): guard auto migration service boundaries

KoNit-K10654711fa1f
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py
index 77d5465fc8b..14cd938d3b6 100644
--- a/hermes_cli/gateway_migrate.py
+++ b/hermes_cli/gateway_migrate.py
@@ -13,6 +13,7 @@ import contextlib
import json
import logging
import os
+import subprocess
import sys
import time
from dataclasses import dataclass, field
@@ -37,6 +38,7 @@ class ProfileGateway:
home: Path
pid: Optional[int] = None
service: Optional[tuple[str, bool]] = None # ("systemd", system) | ("launchd", False)
+ unix_user: Optional[str] = None
@property
def is_default(self) -> bool:
@@ -178,6 +180,47 @@ def _installed_service(home: Path) -> Optional[tuple[str, bool]]:
return None
+def _gateway_unix_user(home: Path, pid: Optional[int], service: Optional[tuple[str, bool]]) -> Optional[str]:
+ """Best-effort owner identity for an installed or live gateway.
+
+ A system unit's ``User=`` is authoritative even when the process is stopped. User-scope
+ systemd and launchd services run as this account; a live process takes precedence when its
+ owner can be inspected. ``None`` means the owner cannot be established, not a different user.
+ """
+ if pid is not None:
+ with contextlib.suppress(OSError):
+ return f"uid:{os.stat(f'/proc/{pid}').st_uid}"
+ with contextlib.suppress(OSError, ValueError):
+ result = subprocess.run(
+ ["ps", "-o", "uid=", "-p", str(pid)], capture_output=True, text=True,
+ check=False, timeout=2,
+ )
+ if result.returncode == 0 and (uid := result.stdout.strip()):
+ return f"uid:{int(uid)}"
+ if service is None:
+ with contextlib.suppress(OSError):
+ return f"uid:{home.stat().st_uid}"
+ return None
+ kind, system = service
+ if kind == "systemd" and system:
+ from hermes_cli import gateway as gw
+ with _home_env(home):
+ with contextlib.suppress(OSError):
+ user = gw._read_systemd_user_from_unit(gw.get_systemd_unit_path(system=True))
+ if user:
+ with contextlib.suppress(KeyError):
+ import pwd
+ return f"uid:{pwd.getpwnam(user).pw_uid}"
+ return f"user:{user}"
+ # A systemd system unit with no User= runs as root.
+ return "uid:0"
+ if kind in {"systemd", "launchd"}:
+ return f"uid:{os.geteuid()}"
+ with contextlib.suppress(OSError):
+ return f"uid:{home.stat().st_uid}"
+ return None
+
+
def _service_op(kind: str, system: bool, verb: str, home: Path) -> None:
"""``stop`` / ``uninstall`` / ``start`` / ``restart`` / ``install`` on ``home``'s service."""
from hermes_cli import gateway as gw
@@ -377,6 +420,41 @@ _PREFLIGHT_CHECKS: tuple[Callable[[MigrationPlan, dict[str, object]], None], ...
)
+def _auto_migration_blockers(plan: MigrationPlan) -> list[str]:
+ """Guards for the unattended update hook.
+
+ Auto-migration removes services, so it must not fold gateways from another service domain,
+ account, or Hermes-home tree into the default service. The explicit command remains available
+ for an operator who has reviewed and intentionally reconciled such a fleet.
+ """
+ blockers: list[str] = []
+ profile_root = (plan.default_home / "profiles").resolve()
+ # The auto-migration target is always the default gateway. Unlike the explicit
+ # command, it must not elect a secondary's service when the default is detached:
+ # doing so would silently move the default into a different service domain.
+ target_service = plan.default.service
+ default_user = plan.default.unix_user
+ for profile in plan.standalone_secondaries:
+ try:
+ profile.home.resolve().relative_to(profile_root)
+ except ValueError:
+ blockers.append(
+ f"Profile '{profile.name}' has HERMES_HOME outside {profile_root}; keep it standalone or move it "
+ f"under {profile_root} before running {MIGRATE_COMMAND}."
+ )
+ if profile.service != target_service:
+ blockers.append(
+ f"Profile '{profile.name}' uses a different service manager or scope than the default migration "
+ f"target; keep it standalone or align its gateway service before running {MIGRATE_COMMAND}."
+ )
+ if default_user and profile.unix_user and profile.unix_user != default_user:
+ blockers.append(
+ f"Profile '{profile.name}' runs as {profile.unix_user}, while the default gateway runs as "
+ f"{default_user}; keep it standalone or align the UNIX user before running {MIGRATE_COMMAND}."
+ )
+ return blockers
+
+
def _load_profile_configs(plan: MigrationPlan) -> dict[str, object]:
configs: dict[str, object] = {}
with _multiplex_read_mode():
@@ -393,7 +471,10 @@ def build_migration_plan() -> MigrationPlan:
from hermes_cli.gateway_multiplex_served import recorded_served_profiles
default_home = _default_home()
profiles = [
- ProfileGateway(name=name, home=home, pid=_live_gateway_pid(home), service=_installed_service(home))
+ ProfileGateway(
+ name=name, home=home, pid=(pid := _live_gateway_pid(home)),
+ service=(service := _installed_service(home)), unix_user=_gateway_unix_user(home, pid, service),
+ )
for name, home in _profile_homes()
]
plan = MigrationPlan(
@@ -407,6 +488,9 @@ def build_migration_plan() -> MigrationPlan:
configs = _load_profile_configs(plan)
for check in _PREFLIGHT_CHECKS:
check(plan, configs)
+ plan.notices.extend(
+ f"Automatic migration guard: {blocker}" for blocker in _auto_migration_blockers(plan)
+ )
plan.notices.append(
"Profiles created after the migration are served by the running multiplexer as soon as "
"they exist (it rescans profiles/ on create/delete and every 30s)."
@@ -508,11 +592,11 @@ def format_rollback_plan(default_home: Path, manifest: dict, *, dry_run: bool) -
return lines
-def format_update_warning(plan: MigrationPlan) -> list[str]:
+def format_update_warning(plan: MigrationPlan, auto_blockers: list[str]) -> list[str]:
return [
"⚠ Your profiles each run their own gateway. A single multiplexed gateway is the recommended",
" setup, but this install cannot be migrated automatically yet:",
- *[f" • {b}" for b in plan.blockers],
+ *[f" • {b}" for b in [*plan.blockers, *auto_blockers]],
f" After fixing the above, run: {MIGRATE_COMMAND}",
" (`hermes update` will migrate automatically once nothing blocks it.)",
]
@@ -781,8 +865,9 @@ def maybe_auto_migrate_after_update() -> None:
if plan.already_multiplexed or len(plan.profiles) < 2 or not plan.standalone_secondaries:
return
print()
- if plan.blocked:
- _print(format_update_warning(plan))
+ auto_blockers = _auto_migration_blockers(plan)
+ if plan.blocked or auto_blockers:
+ _print(format_update_warning(plan, auto_blockers))
return
print("→ Migrating per-profile gateways onto one multiplexed default gateway...")
_print(format_plan(plan, dry_run=False))
diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py
index 7d1c27a75f9..d36a9b3f7bb 100644
--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py
+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py
@@ -277,6 +277,107 @@ def test_update_hook_never_touches_single_profile_or_already_multiplexed(fleet,
assert capsys.readouterr().out == "" and _config_flag(fleet.root) is None
+def test_update_hook_refuses_a_secondary_on_a_different_service_manager(fleet, capsys):
+ """Automatic migration must not replace a secondary from a different service domain."""
+ fleet.services["default"] = ("systemd", False)
+ fleet.services["ops"] = ("launchd", False)
+
+ gm.maybe_auto_migrate_after_update()
+
+ out = capsys.readouterr().out
+ assert "different service manager or scope" in out
+ assert gm.MIGRATE_COMMAND in out
+ assert fleet.ops == []
+ assert fleet.services == {
+ "default": ("systemd", False), "coder": ("systemd", False), "ops": ("launchd", False),
+ }
+ assert _config_flag(fleet.root) is None
+
+
+ ("secondary_service", "secondary_user", "secondary_home", "expected"),
+ [
+ (("systemd", True), "uid:1000", "profiles/coder", "different service manager or scope"),
+ (("systemd", False), "uid:2000", "profiles/coder", "align the UNIX user"),
+ (("systemd", False), "uid:1000", "external", "HERMES_HOME outside"),
+ ],
+)
+def test_auto_migration_guard_detects_service_scope_user_and_home_boundaries(
+ tmp_path, secondary_service, secondary_user, secondary_home, expected,
+):
+ root = tmp_path / "hermes"
+ secondary = tmp_path / "external-hermes" if secondary_home == "external" else root / secondary_home
+ plan = gm.MigrationPlan(
+ default_home=root,
+ profiles=[
+ gm.ProfileGateway("default", root, service=("systemd", False), unix_user="uid:1000"),
+ gm.ProfileGateway("coder", secondary, service=secondary_service, unix_user=secondary_user),
+ ],
+ multiplex_flag_on=False,
+ live_served=None,
+ )
+
+ blockers = gm._auto_migration_blockers(plan)
+
+ assert any(expected in blocker for blocker in blockers)
+ assert all(gm.MIGRATE_COMMAND in blocker for blocker in blockers)
+
+
+def test_auto_migration_guard_allows_a_same_scope_same_user_profile_tree(tmp_path):
+ root = tmp_path / "hermes"
+ plan = gm.MigrationPlan(
+ default_home=root,
+ profiles=[
+ gm.ProfileGateway("default", root, service=("systemd", False), unix_user="uid:1000"),
+ gm.ProfileGateway(
+ "coder", root / "profiles/coder", service=("systemd", False), unix_user="uid:1000",
+ ),
+ ],
+ multiplex_flag_on=False,
+ live_served=None,
+ )
+
+ assert gm._auto_migration_blockers(plan) == []
+
+
+def test_auto_migration_guard_blocks_service_managed_secondary_when_default_is_detached(tmp_path):
+ root = tmp_path / "hermes"
+ plan = gm.MigrationPlan(
+ default_home=root,
+ profiles=[
+ gm.ProfileGateway("default", root, unix_user="uid:1000"),
+ gm.ProfileGateway(
+ "coder", root / "profiles/coder", service=("systemd", False), unix_user="uid:1000",
+ ),
+ gm.ProfileGateway(
+ "ops", root / "profiles/ops", service=("launchd", False), unix_user="uid:1000",
+ ),
+ ],
+ multiplex_flag_on=False,
+ live_served=None,
+ )
+
+ blockers = gm._auto_migration_blockers(plan)
+
+ assert len(blockers) == 2
+ assert all("different service manager or scope" in blocker for blocker in blockers)
+
+
+def test_auto_migration_guard_allows_detached_default_and_secondary_in_same_scope(tmp_path):
+ root = tmp_path / "hermes"
+ plan = gm.MigrationPlan(
+ default_home=root,
+ profiles=[
+ gm.ProfileGateway("default", root, unix_user="uid:1000"),
+ gm.ProfileGateway("coder", root / "profiles/coder", unix_user="uid:1000"),
+ ],
+ multiplex_flag_on=False,
+ live_served=None,
+ )
+
+ assert gm._auto_migration_blockers(plan) == []
+
+
def test_explicit_migrate_with_no_standalone_secondaries_still_flips_flag_and_restarts_default(fleet, capsys, monkeypatch):
"""The user typed --multiplex: 'nothing to migrate' + flag left off was a no-op the user did not ask
for. The update hook keeps its no-op (previous test); the explicit command proceeds."""