gateway_migrate_guards.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """Boundaries the AUTOMATIC multiplex migration (``hermes update``) must not cross, and the opt-out.
  2. The multiplexer replaces a kernel-enforced boundary (separate UNIX users, separate service domains,
  3. separate HERMES_HOME trees) with in-process isolation. An operator may choose that with
  4. ``hermes gateway migrate --multiplex``; an unattended update hook must not choose it for them.
  5. ``build_migration_plan`` records the same findings as NOTICES so a dry run shows them; only
  6. :func:`maybe_auto_migrate_after_update` treats them as blockers (#109954).
  7. """
  8. from __future__ import annotations
  9. import contextlib
  10. import os
  11. import subprocess
  12. from pathlib import Path
  13. from typing import TYPE_CHECKING, Callable, Optional
  14. if TYPE_CHECKING:
  15. from hermes_cli.gateway_migrate import MigrationPlan, ProfileGateway
  16. # --------------------------------------------------------------------------- identity resolution
  17. def _pid_uid(pid: int) -> Optional[int]:
  18. """Owner uid of a live process: ``/proc`` where it exists, ``ps`` on macOS; None when unknown."""
  19. with contextlib.suppress(OSError):
  20. return os.stat(f"/proc/{pid}").st_uid
  21. from hermes_cli.gateway import is_macos
  22. if not is_macos():
  23. return None
  24. with contextlib.suppress(OSError, ValueError, subprocess.SubprocessError):
  25. result = subprocess.run(["ps", "-o", "uid=", "-p", str(pid)], capture_output=True, text=True, encoding="utf-8",
  26. check=False, timeout=2)
  27. if result.returncode == 0 and result.stdout.strip():
  28. return int(result.stdout.strip())
  29. return None
  30. def pid_is_other_users(pid: int) -> bool:
  31. """True when *pid* is owned by another Unix user than this non-root caller.
  32. Gateway process scans match argv host-wide, so without this a second account's gateway (users
  33. isolate credentials by UID) became a ``restart --all`` SIGTERM target and "unfolded profile"
  34. advice. Root keeps the host-wide view (``sudo … --system`` over a ``User=`` unit), as does
  35. Windows (no ``geteuid``); an unknown owner is not called foreign.
  36. """
  37. my_uid = os.geteuid() if hasattr(os, "geteuid") else 0
  38. owner = _pid_uid(pid) if my_uid else None
  39. return owner is not None and owner != my_uid
  40. def _system_unit_uid(unit_path: Path) -> Optional[int]:
  41. """uid a system unit runs as: its ``User=`` (root when absent); None when the name is unknown."""
  42. from hermes_cli.gateway import _read_systemd_user_from_unit
  43. user = _read_systemd_user_from_unit(unit_path)
  44. if user is None:
  45. return 0
  46. import pwd
  47. with contextlib.suppress(KeyError):
  48. return pwd.getpwnam(user).pw_uid
  49. return None
  50. def gateway_identity(home: Path, pid: Optional[int], services: list[tuple[str, bool]]) -> tuple[Optional[int], Path]:
  51. """``(uid, runtime_home)`` of the gateway that serves ``home``.
  52. uid: the live process owner; else, for a system unit, its ``User=`` — and ONLY that: a system
  53. unit's principal is whatever systemd will run, so an unresolvable ``User=`` stays None rather than
  54. borrowing the profile directory's owner (a stopped unit pinned to an absent NSS user is not the
  55. account that owns the files). Without a system unit (user-scope systemd / launchd / detached), the
  56. profile directory owner is the account the gateway runs as. None means unknown. runtime_home: the
  57. HERMES_HOME an installed unit pins, which is where the gateway really runs; ``home`` otherwise.
  58. """
  59. from hermes_cli.gateway import _hermes_home_pinned_by_unit, get_systemd_unit_path
  60. from hermes_cli.gateway_migrate import _home_env
  61. uid: Optional[int] = _pid_uid(pid) if pid is not None else None
  62. runtime_home = home
  63. has_system_unit = False
  64. for kind, system in services:
  65. if kind != "systemd":
  66. continue
  67. with _home_env(home):
  68. unit_path = get_systemd_unit_path(system=system)
  69. pinned = _hermes_home_pinned_by_unit(unit_path)
  70. if pinned and runtime_home == home:
  71. runtime_home = Path(pinned).expanduser()
  72. if system:
  73. has_system_unit = True
  74. if uid is None:
  75. uid = _system_unit_uid(unit_path)
  76. if uid is None and not has_system_unit:
  77. with contextlib.suppress(OSError):
  78. uid = home.stat().st_uid
  79. return uid, runtime_home
  80. # --------------------------------------------------------------------------- guards
  81. def _service_label(profile: ProfileGateway) -> str:
  82. return profile.service_label() if profile.services else "no service manager (detached)"
  83. def _guard_service_domain(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]:
  84. """Different manager or scope than the one the fleet converges on (system vs user systemd, launchd vs
  85. systemd). The reference is the default's own unit when it has one, else the manager
  86. ``target_service_kind()`` elects from the secondaries: a default that never had a gateway unit is not a
  87. service domain of its own, and refusing every secondary against it left the common upgrade fleet (N
  88. launchd profiles, unit-less default, #118097) printing blockers instead of folding. Two managers
  89. among the secondaries still refuse — the ones not elected differ from the target. Two units on one
  90. profile is an ambiguous topology the unattended path does not resolve either."""
  91. if len(profile.services) > 1:
  92. return (f"Profile '{profile.name}' has more than one installed service ({profile.service_label()}): "
  93. f"an ambiguous service topology is not folded automatically.")
  94. target = plan.target_service_kind()
  95. reference = plan.default.services or ([target] if target is not None else [])
  96. if set(profile.services) == set(reference):
  97. return None
  98. from hermes_cli.gateway_migrate import _service_label as _kind_label
  99. against = (f"the default gateway runs under {_service_label(plan.default)}" if plan.default.services
  100. else f"the fleet converges on {_kind_label(target)}")
  101. return (f"Profile '{profile.name}' runs under {_service_label(profile)} while {against}: "
  102. f"a different service domain is not folded automatically.")
  103. def _guard_unix_user(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]:
  104. default_uid = plan.default.uid
  105. if default_uid is None and plan.default.has_system_unit:
  106. # Consolidating INTO a principal this host cannot identify is the same unknown boundary
  107. # from the other side: the default's system unit names an account NSS does not resolve.
  108. return ("The default gateway runs a system unit whose User= cannot be resolved on this host: "
  109. "an unknown service principal is not folded into automatically.")
  110. if profile.uid is None and profile.has_system_unit:
  111. # Unknown principal is not "same user": the unit names an account this host cannot resolve.
  112. return (f"Profile '{profile.name}' runs a system unit whose User= cannot be resolved on this host: "
  113. f"an unknown service principal is not folded automatically.")
  114. if default_uid is None or profile.uid is None or profile.uid == default_uid:
  115. return None
  116. return (f"Profile '{profile.name}' runs as uid {profile.uid} while the default gateway runs as uid "
  117. f"{default_uid}: a UNIX privilege boundary is not folded automatically.")
  118. def _guard_home_tree(plan: MigrationPlan, profile: ProfileGateway) -> Optional[str]:
  119. profiles_root = (plan.default_home / "profiles").resolve()
  120. runtime_home = (profile.runtime_home or profile.home).resolve()
  121. if runtime_home.is_relative_to(profiles_root):
  122. return None
  123. return (f"Profile '{profile.name}' runs with HERMES_HOME={runtime_home}, outside {profiles_root}: "
  124. f"the multiplexer would serve {profile.home} instead of the live home.")
  125. _AUTO_MIGRATION_GUARDS: tuple[Callable[[MigrationPlan, ProfileGateway], Optional[str]], ...] = (
  126. _guard_service_domain,
  127. _guard_unix_user,
  128. _guard_home_tree,
  129. )
  130. def auto_migration_blockers(plan: MigrationPlan) -> list[str]:
  131. """Every boundary a standalone secondary sits behind; empty when the fleet is one user, one service
  132. domain, one profiles/ tree — the only shape ``hermes update`` may fold on its own."""
  133. findings = [
  134. finding
  135. for profile in plan.standalone_secondaries
  136. for guard in _AUTO_MIGRATION_GUARDS
  137. if (finding := guard(plan, profile)) is not None
  138. ]
  139. return list(dict.fromkeys(findings)) # a default-side finding repeats per secondary
  140. # --------------------------------------------------------------------------- opt-out
  141. def masked_default_unit(default_home: Path) -> Optional[Path]:
  142. """The default profile's systemd unit when the operator MASKED it (``systemctl mask`` links it to
  143. ``/dev/null``), else None. A masked survivor cannot be enabled at boot, and masking is a deliberate
  144. "never start this", so the update hook reads it as an opt-out instead of refusing (#139324)."""
  145. from hermes_cli import gateway as gw
  146. from hermes_cli.gateway_migrate import _home_env
  147. with _home_env(default_home):
  148. units = [gw.get_systemd_unit_path(system=system) for system in (False, True)]
  149. for unit in units:
  150. with contextlib.suppress(OSError):
  151. if unit.is_symlink() and os.path.realpath(unit) == os.devnull:
  152. return unit
  153. return None
  154. def auto_migration_opted_out(default_home: Path) -> bool:
  155. """``gateway.auto_multiplex_migration: false`` in the DEFAULT profile's EFFECTIVE config: the same
  156. ``load_config`` the rest of the CLI reads (``DEFAULT_CONFIG`` + config.yaml + the managed overlay), so
  157. an administrator's managed ``false`` wins over a user's ``true`` and a YAML string ``"false"`` is
  158. false, not truthy. Only the nested key counts, there is no top-level alias."""
  159. from hermes_cli.config import load_config_readonly
  160. from hermes_cli.gateway_migrate import _home_env
  161. from utils import is_truthy_value
  162. with _home_env(default_home):
  163. gateway_section = load_config_readonly().get("gateway")
  164. if not isinstance(gateway_section, dict):
  165. return False
  166. return not is_truthy_value(gateway_section.get("auto_multiplex_migration"), default=True)