__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """SelfHostedOIDCProvider — generic self-hosted OpenID Connect dashboard auth.
  2. A plain OIDC Relying Party (Authentik, Keycloak, Zitadel, Authelia, Auth0, Okta, …): discovers
  3. endpoints from ``{issuer}/.well-known/openid-configuration``, builds the PKCE (S256) authorize
  4. URL, exchanges the code, and verifies the **ID token** (the access token is opaque per spec)
  5. against the discovered ``jwks_uri`` with ``iss``/``aud`` pinned. Public and confidential
  6. (``client_secret`` layered on top of PKCE, never replacing it) clients both work. Config:
  7. ``dashboard.oauth.self_hosted.{issuer,client_id,scopes,client_secret,id_token_leeway}`` or
  8. ``HERMES_DASHBOARD_OIDC_*`` (leeway is config.yaml-only; default 60s of clock-skew tolerance
  9. for the ID token's time claims, ``0`` restores strict verification).
  10. """
  11. from __future__ import annotations
  12. import base64
  13. import logging
  14. import threading
  15. import time
  16. import urllib.parse
  17. from typing import Any, Dict, Optional
  18. import httpx
  19. from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session
  20. from plugins.dashboard_auth._shared import (
  21. DEFAULT_TOKEN_LEEWAY_SECONDS,
  22. JSON_HEADERS,
  23. TOKEN_ENDPOINT_TIMEOUT_SEC as _TOKEN_ENDPOINT_TIMEOUT_SEC,
  24. JwtOAuthProvider,
  25. SkipRegistration,
  26. exchange_token,
  27. load_config_section,
  28. parse_json_body,
  29. parse_leeway,
  30. pkce_login_start,
  31. refresh_token_from,
  32. register_provider,
  33. resolve_env_or_cfg,
  34. session_from_claims,
  35. validate_redirect_uri,
  36. verify_jwt)
  37. logger = logging.getLogger(__name__)
  38. _TAG = "dashboard-auth-self-hosted"
  39. # ``openid`` is mandatory (no ID token without it); profile/email populate display_name/email.
  40. _DEFAULT_SCOPES = "openid profile email"
  41. # RS256 is the OIDC default; ES256 is common on modern IDPs (Zitadel, newer Keycloak).
  42. # HS256 is deliberately excluded: it implies a shared secret we don't hold in the
  43. # public-client model and is a JWT algorithm-confusion footgun.
  44. _ALLOWED_ID_TOKEN_ALGS = ("RS256", "ES256", "RS384", "RS512", "ES384", "ES512")
  45. _DISCOVERY_TIMEOUT_SEC = 10.0
  46. # Discovery is effectively static; a soft TTL lets a long-running dashboard
  47. # pick up an IDP endpoint migration within the hour.
  48. _DISCOVERY_CACHE_TTL_SEC = 3600
  49. LAST_SKIP_REASON: str = ""
  50. def _require_https_or_loopback(url: str, *, field: str) -> str:
  51. """Reject non-HTTPS endpoint URLs (loopback http allowed) so a misconfigured
  52. issuer can't ship auth codes / refresh tokens in cleartext."""
  53. parsed = urllib.parse.urlparse(url)
  54. if parsed.scheme == "https" or (parsed.scheme == "http" and (parsed.hostname or "") in ("localhost", "127.0.0.1", "::1")):
  55. return url
  56. raise ProviderError(f"OIDC {field} must be https:// (or http on localhost), got {url!r}")
  57. def _origin(url: str) -> tuple:
  58. """``(scheme, hostname, port)`` for an origin compare, with default ports
  59. normalised so ``https://h`` and ``https://h:443`` are the same origin."""
  60. parts = urllib.parse.urlparse(url)
  61. scheme = parts.scheme.lower()
  62. return (scheme, (parts.hostname or "").lower(),
  63. parts.port or {"https": 443, "http": 80}.get(scheme))
  64. class SelfHostedOIDCProvider(JwtOAuthProvider):
  65. """Generic self-hosted OpenID Connect provider (authorization-code + PKCE)."""
  66. name = "self-hosted"
  67. display_name = "Self-Hosted OIDC"
  68. # Class-level default so partially-constructed instances (object.__new__ in
  69. # tests) still verify with the standard clock-skew leeway.
  70. _id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS
  71. def __init__(
  72. self, *, issuer: str, client_id: str, scopes: str = _DEFAULT_SCOPES, client_secret: str = "",
  73. id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS,
  74. ) -> None:
  75. if not issuer:
  76. raise ValueError("issuer is required")
  77. if not client_id:
  78. raise ValueError("client_id is required")
  79. # Trailing slash normalised for stable compares; ``iss`` is pinned against the
  80. # *discovered* issuer so a config/IDP slash mismatch is tolerated.
  81. self._issuer = issuer.rstrip("/")
  82. _require_https_or_loopback(self._issuer, field="issuer")
  83. self._client_id = client_id
  84. self._scopes = scopes.strip() or _DEFAULT_SCOPES
  85. # Clock-skew tolerance (seconds) for the ID token's exp/nbf/iat claims;
  86. # the default absorbs unsynced-IDP skew (#47815), 0 restores strict mode.
  87. self._id_token_leeway = parse_leeway(id_token_leeway)
  88. # Empty/whitespace secret ⇒ public client, so a provisioned-but-blank secret
  89. # can't flip us into a broken confidential mode.
  90. self._client_secret = (client_secret or "").strip()
  91. # Discovery + JWKS resolve lazily so registration never hits the network
  92. # (the IDP may be down at boot; fail per-request instead).
  93. self._discovery: dict[str, Any] | None = None
  94. self._discovery_fetched_at: float = 0.0
  95. self._discovery_lock = threading.Lock()
  96. self._jwks_client: Any = None
  97. def start_login(self, *, redirect_uri: str) -> LoginStart:
  98. # Validate the redirect before discovery so a bad redirect_uri surfaces even when the IDP is unreachable.
  99. validate_redirect_uri(redirect_uri)
  100. disco = self._get_discovery()
  101. return pkce_login_start(
  102. disco["authorization_endpoint"], client_id=self._client_id, scope=self._scopes, redirect_uri=redirect_uri)
  103. def revoke_session(self, *, refresh_token: str) -> None:
  104. # Best-effort RFC 7009 revocation when the IDP advertises an endpoint.
  105. # Must never raise — logout is client-side cookie clearing regardless.
  106. if not refresh_token:
  107. return
  108. try:
  109. disco = self._get_discovery()
  110. except ProviderError:
  111. return
  112. endpoint = str(disco.get("revocation_endpoint") or "").strip()
  113. if not endpoint:
  114. return
  115. # Confidential clients must authenticate on revocation too (RFC 7009 §2.1).
  116. extra_data, extra_headers = self._token_endpoint_auth(disco)
  117. data = {"token": refresh_token, "token_type_hint": "refresh_token", "client_id": self._client_id, **extra_data}
  118. try:
  119. httpx.post(endpoint, data=data, headers={**JSON_HEADERS, **extra_headers}, timeout=_TOKEN_ENDPOINT_TIMEOUT_SEC)
  120. except Exception as exc:
  121. logger.debug("self-hosted OIDC: revoke failed (ignored): %s", exc)
  122. return
  123. # ---- JwtOAuthProvider hooks: token exchange ---------------------------
  124. def _token_endpoint_auth(self, disco: dict[str, Any]) -> tuple[dict[str, str], dict[str, str]]:
  125. """``(extra_data, extra_headers)`` for token-endpoint client auth. Public client →
  126. ``({}, {})`` (PKCE alone). Confidential client → ``client_secret_post`` when the IDP
  127. advertises it *without* ``client_secret_basic``, else HTTP Basic (the OIDC default
  128. and the fallback when nothing is advertised). RFC 6749 §2.3.1."""
  129. if not self._client_secret:
  130. return {}, {}
  131. methods = disco.get("token_endpoint_auth_methods_supported") or []
  132. if "client_secret_post" in methods and "client_secret_basic" not in methods:
  133. return {"client_secret": self._client_secret}, {}
  134. # Both halves must be form-url-encoded *before* base64 (RFC 6749 §2.3.1) or a
  135. # secret containing ':' / reserved chars corrupts the header.
  136. userpass = f"{urllib.parse.quote(self._client_id, safe='')}:{urllib.parse.quote(self._client_secret, safe='')}"
  137. return {}, {"Authorization": f"Basic {base64.b64encode(userpass.encode('utf-8')).decode('ascii')}"}
  138. def _refresh_request(self, refresh_token: str) -> tuple[dict[str, str], Optional[dict[str, str]]]:
  139. # Re-request the same scopes so the rotated ID token keeps its identity claims
  140. # (some IDPs narrow scope on refresh otherwise).
  141. return (
  142. {"grant_type": "refresh_token", "client_id": self._client_id, "refresh_token": refresh_token,
  143. "scope": self._scopes},
  144. None)
  145. def _grant(
  146. self, data: dict[str, str], *, bad_request_exc: type[Exception], headers: Optional[dict[str, str]] = None,
  147. previous_refresh_token: str = "",
  148. ) -> Session:
  149. """POST the discovered token endpoint and turn the response into a Session.
  150. Confidential-client auth (body field or Basic header) is added for both grants —
  151. the IDP rejects an unauthenticated refresh with ``invalid_client``."""
  152. disco = self._get_discovery()
  153. extra_data, extra_headers = self._token_endpoint_auth(disco)
  154. id_token, payload = exchange_token(
  155. disco["token_endpoint"], {**data, **extra_data}, headers=extra_headers, bad_request_exc=bad_request_exc,
  156. idp="IDP", endpoint="OIDC token endpoint", token_key="id_token",
  157. missing_msg=(
  158. "OIDC token response missing id_token — ensure the 'openid' "
  159. "scope is configured and the client is allowed to receive an "
  160. "ID token."))
  161. claims = self._verify_id_token(id_token)
  162. # Prefer a freshly-issued RT, else keep the previous (some IDPs don't rotate).
  163. return self._session(id_token, refresh_token_from(payload, previous_refresh_token), claims)
  164. # ---- internals: discovery ---------------------------------------------
  165. def _fresh_discovery(self) -> dict[str, Any] | None:
  166. if self._discovery is not None and time.time() - self._discovery_fetched_at < _DISCOVERY_CACHE_TTL_SEC:
  167. return self._discovery
  168. return None
  169. def _get_discovery(self) -> dict[str, Any]:
  170. """Return the cached OIDC discovery document, fetching if stale (double-checked lock)."""
  171. disco = self._fresh_discovery()
  172. if disco is None:
  173. with self._discovery_lock:
  174. disco = self._fresh_discovery()
  175. if disco is None:
  176. disco = self._discovery = self._fetch_discovery()
  177. self._discovery_fetched_at = time.time()
  178. self._jwks_client = None # new issuer/keys → rebind the JWKS client to the fresh jwks_uri
  179. return disco
  180. def _fetch_discovery(self) -> dict[str, Any]:
  181. url = f"{self._issuer}/.well-known/openid-configuration"
  182. try:
  183. # follow_redirects=True: many IDPs answer discovery with a 3xx (Authentik
  184. # canonicalises .well-known; proxies upgrade http→https) and httpx defaults to
  185. # not following. The token/revocation POSTs deliberately do NOT follow
  186. # redirects (they carry an auth code / refresh token).
  187. response = httpx.get(url, headers=JSON_HEADERS, timeout=_DISCOVERY_TIMEOUT_SEC, follow_redirects=True)
  188. except httpx.RequestError as exc:
  189. raise ProviderError(f"OIDC discovery unreachable: {exc}") from exc
  190. if response.status_code != 200:
  191. raise ProviderError(f"OIDC discovery returned {response.status_code} for {url!r}")
  192. # Resolved-origin pin: the document only counts as the IDP's when the url that
  193. # actually served it shares the configured issuer's origin. The ``issuer`` field
  194. # inside the body is attacker-controlled content and cannot prove where the
  195. # document came from — a single cleartext or attacker-hosted redirect hop could
  196. # otherwise serve a forged document asserting the configured issuer with
  197. # attacker jwks_uri / token_endpoint.
  198. if _origin(str(response.url)) != _origin(self._issuer):
  199. raise ProviderError(
  200. f"OIDC discovery resolved to {response.url}, outside the configured "
  201. f"issuer's origin ({self._issuer!r})")
  202. payload = parse_json_body(response)
  203. if not payload:
  204. raise ProviderError("OIDC discovery returned a non-JSON body")
  205. def field(key: str) -> str:
  206. return str(payload.get(key, "") or "").strip()
  207. endpoints = {k: field(k) for k in ("authorization_endpoint", "token_endpoint", "jwks_uri")}
  208. if not all(endpoints.values()):
  209. raise ProviderError("OIDC discovery missing one of authorization_endpoint / token_endpoint / jwks_uri")
  210. # Issuer pin: a mismatch means the document came from the wrong place
  211. # (proxy/MITM/misconfig). Only a trailing-slash difference is tolerated.
  212. advertised_issuer = field("issuer")
  213. if advertised_issuer and advertised_issuer.rstrip("/") != self._issuer:
  214. raise ProviderError(
  215. f"OIDC discovery issuer mismatch: document advertises {advertised_issuer!r} "
  216. f"but configured issuer is {self._issuer!r}")
  217. for key, url in endpoints.items():
  218. _require_https_or_loopback(url, field=key)
  219. # Absent/garbage auth-methods → [] → OIDC default (basic) applies.
  220. auth_methods_raw = payload.get("token_endpoint_auth_methods_supported")
  221. return {
  222. "issuer": advertised_issuer or self._issuer,
  223. **endpoints,
  224. "revocation_endpoint": field("revocation_endpoint"),
  225. "token_endpoint_auth_methods_supported": (
  226. [str(m) for m in auth_methods_raw] if isinstance(auth_methods_raw, list) else [])}
  227. # ---- JwtOAuthProvider hooks: verification + mapping -------------------
  228. def _jwks_uri(self) -> str:
  229. return self._get_discovery()["jwks_uri"]
  230. def _verify_id_token(self, id_token: str) -> dict[str, Any]:
  231. issuer = self._get_discovery()["issuer"]
  232. return verify_jwt(
  233. id_token, self._get_jwks_client(), algorithms=list(_ALLOWED_ID_TOKEN_ALGS),
  234. audience=self._client_id, issuer=issuer, label="ID token", leeway=self._id_token_leeway)
  235. _claims_for = _verify_id_token
  236. def _session(self, id_token: str, refresh_token: str, claims: dict[str, Any]) -> Session:
  237. """Map verified OIDC claims onto a Session. The verified ID token is stored in
  238. ``Session.access_token`` so the per-request ``verify_session`` re-verifies a real
  239. JWT; the opaque OAuth access token is not kept — the dashboard only needs identity."""
  240. email = str(claims.get("email", "") or "")
  241. # Org/tenant is non-standard: accept common spellings, else join ``groups`` so
  242. # multi-tenant IDPs surface *something* (free-form string).
  243. org_id = claims.get("org_id") or claims.get("organization") or ""
  244. groups = claims.get("groups")
  245. if not org_id and isinstance(groups, list) and groups:
  246. org_id = ",".join(str(g) for g in groups)
  247. return session_from_claims(
  248. self.name, claims, access_token=id_token, refresh_token=refresh_token, label="ID token", email=email,
  249. display_name=str(claims.get("name") or claims.get("preferred_username") or claims.get("nickname") or email or ""),
  250. org_id=str(org_id or ""))
  251. # ---- Plugin entry point ----
  252. def _load_config_oauth_section() -> dict:
  253. return load_config_section(logger, _TAG, "dashboard", "oauth", "self_hosted")
  254. def _settings() -> dict:
  255. """Resolve SelfHostedOIDCProvider kwargs; the skip reason names BOTH configuration surfaces."""
  256. oidc_cfg = _load_config_oauth_section()
  257. def setting(env_name: str, cfg_key: str) -> str:
  258. return resolve_env_or_cfg(env_name, oidc_cfg.get(cfg_key))
  259. issuer = setting("HERMES_DASHBOARD_OIDC_ISSUER", "issuer")
  260. client_id = setting("HERMES_DASHBOARD_OIDC_CLIENT_ID", "client_id")
  261. if not issuer or not client_id:
  262. raise SkipRegistration(
  263. "Self-hosted OIDC dashboard auth is not configured. Set both an issuer and "
  264. "a client_id — either as env vars (HERMES_DASHBOARD_OIDC_ISSUER + "
  265. "HERMES_DASHBOARD_OIDC_CLIENT_ID) or under "
  266. "dashboard.oauth.self_hosted.{issuer,client_id} in config.yaml — or pass "
  267. f"--insecure to skip the OAuth gate entirely. (issuer set: {bool(issuer)}; client_id set: {bool(client_id)})")
  268. return {
  269. "issuer": issuer, "client_id": client_id,
  270. "scopes": setting("HERMES_DASHBOARD_OIDC_SCOPES", "scopes") or _DEFAULT_SCOPES,
  271. # Credential: canonical home is the env var / ~/.hermes/.env. Empty ⇒ public client.
  272. "client_secret": setting("HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "client_secret"),
  273. # Clock-skew tolerance for ID-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).
  274. "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway"))}
  275. def register(ctx) -> None:
  276. """Register :class:`SelfHostedOIDCProvider` when issuer + client_id are set."""
  277. global LAST_SKIP_REASON
  278. LAST_SKIP_REASON = ""
  279. kw, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, SelfHostedOIDCProvider, _settings)
  280. if kw is not None:
  281. logger.info(
  282. "dashboard-auth-self-hosted: registered provider "
  283. "(issuer=%s, client_id=%s, scopes=%r, confidential=%s, id_token_leeway=%ss)",
  284. kw["issuer"], kw["client_id"], kw["scopes"], bool(kw["client_secret"]), kw["id_token_leeway"]) # never log the secret itself