diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md index 9743fab5e0..20eaeabbad 100644 --- a/hermes_cli/AGENTS.md +++ b/hermes_cli/AGENTS.md @@ -150,7 +150,9 @@ tool registry overlays) key on `hermes_constants.hermes_home_key()`, never a sin Migration from per-profile gateways: `hermes_cli/gateway_migrate.py` (`hermes gateway migrate --multiplex|--standalone`, table-driven `_PREFLIGHT_CHECKS`, manifest `/gateway_migration.json`); `update_cmd_fleet._verify_fleet_after_update` calls `maybe_auto_migrate_after_update` on the success -path only. Blockers reuse `GatewayRunner._adapter_credential_fingerprint` and `platform_binds_port`; +path only; `gateway_migrate_guards.py` holds the auto-path-only refusals (table `_AUTO_MIGRATION_GUARDS`: +other service domain / UNIX user / HERMES_HOME outside `profiles/` — notices for the explicit command, +blockers for the hook) and the `gateway.auto_multiplex_migration` opt-out (#109954). Blockers reuse `GatewayRunner._adapter_credential_fingerprint` and `platform_binds_port`; "has a `/p//` ingress" is the adapter class attribute `serves_profile_prefix` — set it on a new HTTP-inbound adapter when it answers the prefix, never extend a list here. diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.py index a17c2bcaa2..ec0c461085 100644 --- a/hermes_cli/gateway_migrate.py +++ b/hermes_cli/gateway_migrate.py @@ -13,7 +13,6 @@ import contextlib import json import logging import os -import subprocess import sys import time from dataclasses import dataclass, field @@ -38,7 +37,8 @@ class ProfileGateway: home: Path pid: Optional[int] = None service: Optional[tuple[str, bool]] = None # ("systemd", system) | ("launchd", False) - unix_user: Optional[str] = None + uid: Optional[int] = None # owner of the gateway process/unit; None = unknown (never "different") + runtime_home: Optional[Path] = None # HERMES_HOME the installed unit pins, when it differs from ``home`` @property def is_default(self) -> bool: @@ -58,6 +58,7 @@ class ProfileGateway: return { "profile": self.name, "home": str(self.home), "pid": self.pid, "service": None if self.service is None else {"kind": self.service[0], "system": self.service[1]}, + "uid": self.uid, "runtime_home": None if self.runtime_home is None else str(self.runtime_home), } @@ -167,6 +168,11 @@ def _live_gateway_pid(home: Path) -> Optional[int]: return None +def _gateway_identity(home: Path, pid: Optional[int], service: Optional[tuple[str, bool]]) -> tuple[Optional[int], Path]: + from hermes_cli.gateway_migrate_guards import gateway_identity + return gateway_identity(home, pid, service) + + def _installed_service(home: Path) -> Optional[tuple[str, bool]]: """Installed service kind for ``home``'s gateway (unit / plist on disk), else None.""" from hermes_cli import gateway as gw @@ -180,47 +186,6 @@ 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 @@ -259,25 +224,6 @@ def _read_multiplex_flag(default_home: Path) -> bool: return bool(cfg.get("multiplex_profiles") or gateway_section.get("multiplex_profiles")) -def _read_auto_migrate_flag(default_home: Path) -> bool: - """``gateway.auto_migrate`` in the DEFAULT profile's config.yaml: may ``hermes update`` fold - this install onto a multiplexed gateway on its own? Absent (the default) means yes; an explicit - ``false`` is a durable opt-out that survives updates, so an operator who wants to stay on - per-profile gateways does not have to re-decide after every release. Only the AUTO path reads - this — ``hermes gateway migrate --multiplex`` is an explicit request and always proceeds.""" - cfg_path = default_home / "config.yaml" - if not cfg_path.exists(): - return True - from hermes_cli.config import read_user_config_raw - cfg = read_user_config_raw(cfg_path) or {} - gateway_section = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {} - for source in (gateway_section, cfg): - value = source.get("auto_migrate") - if value is not None: - return bool(value) - return True - - def _write_multiplex_flag(default_home: Path, value: bool) -> None: """Set ``gateway.multiplex_profiles`` in the DEFAULT profile's config.yaml through the config API (same read-guard + nested-set + atomic write ``hermes config set`` uses; no raw YAML edits).""" @@ -439,41 +385,6 @@ _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(): @@ -489,13 +400,12 @@ def build_migration_plan() -> MigrationPlan: """Enumerate profiles + their gateway footprint, then run every preflight check.""" from hermes_cli.gateway_multiplex_served import recorded_served_profiles default_home = _default_home() - profiles = [ - 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() - ] + profiles = [] + for name, home in _profile_homes(): + pid, service = _live_gateway_pid(home), _installed_service(home) + uid, runtime_home = _gateway_identity(home, pid, service) + profiles.append(ProfileGateway(name=name, home=home, pid=pid, service=service, uid=uid, + runtime_home=None if runtime_home == home else runtime_home)) plan = MigrationPlan( default_home=default_home, profiles=profiles, multiplex_flag_on=_read_multiplex_flag(default_home), @@ -507,9 +417,10 @@ 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) - ) + from hermes_cli.gateway_migrate_guards import auto_migration_blockers + # Notices, not blockers: the explicit command is the operator's decision; only the update hook + # refuses to cross these boundaries on its own. + plan.notices.extend(f"Not migrated automatically by `hermes update`: {b}" for b 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)." @@ -615,7 +526,7 @@ def format_update_warning(plan: MigrationPlan, auto_blockers: list[str]) -> list 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, *auto_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.)", ] @@ -878,16 +789,16 @@ def cmd_migrate(args) -> None: def maybe_auto_migrate_after_update() -> None: """``hermes update`` hook: with >= 2 profiles, per-profile gateways present and multiplex off, migrate automatically when unblocked (deterministic, never prompts) or print the blocker block. - ``gateway.auto_migrate: false`` on the default profile opts out durably.""" - if _host_supports_migration() is not None: - return - if not _read_auto_migrate_flag(_default_home()): + ``gateway.auto_multiplex_migration: false`` on the default profile opts out; a secondary behind a + service-domain / UNIX-user / HERMES_HOME boundary blocks this path only (the explicit command decides).""" + from hermes_cli.gateway_migrate_guards import auto_migration_blockers, auto_migration_opted_out + if _host_supports_migration() is not None or auto_migration_opted_out(_default_home()): return plan = build_migration_plan() if plan.already_multiplexed or len(plan.profiles) < 2 or not plan.standalone_secondaries: return print() - auto_blockers = _auto_migration_blockers(plan) + auto_blockers = auto_migration_blockers(plan) if plan.blocked or auto_blockers: _print(format_update_warning(plan, auto_blockers)) return diff --git a/hermes_cli/gateway_migrate_guards.py b/hermes_cli/gateway_migrate_guards.py new file mode 100644 index 0000000000..db62a62f59 --- /dev/null +++ b/hermes_cli/gateway_migrate_guards.py @@ -0,0 +1,145 @@ +"""Boundaries the AUTOMATIC multiplex migration (``hermes update``) must not cross, and the opt-out. + +The multiplexer replaces a kernel-enforced boundary (separate UNIX users, separate service domains, +separate HERMES_HOME trees) with in-process isolation. An operator may choose that with +``hermes gateway migrate --multiplex``; an unattended update hook must not choose it for them. +``build_migration_plan`` records the same findings as NOTICES so a dry run shows them; only +:func:`maybe_auto_migrate_after_update` treats them as blockers (#109954). +""" + +from __future__ import annotations + +import contextlib +import os +import subprocess +from pathlib import Path +from typing import TYPE_CHECKING, Callable, Optional + +if TYPE_CHECKING: + from hermes_cli.gateway_migrate import MigrationPlan, ProfileGateway + + +# --------------------------------------------------------------------------- identity resolution + + +def _pid_uid(pid: int) -> Optional[int]: + """Owner uid of a live process: ``/proc`` where it exists, ``ps`` on macOS; None when unknown.""" + with contextlib.suppress(OSError): + return os.stat(f"/proc/{pid}").st_uid + from hermes_cli.gateway import is_macos + if not is_macos(): + return None + with contextlib.suppress(OSError, ValueError, subprocess.SubprocessError): + result = subprocess.run(["ps", "-o", "uid=", "-p", str(pid)], capture_output=True, text=True, encoding="utf-8", + check=False, timeout=2) + if result.returncode == 0 and result.stdout.strip(): + return int(result.stdout.strip()) + return None + + +def _system_unit_uid(unit_path: Path) -> Optional[int]: + """uid a system unit runs as: its ``User=`` (root when absent); None when the name is unknown.""" + from hermes_cli.gateway import _read_systemd_user_from_unit + user = _read_systemd_user_from_unit(unit_path) + if user is None: + return 0 + import pwd + with contextlib.suppress(KeyError): + return pwd.getpwnam(user).pw_uid + return None + + +def gateway_identity(home: Path, pid: Optional[int], service: Optional[tuple[str, bool]]) -> tuple[Optional[int], Path]: + """``(uid, runtime_home)`` of the gateway that serves ``home``. + + uid: the live process owner, else the system unit's ``User=``, else the owner of the profile + directory (user-scope systemd / launchd / detached gateways run as the account that owns it). + None means unknown — never a different user. runtime_home: the HERMES_HOME the installed unit + pins, which is where the gateway really runs; ``home`` when there is no unit or no pin. + """ + from hermes_cli.gateway import _hermes_home_pinned_by_unit, get_systemd_unit_path + from hermes_cli.gateway_migrate import _home_env + + uid: Optional[int] = _pid_uid(pid) if pid is not None else None + runtime_home = home + if service is not None and service[0] == "systemd": + with _home_env(home): + unit_path = get_systemd_unit_path(system=service[1]) + pinned = _hermes_home_pinned_by_unit(unit_path) + if pinned: + runtime_home = Path(pinned).expanduser() + if uid is None and service[1]: + uid = _system_unit_uid(unit_path) + if uid is None: + with contextlib.suppress(OSError): + uid = home.stat().st_uid + return uid, runtime_home + + +# --------------------------------------------------------------------------- guards + + +def _service_label(profile: ProfileGateway) -> str: + return profile.service_label() if profile.service is not None else "no service manager (detached)" + + +def _guard_service_domain(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]: + """Different manager or scope than the default gateway (system vs user systemd, launchd vs systemd, + or any service when the default is detached: the auto path never elects a secondary's manager).""" + if profile.service == plan.default.service: + return None + return (f"Profile '{profile.name}' runs under {_service_label(profile)} while the default gateway " + f"runs under {_service_label(plan.default)}: a different service domain is not folded automatically.") + + +def _guard_unix_user(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]: + default_uid = plan.default.uid + if default_uid is None or profile.uid is None or profile.uid == default_uid: + return None + return (f"Profile '{profile.name}' runs as uid {profile.uid} while the default gateway runs as uid " + f"{default_uid}: a UNIX privilege boundary is not folded automatically.") + + +def _guard_home_tree(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]: + profiles_root = (plan.default_home / "profiles").resolve() + runtime_home = (profile.runtime_home or profile.home).resolve() + if runtime_home.is_relative_to(profiles_root): + return None + return (f"Profile '{profile.name}' runs with HERMES_HOME={runtime_home}, outside {profiles_root}: " + f"the multiplexer would serve {profile.home} instead of the live home.") + + +_AUTO_MIGRATION_GUARDS: tuple[Callable[[MigrationPlan, ProfileGateway], Optional[str]], ...] = ( + _guard_service_domain, + _guard_unix_user, + _guard_home_tree, +) + + +def auto_migration_blockers(plan: MigrationPlan) -> list[str]: + """Every boundary a standalone secondary sits behind; empty when the fleet is one user, one service + domain, one profiles/ tree — the only shape ``hermes update`` may fold on its own.""" + return [ + finding + for profile in plan.standalone_secondaries + for guard in _AUTO_MIGRATION_GUARDS + if (finding := guard(plan, profile)) is not None + ] + + +# --------------------------------------------------------------------------- opt-out + + +def auto_migration_opted_out(default_home: Path) -> bool: + """``gateway.auto_multiplex_migration: false`` in the DEFAULT profile's config.yaml. Absent means + opted in (the ``DEFAULT_CONFIG`` value); only the nested key counts, there is no top-level alias.""" + cfg_path = default_home / "config.yaml" + if not cfg_path.exists(): + return False + from hermes_cli.config import read_user_config_raw + cfg = read_user_config_raw(cfg_path) or {} + gateway_section = cfg.get("gateway") + if not isinstance(gateway_section, dict): + return False + value = gateway_section.get("auto_multiplex_migration") + return value is not None and not bool(value) diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.py index 05f6032edd..c2341d96bb 100644 --- a/tests/hermes_cli/test_gateway_migrate_multiplex.py +++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py @@ -253,6 +253,7 @@ def test_serves_profile_prefix_is_read_from_adapter_classes(): def test_update_hook_migrates_when_unblocked_and_only_warns_when_blocked(fleet, capsys): + fleet.services["default"] = ("systemd", False) # same service domain as the secondaries gm.maybe_auto_migrate_after_update() out = capsys.readouterr().out assert "Migrating per-profile gateways" in out and "serves 3 profiles" in out @@ -262,7 +263,7 @@ def test_update_hook_migrates_when_unblocked_and_only_warns_when_blocked(fleet, for f in ("gateway.pid", "gateway_state.json", gm.MANIFEST_NAME): (fleet.root / f).unlink() (fleet.root / "config.yaml").write_text("model:\n default: x\n", encoding="utf-8") - fleet.services.update({"coder": ("systemd", False)}); fleet.services.pop("default", None) + fleet.services.update({"coder": ("systemd", False), "default": ("systemd", False)}) fleet.pids.update({"coder": 4101}); fleet.ops.clear() (fleet.root / "profiles/coder/.env").write_text("TELEGRAM_BOT_TOKEN=111111:default-token\n", encoding="utf-8") gm.maybe_auto_migrate_after_update() @@ -277,112 +278,66 @@ 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.""" +@pytest.mark.parametrize( + ("secondary_service", "secondary_uid", "secondary_home", "expected"), + [ + (("systemd", True), 1000, "profiles/coder", "different service domain"), + (("launchd", False), 1000, "profiles/coder", "different service domain"), + (("systemd", False), 2000, "profiles/coder", "UNIX privilege boundary"), + (("systemd", False), 1000, "external", "outside"), + ], +) +def test_update_hook_refuses_to_cross_service_user_or_home_boundary( + fleet, capsys, monkeypatch, secondary_service, secondary_uid, secondary_home, expected, +): + """#109954: the unattended hook must not fold a secondary that sits behind a kernel-enforced + boundary (other service domain, other UNIX user, HERMES_HOME outside profiles/). It prints the + boundary + the explicit command and touches nothing; the dry-run plan shows the same finding as a + notice and the explicit command stays available.""" fleet.services["default"] = ("systemd", False) - fleet.services["ops"] = ("launchd", False) + fleet.services["ops"] = secondary_service + ops_home = fleet.root.parent / "external-ops" if secondary_home == "external" else fleet.root / secondary_home + monkeypatch.setattr( + gm, "_gateway_identity", + lambda home, pid, service: (secondary_uid if _name(home) == "ops" else 1000, ops_home if _name(home) == "ops" else home), + raising=False, # absent on the pre-fix module: the test must then fail on behaviour, not on the seam + ) 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 + assert expected in out and gm.MIGRATE_COMMAND in out and "'ops'" in out + assert fleet.ops == [] and fleet.pids == {"coder": 4101, "ops": 4102} + assert fleet.services == {"default": ("systemd", False), "coder": ("systemd", False), "ops": secondary_service} + assert _config_flag(fleet.root) is None and not (fleet.root / gm.MANIFEST_NAME).exists() + + plan = gm.build_migration_plan() + assert not plan.blocked and any(expected in n for n in plan.notices) + gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=True, yes=True)) + assert expected in capsys.readouterr().out -@pytest.mark.parametrize( - ("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, - ) +def test_update_hook_still_migrates_same_user_same_scope_profiles_under_the_default_tree(fleet, capsys, monkeypatch): + """The guard is a boundary check, not a kill switch: one user, one service domain, everything under + profiles/ (the shape `hermes profile create` produces) still auto-migrates.""" + fleet.services["default"] = ("systemd", False) + monkeypatch.setattr(gm, "_gateway_identity", lambda home, pid, service: (1000, home), raising=False) - blockers = gm._auto_migration_blockers(plan) + gm.maybe_auto_migrate_after_update() - assert any(expected in blocker for blocker in blockers) - assert all(gm.MIGRATE_COMMAND in blocker for blocker in blockers) + out = capsys.readouterr().out + assert "Migrating per-profile gateways" in out and "serves 3 profiles" in out + assert _config_flag(fleet.root) is True and ("ops", "uninstall") in fleet.ops -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_auto_migrate_false_opts_out_of_the_update_hook_but_not_the_explicit_command(fleet, capsys): - """``gateway.auto_migrate: false`` is a durable opt-out: an otherwise-eligible fleet is left - alone by ``hermes update``, while the operator typing ``migrate --multiplex`` still migrates.""" +def test_auto_multiplex_migration_false_opts_out_of_the_update_hook_but_not_the_explicit_command(fleet, capsys): + """``gateway.auto_multiplex_migration: false`` is a durable opt-out: an otherwise-eligible fleet is + left alone by ``hermes update`` (no output, no ops, no flag flip), while the operator typing + ``migrate --multiplex`` still migrates. Only the nested key counts.""" assert gm.build_migration_plan().eligible_for_migration() # would migrate but for the flag (fleet.root / "config.yaml").write_text( - "model:\n default: x\ngateway:\n auto_migrate: false\n", encoding="utf-8") + "model:\n default: x\nauto_multiplex_migration: false\ngateway:\n auto_multiplex_migration: false\n", + encoding="utf-8") gm.maybe_auto_migrate_after_update() assert capsys.readouterr().out == "" @@ -391,17 +346,18 @@ def test_auto_migrate_false_opts_out_of_the_update_hook_but_not_the_explicit_com assert fleet.pids == {"coder": 4101, "ops": 4102} assert not (fleet.root / gm.MANIFEST_NAME).exists() - # Absent (the default) and an explicit true both keep today's automatic behaviour. - assert gm._read_auto_migrate_flag(fleet.root) is False + # A top-level alias is NOT honoured; absent and an explicit true keep the automatic behaviour. + from hermes_cli.gateway_migrate_guards import auto_migration_opted_out (fleet.root / "config.yaml").write_text( - "model:\n default: x\ngateway:\n auto_migrate: true\n", encoding="utf-8") - assert gm._read_auto_migrate_flag(fleet.root) is True - (fleet.root / "config.yaml").write_text("model:\n default: x\n", encoding="utf-8") - assert gm._read_auto_migrate_flag(fleet.root) is True + "model:\n default: x\nauto_multiplex_migration: false\n", encoding="utf-8") + assert auto_migration_opted_out(fleet.root) is False + (fleet.root / "config.yaml").write_text( + "model:\n default: x\ngateway:\n auto_multiplex_migration: true\n", encoding="utf-8") + assert auto_migration_opted_out(fleet.root) is False # The opt-out governs the AUTOMATIC path only: an explicit --multiplex is an explicit request. (fleet.root / "config.yaml").write_text( - "model:\n default: x\ngateway:\n auto_migrate: false\n", encoding="utf-8") + "model:\n default: x\ngateway:\n auto_multiplex_migration: false\n", encoding="utf-8") with pytest.raises(SystemExit) as exc: gm.cmd_migrate(SimpleNamespace(multiplex=True, standalone=False, dry_run=False, yes=True)) assert exc.value.code == 0 diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md index c42a7ce850..8faf5d5c96 100644 --- a/website/docs/user-guide/multi-profile-gateways.md +++ b/website/docs/user-guide/multi-profile-gateways.md @@ -812,13 +812,33 @@ install that is already multiplexing is left alone. `hermes update` also does nothing when no secondary profile runs its own gateway — it never flips modes on an install where nothing was running. +### Boundaries `hermes update` never crosses on its own + +The unattended hook only folds profiles that share **one UNIX user, one service +domain and one `profiles/` tree** — the shape `hermes profile create` produces. +A standalone secondary behind any of these boundaries stops the automatic path: + +| boundary | example | +|---|---| +| different service manager or scope | default on user systemd, a secondary on **system** systemd (or launchd), or the default detached with a service-managed secondary | +| different UNIX user | a system unit with its own `User=`, or a live gateway owned by another uid | +| `HERMES_HOME` outside `/profiles/` | a unit pinning `HERMES_HOME=/opt/hermes/profiles/emma` | + +In that case `hermes update` prints the boundary it found plus +`hermes gateway migrate --multiplex`, and changes nothing — no unit is removed +and `gateway.multiplex_profiles` stays off. Collapsing such a fleet replaces a +kernel-enforced boundary (file ownership, `User=`) with in-process isolation, +which is an operator's decision. The explicit command still makes it: the same +findings appear as **notices** in `hermes gateway migrate --multiplex --dry-run` +so you can read them first, and `--multiplex` proceeds when you confirm. + ### Opting out of the automatic migration -Set `gateway.auto_migrate: false` on the **default** profile to keep the -automatic fold from ever running on this install: +Set `gateway.auto_multiplex_migration: false` on the **default** profile to keep +the automatic fold from ever running on this install: ```bash -hermes config set gateway.auto_migrate false +hermes config set gateway.auto_multiplex_migration false ``` `hermes update` then leaves per-profile gateways exactly as they are, with no