auth_oauth_pkce_plugin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """Declarative OAuth 2.0 Authorization-Code + PKCE login for out-of-tree model-provider plugins.
  2. A plugin declares endpoints and public-client metadata in :class:`OAuthPKCEConfig` and plugs the two
  3. factories into the ``ProviderProfile`` hooks::
  4. cfg = OAuthPKCEConfig(client_id="…", authorize_url="https://…", token_url="https://…", scopes=("…",))
  5. ProviderProfile(name="example", auth_type="oauth_external",
  6. auth_handler=pkce_auth_handler(cfg), refresh_credential=pkce_refresh_credential(cfg))
  7. Hermes owns the security boundary: HTTPS-only endpoints (plain HTTP only for a loopback-literal host,
  8. i.e. a local development IdP), token endpoint host checked against the same allowlist as the authorize
  9. URL BEFORE any request, S256 PKCE, CSRF ``state`` compared in constant time, an RFC 8252 loopback
  10. listener on the literal ``127.0.0.1`` (explicit port, ``0`` = OS-assigned), persistence as a
  11. ``PooledCredential`` and single-use refresh tokens re-read from the store under the auth lock. No token,
  12. ``state`` or verifier is ever logged.
  13. Lives in ``hermes_cli`` because everything it drives (loopback helpers, the auth store lock, the pool)
  14. does; every core import is deferred into the callables so a plugin may import this module while
  15. provider discovery is still running inside ``hermes_cli.auth``'s own import.
  16. """
  17. from __future__ import annotations
  18. import hmac
  19. import logging
  20. import secrets
  21. import time
  22. import uuid
  23. import webbrowser
  24. from dataclasses import dataclass, field
  25. from typing import Any, Callable, Dict, Mapping, Optional, Tuple
  26. from urllib.parse import urlencode, urlparse
  27. logger = logging.getLogger(__name__)
  28. POOL_SOURCE = "manual:loopback_pkce" # ``manual:`` prefix = never pruned by load_pool() re-seeding
  29. _LOOPBACK_LITERALS = frozenset({"127.0.0.1", "::1"})
  30. @dataclass(frozen=True)
  31. class OAuthPKCEConfig:
  32. """Public-client OAuth metadata for one provider. No client secret — PKCE is the proof."""
  33. client_id: str
  34. authorize_url: str
  35. token_url: str
  36. scopes: tuple[str, ...] = ()
  37. redirect_port: int = 0 # 0 = OS-assigned; pin it when the IdP allowlists an exact redirect URI
  38. redirect_path: str = "/callback"
  39. audience: Optional[str] = None
  40. extra_authorize_params: Mapping[str, str] = field(default_factory=dict)
  41. extra_token_params: Mapping[str, str] = field(default_factory=dict)
  42. # Hosts the token endpoint may live on; default = the authorize URL's host (and its subdomains).
  43. allowed_hosts: tuple[str, ...] = ()
  44. timeout_seconds: float = 180.0
  45. label: str = ""
  46. # Confidential client behind a broker: called with the grant fields (``grant_type``, ``code`` /
  47. # ``refresh_token``, ``redirect_uri``, ``code_verifier``) INSTEAD of POSTing ``token_url``; returns
  48. # the token-endpoint JSON or raises ``AuthError``. The broker holds the client secret, so the
  49. # plugin owns that transport and ``token_url`` is unused.
  50. token_request: Optional[Callable[[dict[str, str]], Mapping[str, Any]]] = None
  51. def _err(provider: str, message: str, code: str):
  52. from hermes_cli.auth_constants import AuthError
  53. return AuthError(f"{provider}: {message}", provider=provider, code=code)
  54. def _host_allowed(host: str, allowlist: tuple[str, ...]) -> bool:
  55. return any(host == apex or host.endswith(f".{apex}") for apex in allowlist)
  56. def _endpoint_host(provider: str, name: str, url: str) -> str:
  57. parsed = urlparse(str(url or "").strip())
  58. host = (parsed.hostname or "").lower()
  59. if not host:
  60. raise _err(provider, f"OAuth {name} has no host.", "oauth_endpoint_invalid")
  61. if parsed.scheme != "https" and not (parsed.scheme == "http" and host in _LOOPBACK_LITERALS):
  62. raise _err(provider, f"OAuth {name} must use HTTPS.", "oauth_endpoint_invalid")
  63. return host
  64. def validate_config(provider: str, cfg: OAuthPKCEConfig) -> None:
  65. """Refuse a misdeclared config before any network request (login AND refresh call this)."""
  66. if cfg.token_request is not None:
  67. return # brokered: no client or token endpoint of our own to check
  68. if not str(cfg.client_id or "").strip():
  69. raise _err(provider, "OAuth client_id is missing.", "oauth_client_id_missing")
  70. authorize_host = _endpoint_host(provider, "authorize_url", cfg.authorize_url)
  71. token_host = _endpoint_host(provider, "token_url", cfg.token_url)
  72. allowlist = tuple(h.lower() for h in cfg.allowed_hosts) or (authorize_host,)
  73. if not _host_allowed(token_host, allowlist):
  74. raise _err(provider, f"OAuth token_url host {token_host!r} is not on the allowlist "
  75. f"{sorted(allowlist)}.", "oauth_token_host_rejected")
  76. if not 0 <= int(cfg.redirect_port) <= 65535:
  77. raise _err(provider, "OAuth redirect_port must be within 0..65535.", "oauth_redirect_invalid")
  78. def _post_token(provider: str, cfg: OAuthPKCEConfig, data: dict[str, str], *, code: str) -> dict[str, Any]:
  79. """POST the token endpoint (or the plugin's broker) and return the rotated pool fields; the payload
  80. is never logged."""
  81. from hermes_cli.auth import _default_verify
  82. from hermes_cli.auth_constants import httpx
  83. if cfg.token_request is not None:
  84. return _token_fields(provider, cfg.token_request(dict(data)), data, code)
  85. body = {**cfg.extra_token_params, **data, "client_id": cfg.client_id}
  86. if cfg.audience:
  87. body.setdefault("audience", cfg.audience)
  88. try:
  89. response = httpx.post(cfg.token_url, data=body, headers={"Accept": "application/json"},
  90. timeout=30.0, verify=_default_verify())
  91. except Exception as exc:
  92. raise _err(provider, f"OAuth token request failed: {type(exc).__name__}", code) from exc
  93. if response.status_code >= 400:
  94. raise _token_http_error(provider, response, code)
  95. return _token_fields(provider, response.json(), data, code)
  96. def _token_fields(provider: str, payload: Mapping[str, Any], data: dict[str, str], code: str) -> dict[str, Any]:
  97. """Pool fields from a token-endpoint payload; a response without ``refresh_token`` keeps the old one."""
  98. from hermes_cli.auth import _coerce_ttl_seconds, _utc_now_z
  99. access_token = str(payload.get("access_token") or "").strip()
  100. if not access_token:
  101. raise _err(provider, "OAuth token response carried no access_token.", code)
  102. ttl = _coerce_ttl_seconds(payload.get("expires_in", 0))
  103. return {
  104. "access_token": access_token,
  105. "refresh_token": str(payload.get("refresh_token") or data.get("refresh_token") or "").strip() or None,
  106. "expires_at_ms": int(time.time() * 1000) + ttl * 1000 if ttl else None,
  107. "last_refresh": _utc_now_z(),
  108. }
  109. def _token_http_error(provider: str, response: Any, fallback_code: str):
  110. """Map a failed token HTTP response. A grant-dead JSON ``error`` value becomes the
  111. error's ``code`` — the pool's plugin recovery treats those codes as terminal. The
  112. response body is not logged."""
  113. from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES
  114. error = ""
  115. try:
  116. payload = response.json()
  117. if isinstance(payload, dict):
  118. error = str(payload.get("error") or "").strip()
  119. except Exception:
  120. error = ""
  121. if error in _OAUTH_GRANT_DEAD_CODES:
  122. return _err(provider, f"OAuth token request failed with HTTP {response.status_code} ({error}).", error)
  123. return _err(provider, f"OAuth token request failed with HTTP {response.status_code}.", fallback_code)
  124. def _pool_provider(args: Any) -> str:
  125. """Canonical profile name for the credential pool. ``args.provider`` may be an alias."""
  126. raw = str(getattr(args, "provider", "") or "").strip().lower()
  127. from providers import get_provider_profile
  128. profile = get_provider_profile(raw)
  129. return profile.name if profile is not None else raw
  130. def login(provider: str, cfg: OAuthPKCEConfig, *, open_browser: bool = True) -> dict[str, Any]:
  131. """Run the browser Authorization-Code + PKCE flow; returns the pool fields for the new grant."""
  132. from hermes_cli.auth_device_flow import (
  133. _bind_loopback_callback_server, _can_open_graphical_browser, _make_loopback_callback_handler,
  134. _pkce_code_challenge, _pkce_code_verifier, _print_loopback_ssh_hint, _serve_loopback_callback)
  135. validate_config(provider, cfg)
  136. path = cfg.redirect_path if cfg.redirect_path.startswith("/") else f"/{cfg.redirect_path}"
  137. err = lambda message, code: _err(provider, message, code)
  138. handler_cls, result = _make_loopback_callback_handler(path, display_name=cfg.label or provider)
  139. server = _bind_loopback_callback_server(
  140. "127.0.0.1", int(cfg.redirect_port), handler_cls, err=err, bind_failed_code="oauth_callback_bind_failed")
  141. redirect_uri = f"http://127.0.0.1:{server.server_address[1]}{path}"
  142. verifier = _pkce_code_verifier()
  143. state = secrets.token_urlsafe(32)
  144. params = {
  145. **cfg.extra_authorize_params, "client_id": cfg.client_id, "response_type": "code",
  146. "redirect_uri": redirect_uri, "state": state, "code_challenge": _pkce_code_challenge(verifier),
  147. "code_challenge_method": "S256"}
  148. if cfg.scopes:
  149. params["scope"] = " ".join(cfg.scopes)
  150. if cfg.audience:
  151. params["audience"] = cfg.audience
  152. authorize_url = f"{cfg.authorize_url}{'&' if urlparse(cfg.authorize_url).query else '?'}{urlencode(params)}"
  153. print(f"\nOpen this URL to authorize Hermes with {cfg.label or provider}:\n {authorize_url}\n")
  154. print(f"Waiting for callback on {redirect_uri} (timeout {int(cfg.timeout_seconds)}s, Ctrl+C to cancel)...")
  155. _print_loopback_ssh_hint(redirect_uri)
  156. if open_browser and _can_open_graphical_browser():
  157. try:
  158. webbrowser.open(authorize_url)
  159. except Exception:
  160. print("Could not open the browser automatically; use the URL above.")
  161. try:
  162. callback = _serve_loopback_callback(
  163. server, result, timeout_seconds=cfg.timeout_seconds, err=err, timeout_code="oauth_callback_timeout")
  164. except KeyboardInterrupt:
  165. print("\nLogin cancelled.")
  166. raise SystemExit(130)
  167. if callback.get("error"):
  168. raise err(f"authorization failed: {callback.get('error_description') or callback['error']}",
  169. "oauth_authorization_denied")
  170. if not hmac.compare_digest(str(callback.get("state") or ""), state):
  171. raise err("callback state mismatch — the redirect did not come from this login. Aborting.",
  172. "oauth_state_mismatch")
  173. code = str(callback.get("code") or "").strip()
  174. if not code:
  175. raise err("callback carried no authorization code.", "oauth_no_code")
  176. return _post_token(provider, cfg, {
  177. "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "code_verifier": verifier,
  178. }, code="oauth_token_exchange_failed")
  179. def _is_usable(access_token: Any, expires_at_ms: Any, now_ms: int) -> bool:
  180. return bool(str(access_token or "").strip()) and (expires_at_ms is None or int(expires_at_ms) > now_ms)
  181. def pkce_auth_handler(cfg: OAuthPKCEConfig) -> Callable[[str, Any], bool]:
  182. """``ProviderProfile.auth_handler`` owning add/status/logout; ``refresh`` is declined so the
  183. credential pool's generic refresh (which calls :func:`pkce_refresh_credential`) handles it."""
  184. def handler(action: str, args: Any) -> bool:
  185. from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool
  186. provider = _pool_provider(args)
  187. if action == "add":
  188. tokens = login(provider, cfg, open_browser=not getattr(args, "no_browser", False))
  189. entry = load_pool(provider).add_entry(PooledCredential(
  190. provider=provider, id=uuid.uuid4().hex[:6], label=cfg.label or provider,
  191. auth_type=AUTH_TYPE_OAUTH, priority=0, source=POOL_SOURCE, **tokens,
  192. extra={"oauth_pkce": {"client_id": cfg.client_id, "scope": " ".join(cfg.scopes)}}))
  193. print(f"Signed in to {cfg.label or provider}; credential {entry.id} added to the pool.")
  194. return True
  195. if action == "status":
  196. entries = load_pool(provider).entries()
  197. now_ms = int(time.time() * 1000)
  198. if not entries:
  199. print(f"{provider}: logged out")
  200. elif any(_is_usable(e.access_token, e.expires_at_ms, now_ms) for e in entries):
  201. print(f"{provider}: logged in\n auth_type: oauth (pkce)\n credentials: {len(entries)}")
  202. else:
  203. print(f"{provider}: expired (needs refresh) — run `hermes auth refresh {provider}`")
  204. return True
  205. if action == "logout":
  206. pool = load_pool(provider)
  207. count = len(pool.entries())
  208. for index in range(count, 0, -1):
  209. pool.remove_index(index)
  210. print(f"Logged out of {provider} ({count} credential(s) removed)")
  211. return True
  212. return False
  213. return handler
  214. def pkce_refresh_credential(cfg: OAuthPKCEConfig) -> Callable[[Any], Mapping[str, Any]]:
  215. """``ProviderProfile.refresh_credential``: rotate one pooled row via the refresh_token grant.
  216. Refresh tokens are single-use, so the store is re-read under the auth lock first: a peer that
  217. already rotated this row is adopted instead of spending its (now-revoked) refresh token again.
  218. """
  219. def refresh(entry: Any) -> Mapping[str, Any]:
  220. from hermes_cli.auth import _auth_store_lock, read_credential_pool
  221. provider = str(entry.provider)
  222. validate_config(provider, cfg)
  223. with _auth_store_lock():
  224. on_disk = next((row for row in read_credential_pool(provider)
  225. if isinstance(row, dict) and row.get("id") == entry.id), None) or {}
  226. disk_refresh = str(on_disk.get("refresh_token") or "").strip()
  227. if disk_refresh and disk_refresh != (entry.refresh_token or "") and _is_usable(
  228. on_disk.get("access_token"), on_disk.get("expires_at_ms"), int(time.time() * 1000)):
  229. logger.debug("%s entry %s: adopting a peer's rotation, refresh token not spent", provider, entry.id)
  230. return {k: on_disk.get(k) for k in ("access_token", "refresh_token", "expires_at_ms", "last_refresh")}
  231. refresh_token = disk_refresh or str(entry.refresh_token or "").strip()
  232. if not refresh_token:
  233. raise _err(provider, "no refresh_token on the pooled credential.", "oauth_refresh_no_token")
  234. data = {"grant_type": "refresh_token", "refresh_token": refresh_token}
  235. if cfg.scopes:
  236. data["scope"] = " ".join(cfg.scopes)
  237. return _post_token(provider, cfg, data, code="oauth_refresh_failed")
  238. return refresh