gateway_service_owner.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """Who may write a gateway service definition (systemd unit, launchd plist).
  2. A service definition pins the ``HERMES_HOME`` its gateway runs with. Service names are derived from the
  3. home (bare / profile name / path hash), and two homes can still resolve to the same name: a custom root's
  4. ``<root>/profiles/<name>`` takes the same ``hermes-gateway-<name>`` unit as ``~/.hermes/profiles/<name>``.
  5. Every gateway boot refreshes "its" unit, so a scratch or E2E gateway started from such a home rewrote the
  6. real install's unit to point at the scratch directory, and the real gateway failed on its next restart.
  7. The rule: a definition that pins a home is written only by a process acting for that home. Uninstall
  8. already refused a unit pinning another home (``_systemd_unit_belongs_to_current_home``); the writers now
  9. refuse the same way. ``hermes gateway install --force-unit-path`` is the explicit repoint.
  10. """
  11. from __future__ import annotations
  12. import os
  13. import plistlib
  14. import sys
  15. from pathlib import Path
  16. from xml.parsers.expat import ExpatError
  17. def pinned_home(definition_path: Path) -> str | None:
  18. """``HERMES_HOME`` pinned by the systemd unit or launchd plist at *definition_path*, or None."""
  19. if definition_path.suffix == ".plist":
  20. try:
  21. with definition_path.open("rb") as fh:
  22. data = plistlib.load(fh)
  23. except (OSError, ValueError, ExpatError): # unreadable / not a plist: pins nobody
  24. return None
  25. env = data.get("EnvironmentVariables") if isinstance(data, dict) else None
  26. value = env.get("HERMES_HOME") if isinstance(env, dict) else None
  27. return (str(value).strip() or None) if value is not None else None
  28. from hermes_cli import gateway as gw
  29. return gw._hermes_home_pinned_by_unit(definition_path)
  30. def _resolve(raw: str | Path) -> Path | None:
  31. try:
  32. return Path(raw).expanduser().resolve()
  33. except (OSError, RuntimeError, ValueError):
  34. return None
  35. def service_home_for_unit(unit_path: Path, system: bool) -> Path:
  36. """The ``HERMES_HOME`` this process acts for when it writes the systemd unit at *unit_path*.
  37. User scope: its own home. System scope: an explicit ``HERMES_HOME`` remapped to the unit's ``User=``
  38. account the way ``generate_systemd_unit`` pins it; with none (``sudo`` strips it, HOME=/root), the
  39. unit's own pinned home, which is the only thing naming the install being operated on. Pure: it never
  40. adopts the unit's home into ``os.environ``, so a check on this value compares caller and unit.
  41. """
  42. from hermes_cli import gateway as gw
  43. if not system:
  44. return gw.get_hermes_home()
  45. if not os.environ.get("HERMES_HOME", "").strip():
  46. pinned = pinned_home(unit_path) if unit_path.exists() else None
  47. return Path(pinned).expanduser() if pinned else gw.get_hermes_home()
  48. user = gw._read_systemd_user_from_unit(unit_path)
  49. if not user:
  50. return gw.get_hermes_home()
  51. try:
  52. home_dir = gw._system_service_identity(run_as_user=user)[2]
  53. except ValueError: # unknown User=: generate_systemd_unit refuses the same way
  54. return gw.get_hermes_home()
  55. return Path(gw._hermes_home_for_target_user(home_dir))
  56. def definition_belongs_to_home(definition_path: Path, home: Path, action: str) -> bool:
  57. """False (with guidance printed) when the existing definition pins a ``HERMES_HOME`` other than *home*.
  58. A missing definition, or one that pins no home (hand-written, pre-pinning), belongs to nobody else.
  59. """
  60. if not definition_path.exists():
  61. return True
  62. raw = pinned_home(definition_path)
  63. if raw is None or _resolve(raw) == _resolve(home):
  64. return True
  65. print(f"✗ Refusing to {action} {definition_path}: it runs HERMES_HOME={raw}, "
  66. f"but this process has HERMES_HOME={home}.")
  67. print(" That file is another install's gateway. Use that install, or pass --force-unit-path")
  68. print(" to `hermes gateway install` if you really mean to repoint it at this home.")
  69. return False
  70. def unit_belongs_to_caller(unit_path: Path, system: bool, action: str, run_as_user: str | None = None) -> bool:
  71. """``definition_belongs_to_home`` for the systemd unit at *unit_path*, judged against the home this
  72. process would pin there (``run_as_user``'s for an explicit ``--system --run-as-user`` install)."""
  73. from hermes_cli import gateway as gw
  74. home = service_home_for_unit(unit_path, system)
  75. if system and run_as_user:
  76. try:
  77. home = Path(gw._hermes_home_for_target_user(gw._system_service_identity(run_as_user)[2]))
  78. except ValueError:
  79. pass # unknown account: generate_systemd_unit refuses it later with the real error
  80. return definition_belongs_to_home(unit_path, home, action)
  81. def foreign_systemd_unit_home(system: bool) -> str | None:
  82. """``HERMES_HOME`` of the unit at this scope when it belongs to ANOTHER install, else None.
  83. A throwaway ``HOME`` used to resolve the bare ``hermes-gateway`` name (its ``.hermes`` looked native) and
  84. reach the account's real unit — user scope through the account-anchored unit dir, system scope
  85. because system units are global. Naming now follows the account home, but two homes can still share
  86. a name (a custom root's ``profiles/<name>``, a pre-pinning unit), so every systemd verb asks this.
  87. ``_sync_hermes_home_from_systemd_unit`` would adopt the unit's home and ``stop``/``restart`` would take
  88. the live gateway down, so it must be evaluated BEFORE that sync.
  89. Foreign means: the unit pins a home, it differs from this process's home, and this process's home
  90. is not the account's own default root. The last clause keeps the ``sudo`` remap (#108674): root's
  91. default home operating a unit that pins the invoking user's home is the operator, not a stranger.
  92. """
  93. from hermes_cli import gateway as gw
  94. unit_home = gw._hermes_home_pinned_by_unit(gw.get_systemd_unit_path(system=system))
  95. if not unit_home:
  96. return None
  97. try:
  98. unit = Path(unit_home).expanduser().resolve()
  99. mine = gw.get_hermes_home().resolve()
  100. except OSError:
  101. return None
  102. if unit == mine:
  103. return None
  104. from hermes_constants import account_default_hermes_home
  105. if mine == account_default_hermes_home().resolve():
  106. return None
  107. return unit_home
  108. def refuse_foreign_systemd_unit(action: str, system: bool) -> None:
  109. """Exit non-zero instead of operating another install's unit (see ``foreign_systemd_unit_home``)."""
  110. from hermes_cli import gateway as gw
  111. unit_home = foreign_systemd_unit_home(system)
  112. if unit_home is None:
  113. return
  114. gw.print_error(
  115. f"Refusing to {action} {gw.get_service_name()}: that {gw._service_scope_label(system)} unit runs "
  116. f"HERMES_HOME={unit_home}, but this process has HERMES_HOME={gw.get_hermes_home()}.\n"
  117. f"It belongs to another Hermes install. Run this from that install's HERMES_HOME."
  118. )
  119. sys.exit(1)
  120. def refuse_foreign_launchd_plist(verb: str) -> None:
  121. """The launchd half of ``refuse_foreign_systemd_unit``: exit 1 rather than start/stop/restart/remove a
  122. LaunchAgent pinning another HERMES_HOME. (Windows task names derive from LOCALAPPDATA, not HOME.)"""
  123. from hermes_cli import gateway as gw
  124. if not definition_belongs_to_home(gw.get_launchd_plist_path(), gw.get_hermes_home(), verb):
  125. sys.exit(1)
  126. def service_definition_homes(definition: str) -> list[str]:
  127. """Every HERMES_HOME a gateway service definition sets: systemd ``Environment=``, launchd
  128. ``EnvironmentVariables``, the Windows ``gateway.cmd`` ``set`` line and the ``gateway.vbs`` env item."""
  129. import re
  130. homes = re.findall(r'HERMES_HOME=([^"\r\n]+)', definition)
  131. homes += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.DOTALL)
  132. homes += re.findall(r'Item\("HERMES_HOME"\)\s*=\s*"([^"\r\n]+)"', definition)
  133. return homes
  134. def service_definition_launchers(definition: str) -> list[str]:
  135. """The scripts a definition starts, by their quoted absolute paths. The Windows Startup-folder
  136. fallback and a Scheduled Task's action name no home: they start the home's ``gateway.vbs``, which does."""
  137. import re
  138. found = re.findall(r'"((?:[A-Za-z]:[\\/]|\\\\|/)[^"\r\n]*\.(?:vbs|cmd))"', definition, flags=re.IGNORECASE)
  139. return list(dict.fromkeys(found))
  140. def temp_home_in_service_definition(definition: str) -> str | None:
  141. """Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a
  142. test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""
  143. import tempfile
  144. candidates = service_definition_homes(definition)
  145. temp_roots = {
  146. Path(tempfile.gettempdir()).resolve(),
  147. Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions
  148. }
  149. for raw in candidates:
  150. try:
  151. resolved = Path(raw.strip().strip('"')).resolve()
  152. except (OSError, ValueError):
  153. continue
  154. if any(resolved == root or root in resolved.parents for root in temp_roots):
  155. return raw.strip()
  156. return None
  157. def refuse_temp_home_service_write(definition: str, kind: str) -> bool:
  158. """Refuse (with guidance) when a service definition carries a temp HERMES_HOME."""
  159. temp_home = temp_home_in_service_definition(definition)
  160. if temp_home is None:
  161. return False
  162. print(f"✗ Refusing to write the gateway {kind}: HERMES_HOME resolves to a temporary directory ({temp_home}).")
  163. print(
  164. " This usually means a test/E2E environment exported HERMES_HOME. "
  165. "Unset it (or run from a clean shell) and retry."
  166. )
  167. return True