__init__.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """SessionTokenProvider — the deployment session token as a first-class credential.
  2. Gated mode (non-loopback bind) demands a registered ``DashboardAuthProvider`` and verifies
  3. every bearer / WS ``?token=`` through ``verify_session``. The nix/agenix deployment story
  4. (``backend.sessionTokenFile`` → ``HERMES_DASHBOARD_SESSION_TOKEN=file:<path>``) provisions
  5. exactly one shared secret — the same token the Desktop's "Session token" connection field
  6. presents — but until now nothing vouched for it in gated mode, so a token-only deployment
  7. was forced through the interactive provider prompt into basic-auth credentials it never
  8. asked for. This provider closes that gap: it registers whenever the session token is
  9. provisioned (and not explicitly disabled), and ``verify_session`` constant-time-compares
  10. the presented credential against it. Both auth legs the Desktop uses — the REST
  11. ``Authorization: Bearer`` path and the ``/api/ws`` ``?token=`` upgrade credential — run
  12. through that seam, so one provisioned token authorizes both.
  13. It is deliberately NOT an interactive login: no login-page button, no cookies, no refresh.
  14. A browser visiting a token-gated dashboard sees a note pointing at the deployment's
  15. credential channel instead of a dead sign-in link. Disable with
  16. ``dashboard.session_token_auth.enabled: false`` in config.yaml (the env var itself is the
  17. opt-in; it is a credential, so there is deliberately no new env var for the toggle).
  18. """
  19. from __future__ import annotations
  20. import hmac
  21. import logging
  22. import os
  23. import time
  24. from typing import Optional
  25. from hermes_cli.dashboard_auth import (
  26. DashboardAuthProvider, RefreshExpiredError, Session)
  27. from plugins.dashboard_auth._shared import (
  28. NonInteractiveMixin, SkipRegistration, load_config_section, register_provider)
  29. logger = logging.getLogger(__name__)
  30. _TAG = "dashboard-auth-session-token"
  31. # The verifier re-derives an expiry on every verify (the credential itself never
  32. # expires — rotation is replacing the env var / secret file), so this only bounds
  33. # how long anything that ever minted a cookie from a verified session would keep it.
  34. _SESSION_HORIZON_SECONDS = 24 * 60 * 60
  35. LAST_SKIP_REASON: str = ""
  36. def _resolve_provisioned_token() -> str:
  37. """The exact token ``web_server`` serves under: env value, or the contents of a
  38. ``file:``-prefixed path (BOM-tolerant, same reader). Raises ``SystemExit`` for an
  39. unreadable/empty token file — ``register`` maps that to a skip so plugin discovery
  40. never dies for a sibling provider's misconfiguration."""
  41. from hermes_cli.web_server_session_token import resolve_session_token
  42. return resolve_session_token()
  43. def _load_session_token_auth_section() -> dict:
  44. return load_config_section(logger, _TAG, "dashboard", "session_token_auth")
  45. def _opt_out() -> bool:
  46. """``dashboard.session_token_auth.enabled: false`` disables the provider. There is no
  47. env toggle: the enabling side of this switch IS ``HERMES_DASHBOARD_SESSION_TOKEN``, a
  48. credential; behaviour belongs in config.yaml."""
  49. section = _load_session_token_auth_section()
  50. return str(section.get("enabled", True)).strip().lower() in ("0", "false", "no", "off")
  51. def _settings() -> dict:
  52. """Resolve SessionTokenProvider kwargs; raises ``SkipRegistration`` when the token is
  53. not provisioned, the provider is disabled, or the token file is unreadable (the file
  54. resolver's ``SystemExit`` — a deployment misconfiguration must not crash plugin
  55. discovery for every sibling plugin)."""
  56. if not os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN", "").strip():
  57. raise SkipRegistration(
  58. "HERMES_DASHBOARD_SESSION_TOKEN is not set. Provision it (a literal token, or "
  59. "'file:<path>' pointing at a secret-manager-decrypted token file) to let the "
  60. "deployment session token authorize the gated dashboard.")
  61. if _opt_out():
  62. raise SkipRegistration(
  63. "dashboard.session_token_auth.enabled is false; the deployment session token "
  64. "does not authenticate the gated dashboard.")
  65. try:
  66. token = _resolve_provisioned_token()
  67. except SystemExit as exc:
  68. raise SkipRegistration(str(exc), level="error") from exc
  69. if len(token) < 32:
  70. logger.warning(
  71. "%s: the provisioned session token is short (%d chars); use a "
  72. "`secrets.token_urlsafe(32)`-shaped value for a deployment credential.",
  73. _TAG, len(token))
  74. return {"token": token}
  75. class SessionTokenProvider(NonInteractiveMixin, DashboardAuthProvider):
  76. """Vouches for the deployment session token (``HERMES_DASHBOARD_SESSION_TOKEN``).
  77. ``supports_session`` is True — the presented bearer/``?token=`` IS the session
  78. credential the middleware seam verifies — while ``interactive_login`` is False: there
  79. is no browser sign-in flow, so login surfaces must not offer it.
  80. """
  81. name = "session-token"
  82. display_name = "Deployment Session Token"
  83. supports_password = False
  84. supports_session = True
  85. interactive_login = False
  86. _NOT_INTERACTIVE = (
  87. "SessionTokenProvider has no login flow: clients present the provisioned session "
  88. "token directly (Authorization: Bearer, or ?token= on the /api/ws upgrade).")
  89. _NO_START_LOGIN = _NOT_INTERACTIVE
  90. def __init__(self, *, token: str) -> None:
  91. if not token:
  92. raise ValueError("token must be non-empty")
  93. self._token = token
  94. # ---- session verification (the one capability) --------------------------
  95. def verify_session(self, *, access_token: str) -> Optional[Session]:
  96. if not access_token or not hmac.compare_digest(
  97. access_token.encode("utf-8"), self._token.encode("utf-8")):
  98. return None
  99. return Session(
  100. user_id="deployment-token", email="", display_name="Deployment session token",
  101. org_id="", provider=self.name,
  102. expires_at=int(time.time()) + _SESSION_HORIZON_SECONDS,
  103. access_token=access_token, refresh_token="")
  104. def refresh_session(self, *, refresh_token: str) -> Session:
  105. # The credential never rotates server-side mid-process; there is nothing to
  106. # refresh into. Any refresh attempt is a foreign cookie's — rejected.
  107. raise RefreshExpiredError("the deployment session token has no refresh token")
  108. def revoke_session(self, *, refresh_token: str) -> None:
  109. # Stateless shared credential — revocation is rotation (redeploy the secret).
  110. # Must not raise.
  111. return None
  112. # ---- Plugin entry point ----
  113. def register(ctx) -> None:
  114. """Register ``SessionTokenProvider`` when the deployment session token is provisioned
  115. and not disabled; a no-op otherwise (so the gate's fail-closed message keeps steering
  116. interactive deployments toward basic-auth / OAuth)."""
  117. global LAST_SKIP_REASON
  118. LAST_SKIP_REASON = ""
  119. kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, SessionTokenProvider, _settings)
  120. if kwargs is not None:
  121. logger.info(
  122. "%s: registered deployment session-token provider — the provisioned "
  123. "HERMES_DASHBOARD_SESSION_TOKEN authorizes the gated dashboard "
  124. "(bearer REST + /api/ws ?token=).", _TAG)