base.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. """Abstract base + dataclasses + exceptions for dashboard auth providers."""
  2. from __future__ import annotations
  3. from abc import ABC, abstractmethod
  4. from dataclasses import dataclass
  5. from typing import Optional
  6. @dataclass(frozen=True)
  7. class Session:
  8. """A verified interactive identity (from ``complete_login`` / ``verify_session``). All fields
  9. mandatory; providers without orgs set ``org_id=""``. The tokens are opaque to Hermes."""
  10. user_id: str
  11. email: str
  12. display_name: str
  13. org_id: str
  14. provider: str
  15. expires_at: int # unix seconds; the access_token's exp claim
  16. access_token: str
  17. refresh_token: str
  18. issuer: str = "" # Verified issuer; empty for non-federated providers.
  19. @dataclass(frozen=True)
  20. class TokenPrincipal:
  21. """A verified non-interactive (service-to-service) caller — the token analog of
  22. :class:`Session`: one bearer token on one request, no login/cookie/refresh. ``principal`` is
  23. an opaque stable caller id; ``scopes`` empty means "unscoped" (a route MAY enforce one)."""
  24. principal: str
  25. provider: str
  26. scopes: tuple[str, ...] = ()
  27. @dataclass(frozen=True)
  28. class LoginStart:
  29. """First leg of the OAuth round trip: ``redirect_url`` is the IDP's authorize endpoint;
  30. ``cookie_payload`` maps cookie name -> serialised PKCE/CSRF state that the auth route sets
  31. (HttpOnly, Secure + ``SameSite=None`` over HTTPS, TTL <= 10 min; see ``set_pkce_cookie``)."""
  32. redirect_url: str
  33. cookie_payload: dict[str, str]
  34. class ProviderError(Exception):
  35. """IDP unreachable / transient failure. Middleware -> HTTP 503."""
  36. class InvalidCodeError(Exception):
  37. """OAuth callback ``code``/``state`` failed validation. Middleware -> HTTP 400."""
  38. class InvalidCredentialsError(Exception):
  39. """Username/password rejected. The route answers a generic 401 (no username oracle)."""
  40. class RefreshExpiredError(Exception):
  41. """This provider rejects the refresh token. Not proof of ownership in a multi-provider
  42. deployment: middleware tries the rest and forces re-login only after every reachable one
  43. rejects it."""
  44. def classify_jwks_lookup_error(exc: BaseException) -> Exception:
  45. """Map a ``PyJWKClient.get_signing_key_from_jwt`` failure to the protocol. Only a genuine
  46. transport failure (``PyJWKClientConnectionError``, or an unexpected JWKS shape) is a
  47. :class:`ProviderError` (503, never forces logout). A non-JWT bearer (``DecodeError``), a JWKS
  48. with no key for this ``kid`` (``PyJWKSetError``) or any other invalid token is simply not
  49. verifiable by this provider -> :class:`InvalidCodeError` (``verify_session`` returns ``None``).
  50. Folding "cannot parse" into "cannot reach" once made every opaque bearer a fast 503.
  51. * ``jwt.DecodeError`` — the bearer is not a JWT at all (an opaque peer key, a legacy session token,
  52. garbage). #94558: hosted agents answered every non-JWT bearer with a fast 503 ``Auth provider 'nous'
  53. unreachable`` even though Portal was healthy, because "cannot parse" and "cannot reach" were folded into
  54. one branch. * ``jwt.PyJWKSetError`` — the JWKS was fetched fine but holds no key for this token's
  55. ``kid`` (rotated/foreign key).
  56. """
  57. try:
  58. import jwt
  59. except Exception: # pragma: no cover - jwt is a hard dep of these providers
  60. return ProviderError(f"JWKS lookup failed: {exc!r}")
  61. # Order matters: DecodeError/PyJWKSetError before their PyJWKClientError/InvalidTokenError
  62. # parents.
  63. if isinstance(exc, jwt.PyJWKClientConnectionError):
  64. return ProviderError(f"JWKS lookup failed: {exc}")
  65. if isinstance(exc, (jwt.DecodeError, jwt.PyJWKSetError)):
  66. return InvalidCodeError(f"token not verifiable by this provider: {exc}")
  67. if isinstance(exc, jwt.PyJWKClientError):
  68. return ProviderError(f"JWKS lookup failed: {exc}")
  69. if isinstance(exc, jwt.InvalidTokenError):
  70. return InvalidCodeError(f"token not verifiable by this provider: {exc}")
  71. return ProviderError(f"JWKS lookup failed: {exc!r}")
  72. class DashboardAuthProvider(ABC):
  73. """Protocol every dashboard-auth provider plugin implements.
  74. Lifecycle: ``start_login`` (redirect URL + PKCE state) -> IDP -> ``complete_login`` (code +
  75. verifier -> Session) -> ``verify_session`` per request -> ``refresh_session`` near expiry ->
  76. ``revoke_session`` on logout (best-effort, must not raise). Failure semantics: ``start_login``
  77. / ``complete_login`` raise ``ProviderError`` when the IDP is unreachable, ``complete_login``
  78. ``InvalidCodeError`` on a bad code/state; ``verify_session`` returns ``None`` for
  79. expired/unknown tokens (middleware refreshes) and raises ``ProviderError`` when unreachable
  80. (503); ``refresh_session`` raises ``RefreshExpiredError`` when the token is invalid for that
  81. provider (a foreign opaque token looks expired, so middleware tries the rest) and
  82. ``ProviderError`` on network failure (503, cookies kept).
  83. Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``. Capability flags:
  84. ``supports_password`` (credential form + ``complete_password_login``; OAuth methods may be
  85. ``NotImplementedError`` stubs), ``supports_token`` (``verify_token`` for the token-auth seam),
  86. ``supports_session`` (False for token-only credentials such as drain, never offered a login),
  87. ``interactive_login`` (False for a provider that verifies credentials but has no browser
  88. sign-in flow — kept out of the login page, ``/api/auth/providers`` and the auto-SSO redirect
  89. even though its ``verify_session`` is real; a session provider presenting a provisioned
  90. shared token is the bundled consumer).
  91. """
  92. name: str = ""
  93. display_name: str = ""
  94. supports_password: bool = False
  95. supports_token: bool = False
  96. supports_session: bool = True
  97. interactive_login: bool = True
  98. @abstractmethod
  99. def start_login(self, *, redirect_uri: str) -> LoginStart: ...
  100. @abstractmethod
  101. def complete_login(
  102. self, *, code: str, state: str, code_verifier: str, redirect_uri: str) -> Session: ...
  103. @abstractmethod
  104. def verify_session(self, *, access_token: str) -> Optional[Session]: ...
  105. @abstractmethod
  106. def refresh_session(self, *, refresh_token: str) -> Session: ...
  107. @abstractmethod
  108. def revoke_session(self, *, refresh_token: str) -> None: ...
  109. def complete_password_login(self, *, username: str, password: str) -> Session:
  110. """Verify a username/password pair and mint a :class:`Session` (only called when
  111. ``supports_password``). Raise ``InvalidCredentialsError`` on rejection (SHOULD be constant
  112. time for unknown users — no timing oracle) and ``ProviderError`` when the store is
  113. unreachable. The default raises so a mis-flagged provider fails loudly."""
  114. raise NotImplementedError(
  115. f"{type(self).__name__} does not support password login "
  116. "(set supports_password = True and override complete_password_login)")
  117. def verify_token(self, *, token: str) -> Optional[TokenPrincipal]:
  118. """Verify a non-interactive bearer token; return its principal. Mirrors ``verify_session``:
  119. return ``None`` (never raise) for an unrecognised token so the seam falls through; raise
  120. ``ProviderError`` ONLY for a genuine backing-store outage. Shared secrets MUST be compared
  121. with ``hmac.compare_digest``. The default raises so a mis-flagged provider fails loudly."""
  122. raise NotImplementedError(
  123. f"{type(self).__name__} does not support token auth "
  124. "(set supports_token = True and override verify_token)")
  125. def assert_protocol_compliance(cls: type) -> None:
  126. """Raise ``TypeError`` if ``cls`` doesn't fully implement the protocol (call it from every
  127. provider plugin's unit tests)."""
  128. for attr in ("name", "display_name"):
  129. if not getattr(cls, attr, ""):
  130. raise TypeError(f"{cls.__name__} missing or empty attribute: {attr!r}")
  131. for method in ("start_login", "complete_login", "verify_session", "refresh_session",
  132. "revoke_session"):
  133. if not callable(getattr(cls, method, None)):
  134. raise TypeError(f"{cls.__name__} missing method: {method}")
  135. if getattr(cls, "__abstractmethods__", None):
  136. raise TypeError(
  137. f"{cls.__name__} has unimplemented abstract methods: {sorted(cls.__abstractmethods__)}")