credentials.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """The plane credential (design §4.4 step 2, D26, D31, D32).
  2. Cloud: the Nous access token from the profile's ``auth.json`` (``resolve_nous_access_token``).
  3. On-prem: an IdP workload token from the OAuth2 client-credentials grant, configured by
  4. ``GATEWAY_RELAY_IDP_*`` values in ``.env``. Never from config.yaml (the config is what this token
  5. fetches) and never from a secret source: :data:`PLANE_CREDENTIAL_ENV_NAMES` lists every env name
  6. that decides which token is sent where, and boot refuses a secret source that supplies one.
  7. """
  8. from __future__ import annotations
  9. import hashlib
  10. import json
  11. import os
  12. import threading
  13. import time
  14. import urllib.parse
  15. import urllib.request
  16. from pathlib import Path
  17. from typing import Dict, Tuple
  18. IDP_ENV_PREFIX = "GATEWAY_RELAY_IDP_"
  19. _IDP_KEYS = ("token_url", "client_id", "client_secret", "scope")
  20. PLANE_CREDENTIAL_ENV_NAMES = frozenset({
  21. # which backend, which plane, which agent record
  22. "HERMES_CONFIG_BACKEND", "HERMES_CONFIG_REMOTE_URL", "HERMES_CONFIG_INSTANCE_ID",
  23. # on-prem workload identity
  24. *(IDP_ENV_PREFIX + k.upper() for k in _IDP_KEYS),
  25. # Cloud: where auth.json lives and where its refresh token is sent
  26. "HERMES_SHARED_AUTH_DIR", "HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL",
  27. })
  28. _HTTP_TIMEOUT_S = 15.0
  29. class PlaneCredentialError(RuntimeError):
  30. """No plane credential could be obtained. ``retryable`` is False for a missing or partial
  31. configuration (retrying cannot help)."""
  32. def __init__(self, message: str, *, retryable: bool) -> None:
  33. super().__init__(message)
  34. self.retryable = retryable
  35. _IDP_CACHE: dict[tuple[str, str, str, str], tuple[float, str]] = {}
  36. _IDP_LOCK = threading.Lock()
  37. def _idp_env() -> dict[str, str]:
  38. return {k: os.environ.get(IDP_ENV_PREFIX + k.upper(), "").strip() for k in _IDP_KEYS}
  39. def credential_kind() -> str:
  40. return "idp" if _idp_env()["token_url"] else "nous"
  41. def plane_token(home: Path) -> str:
  42. """A fresh bearer for ``home``'s requests (re-resolved per request, contract §10.2)."""
  43. return _idp_token() if credential_kind() == "idp" else _nous_token(home)
  44. def _nous_token(home: Path) -> str:
  45. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  46. try:
  47. from hermes_cli.auth import resolve_nous_access_token
  48. except Exception as exc:
  49. raise PlaneCredentialError(f"cannot load the Nous auth module: {exc}", retryable=False) from exc
  50. token = set_hermes_home_override(home) # auth.json is per profile home
  51. try:
  52. return resolve_nous_access_token()
  53. except Exception as exc:
  54. # A missing login or a revoked session needs a human; a refresh that hit the network can retry.
  55. fatal = bool(getattr(exc, "relogin_required", False)) or getattr(exc, "code", None) == "nous_auth_missing"
  56. raise PlaneCredentialError(
  57. f"no Nous access token for {home} (auth.json): {exc}", retryable=not fatal) from exc
  58. finally:
  59. reset_hermes_home_override(token)
  60. def _idp_token() -> str:
  61. env = _idp_env()
  62. token_url, client_id, client_secret, scope = (env[k] for k in _IDP_KEYS)
  63. if not client_id or not client_secret:
  64. raise PlaneCredentialError(
  65. f"{IDP_ENV_PREFIX}TOKEN_URL is set but {IDP_ENV_PREFIX}CLIENT_ID / {IDP_ENV_PREFIX}CLIENT_SECRET "
  66. "are not: Remote Config needs the OAuth2 client-credentials grant (both values in .env).",
  67. retryable=False)
  68. from .destination import CredentialDestinationError, checked_url, display_url, open_credentialed
  69. checked_url(token_url, env_name=f"{IDP_ENV_PREFIX}TOKEN_URL") # before the secret leaves the process
  70. # The secret is part of the identity: a rotated secret fetches a new token on the next request.
  71. key = (token_url, client_id, scope, hashlib.sha256(client_secret.encode()).hexdigest())
  72. now = time.monotonic()
  73. with _IDP_LOCK:
  74. cached = _IDP_CACHE.get(key)
  75. if cached is not None and cached[0] > now:
  76. return cached[1]
  77. form = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret}
  78. if scope:
  79. form["scope"] = scope
  80. req = urllib.request.Request(
  81. token_url, data=urllib.parse.urlencode(form).encode(), method="POST",
  82. headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"})
  83. try:
  84. with open_credentialed(req, timeout=_HTTP_TIMEOUT_S) as resp:
  85. payload = json.loads(resp.read().decode() or "{}")
  86. except CredentialDestinationError:
  87. raise
  88. except Exception as exc: # HTTP and network errors alike; the message has no secret
  89. raise PlaneCredentialError(f"IdP token request to {display_url(token_url)} failed: {exc}", retryable=True) from exc
  90. access_token = payload.get("access_token") if isinstance(payload, dict) else None
  91. if not isinstance(access_token, str) or not access_token:
  92. raise PlaneCredentialError("IdP client-credentials response had no access_token", retryable=True)
  93. expires_in = payload.get("expires_in")
  94. ttl = float(expires_in) if isinstance(expires_in, int | float) and expires_in > 0 else 60.0
  95. with _IDP_LOCK:
  96. _IDP_CACHE[key] = (now + max(ttl - 30.0, 0.0), access_token)
  97. return access_token