gateway_enroll.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """``hermes gateway enroll`` — enroll a self-hosted gateway with a relay connector.
  2. Managed/hosted installs do NOT self-enroll: the orchestrator mints the secret and stamps it into the
  3. container env, so this refuses to run under ``is_managed()`` (mirrors ``dashboard register``).
  4. EXPERIMENTAL: the relay auth scheme may change without a deprecation cycle.
  5. """
  6. from __future__ import annotations
  7. import json
  8. import os
  9. import socket
  10. import sys
  11. import urllib.error
  12. import urllib.request
  13. from pathlib import Path
  14. from typing import Optional
  15. def _default_gateway_id() -> str:
  16. """``gw-<hostname>``: the gatewayId is the connector's kill-switch granularity, so default to
  17. the host name for recognizability; override via ``--gateway-id``."""
  18. try:
  19. host = socket.gethostname().strip()
  20. except Exception:
  21. host = ""
  22. return f"gw-{host or 'hermes'}"
  23. def _resolve_connector_url(override: Optional[str]) -> Optional[str]:
  24. """Connector base URL (no trailing slash): ``--connector-url`` > ``GATEWAY_RELAY_URL`` >
  25. ``gateway.relay_url``. The relay URL is a ``ws(s)://…/relay`` dial target; enrollment POSTs to
  26. ``http(s)://`` on the same host, so map the scheme and strip a pasted ``/relay`` suffix."""
  27. raw = (override or os.environ.get("GATEWAY_RELAY_URL", "")).strip()
  28. if not raw:
  29. try:
  30. from gateway.run import _load_gateway_config # late import to avoid cycle
  31. raw = str((_load_gateway_config().get("gateway") or {}).get("relay_url", "") or "").strip()
  32. except Exception:
  33. raw = ""
  34. if not raw:
  35. return None
  36. for ws_scheme, http_scheme in (("ws://", "http://"), ("wss://", "https://")):
  37. if raw.startswith(ws_scheme):
  38. raw = http_scheme + raw[len(ws_scheme):]
  39. break
  40. return raw.rstrip("/").removesuffix("/relay")
  41. def _post_enroll(
  42. *,
  43. connector_base_url: str,
  44. access_token: str,
  45. enrollment_token: str,
  46. gateway_id: str,
  47. timeout: float = 15.0,
  48. ) -> dict:
  49. """POST to the connector's ``/relay/enroll``; return ``{secret, deliveryKey, tenant, gatewayId}``.
  50. Raises RuntimeError with a user-facing message on any non-2xx / transport failure."""
  51. url = f"{connector_base_url.rstrip('/')}/relay/enroll"
  52. data = json.dumps({"enrollmentToken": enrollment_token, "gatewayId": gateway_id}).encode("utf-8")
  53. req = urllib.request.Request(
  54. url,
  55. data=data,
  56. method="POST",
  57. headers={
  58. "Authorization": f"Bearer {access_token}",
  59. "Content-Type": "application/json",
  60. "Accept": "application/json",
  61. },
  62. )
  63. try:
  64. with urllib.request.urlopen(req, timeout=timeout) as resp:
  65. payload = json.loads(resp.read().decode())
  66. except urllib.error.HTTPError as exc:
  67. detail = ""
  68. try:
  69. detail = (json.loads(exc.read().decode()) or {}).get("error", "")
  70. except Exception:
  71. pass
  72. if exc.code == 401:
  73. message = (
  74. "Connector rejected the caller identity (401). Your Nous Portal "
  75. "token could not be verified — try `hermes auth add nous` and retry."
  76. )
  77. elif exc.code == 403:
  78. message = detail or "Enrollment token invalid, expired, already used, or tenant mismatch (403)."
  79. else:
  80. message = f"Connector returned HTTP {exc.code}" + (f": {detail}" if detail else "")
  81. raise RuntimeError(message) from exc
  82. except urllib.error.URLError as exc:
  83. raise RuntimeError(
  84. f"Could not reach the connector at {connector_base_url}: {exc.reason}"
  85. ) from exc
  86. if not isinstance(payload, dict) or not payload.get("secret"):
  87. raise RuntimeError("Connector returned an unexpected response (no secret).")
  88. return payload
  89. def _fail(*lines: str) -> None:
  90. for line in lines:
  91. print(line)
  92. sys.exit(1)
  93. def cmd_gateway_enroll(args) -> None:
  94. """Enroll this gateway with a relay connector; persist the auth creds to .env."""
  95. from hermes_cli.auth import AuthError
  96. from hermes_cli.config import is_managed, save_env_value
  97. # Managed installs get GATEWAY_RELAY_* stamped in by the orchestrator; save_env_value refuses
  98. # to write there anyway.
  99. if is_managed():
  100. _fail(
  101. "✗ `hermes gateway enroll` is not available in a managed/hosted install.\n"
  102. " The relay gateway secret is provisioned by the hosting platform."
  103. )
  104. enrollment_token = (getattr(args, "token", None) or os.environ.get("GATEWAY_RELAY_ENROLL_TOKEN", "")).strip()
  105. if not enrollment_token:
  106. _fail(
  107. "✗ No enrollment token. Pass --token <token> (or set "
  108. "GATEWAY_RELAY_ENROLL_TOKEN).\n"
  109. " The connector mints this single-use token when your tenant's route "
  110. "is provisioned; it is delivered with your gateway config."
  111. )
  112. connector_base_url = _resolve_connector_url(getattr(args, "connector_url", None))
  113. if not connector_base_url:
  114. _fail(
  115. "✗ No connector URL. Pass --connector-url <url> (or set GATEWAY_RELAY_URL "
  116. "/ gateway.relay_url in config.yaml)."
  117. )
  118. gateway_id = (getattr(args, "gateway_id", None) or _default_gateway_id()).strip()
  119. # Caller-identity token (proves the tenant). ``gateway.relay`` owns the ONE resolver shared with
  120. # the runtime self-provision path: generic OIDC client-credentials when ``gateway.idp.token_url``
  121. # is set (air-gapped / self-hosted IdP), otherwise Nous Portal.
  122. try:
  123. from gateway.relay import _resolve_relay_identity_token
  124. access_token = _resolve_relay_identity_token()
  125. except AuthError as exc:
  126. if getattr(exc, "relogin_required", False):
  127. _fail(
  128. "✗ You're not logged into Nous Portal.",
  129. " Run `hermes setup` (or `hermes auth add nous`) first, then retry.",
  130. )
  131. _fail(f"✗ Could not resolve a Nous Portal access token: {exc}")
  132. except Exception as exc:
  133. _fail(f"✗ Could not resolve a caller-identity token: {exc}")
  134. try:
  135. result = _post_enroll(
  136. connector_base_url=connector_base_url,
  137. access_token=access_token,
  138. enrollment_token=enrollment_token,
  139. gateway_id=gateway_id,
  140. )
  141. except RuntimeError as exc:
  142. _fail(f"✗ Enrollment failed: {exc}")
  143. tenant = str(result.get("tenant") or "")
  144. resolved_gateway_id = str(result.get("gatewayId") or gateway_id)
  145. # Persist idempotently; save_env_value writes the sensitive values to ~/.hermes/.env and never
  146. # logs them. Explicitly supplied URLs are persisted too: the ws(s):// dial target so the runtime
  147. # needn't re-specify it, and the wake URL so self_provision_relay forwards it to the connector
  148. # (which pokes it when buffered work arrives while idle; omitted ⇒ drains on next reconnect).
  149. to_write = {
  150. "GATEWAY_RELAY_ID": resolved_gateway_id,
  151. "GATEWAY_RELAY_SECRET": str(result.get("secret") or ""),
  152. "GATEWAY_RELAY_DELIVERY_KEY": str(result.get("deliveryKey") or ""),
  153. }
  154. explicit_urls = {
  155. env_key: (getattr(args, arg, None) or "").strip()
  156. for arg, env_key in (("connector_url", "GATEWAY_RELAY_URL"), ("wake_url", "GATEWAY_RELAY_WAKE_URL"))
  157. }
  158. to_write.update({k: v.rstrip("/") for k, v in explicit_urls.items() if v})
  159. for key, value in to_write.items():
  160. if not value:
  161. continue
  162. try:
  163. save_env_value(key, value)
  164. except Exception as exc:
  165. _fail(f"✗ Failed to write {key} to .env: {exc}")
  166. from hermes_cli.config import get_env_path
  167. print(f'✓ Enrolled gateway "{resolved_gateway_id}"' + (f" for tenant {tenant}" if tenant else ""))
  168. print()
  169. print(f" Wrote to {get_env_path()}:")
  170. for key, value in to_write.items():
  171. shown = "<hidden>" if key in ("GATEWAY_RELAY_SECRET", "GATEWAY_RELAY_DELIVERY_KEY") else value
  172. print(f" {key}={shown}")
  173. print()
  174. # GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-global deployment stamps
  175. # (agent/secret_scope.py): a multiplexed gateway reads them from the PROCESS environment only,
  176. # never a secondary profile's .env. Warn (don't refuse) so a secondary-profile enroll can't claim
  177. # a config that silently never activates — BEFORE the generic restart line so they don't clash.
  178. if not (any(explicit_urls.values()) and _warn_if_secondary_multiplex_profile()):
  179. print(
  180. " The gateway now authenticates its relay WS upgrade with the per-gateway\n"
  181. " secret and verifies signed inbound deliveries with the tenant delivery\n"
  182. " key. Restart the gateway to pick up the new env."
  183. )
  184. def _warn_if_secondary_multiplex_profile() -> bool:
  185. """Warn when relay routing stamps landed in a secondary profile's .env that a multiplexed gateway
  186. will never read. Returns True when the warning fired (caller suppresses the restart text)."""
  187. try:
  188. from hermes_constants import get_default_hermes_root
  189. from hermes_cli.config import get_hermes_home
  190. default_root = Path(get_default_hermes_root()).resolve()
  191. home = Path(get_hermes_home()).resolve()
  192. try:
  193. home.relative_to(default_root / "profiles")
  194. except ValueError:
  195. return False # default profile or custom layout — not a secondary
  196. # The LIVE default gateway's served record, else the operator's explicit flag (env override
  197. # wins, then a RAW read of the DEFAULT root's config.yaml — the active profile's
  198. # load_gateway_config() is the wrong owner and runs the full enablement pass, whose log output
  199. # has no place in enroll output). An unset flag is settled by the gateway at boot, not here.
  200. from hermes_cli.gateway_multiplex_mode import default_gateway_multiplexes
  201. if not default_gateway_multiplexes(default_root):
  202. return False
  203. print(
  204. " ⚠ This profile is a SECONDARY profile of a multiplexed gateway.\n"
  205. " GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-level\n"
  206. " deployment settings: the gateway reads them from the process\n"
  207. " environment (or the default profile's .env), not from this\n"
  208. " profile's .env. Set them in the environment the gateway process\n"
  209. " is launched with, or enroll from the default profile. The\n"
  210. " relay credentials written above are valid either way."
  211. )
  212. return True
  213. except Exception:
  214. return False