plugin_oauth.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. """OAuth clients a plugin declares in ``plugin.yaml``: Hermes signs in, stores and refreshes the grant.
  2. A plugin that calls a third-party API with the user's own OAuth client (a Google Cloud client, for example)
  3. declares it under ``oauth:``. ``hermes auth add <plugin>:<id>`` runs the PKCE login of
  4. :mod:`hermes_cli.auth_oauth_pkce_plugin` in a terminal, the grant lives in the active profile's
  5. ``auth.json`` (section ``plugin_oauth``) and Hermes refreshes it. The plugin calls
  6. ``credentialed_provider_request(<id>, ...)``: Hermes attaches the bearer for the declared hosts only, so
  7. the plugin never holds a token (#139077; the same contract as the Codex lane, #136117).
  8. Each grant remembers a fingerprint of the ``oauth:`` entry it was made for. A later version of the plugin
  9. that changes the token URL, hosts, scopes or client variables gets ``ProviderNotSignedIn`` until the user
  10. signs in again: the grant is used only for what the user consented to. Like capabilities, this is
  11. consent and visibility, not a sandbox.
  12. """
  13. from __future__ import annotations
  14. import hashlib
  15. import json
  16. import re
  17. import time
  18. from dataclasses import asdict, dataclass
  19. from datetime import UTC, datetime
  20. from pathlib import Path
  21. from typing import Any, Callable, Mapping, Optional
  22. from urllib.parse import urlparse
  23. _SECTION = "plugin_oauth"
  24. _EXPIRY_MARGIN_MS = 120_000 # refresh this long before expiry, as the credential pool does
  25. _TOKEN_TIMEOUT = 10.0 # below AUTH_LOCK_TIMEOUT_SECONDS: a peer waiting for the refresh lock outlives the POST
  26. _CLIENT_ERROR_CODES = frozenset({"invalid_client", "unauthorized_client", "invalid_scope"})
  27. _ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
  28. _ENV_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
  29. # Lowercase DNS name with at least one dot whose last label starts with a letter: no IP literal, port or scheme.
  30. _HOST_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z](?:[a-z0-9-]*[a-z0-9])?$")
  31. @dataclass(frozen=True)
  32. class OAuthClient:
  33. """One ``oauth:`` entry of a plugin manifest. Holds variable names, never their values."""
  34. id: str
  35. authorize_url: str
  36. token_url: str
  37. scopes: tuple[str, ...]
  38. client_id_env: str
  39. hosts: tuple[str, ...]
  40. client_secret_env: str = ""
  41. authorize_params: tuple[tuple[str, str], ...] = ()
  42. @property
  43. def fingerprint(self) -> str:
  44. """Hash of every field: a grant is used only with the entry it was made for."""
  45. return hashlib.sha256(json.dumps(asdict(self), sort_keys=True).encode("utf-8")).hexdigest()
  46. # ── Manifest ───────────────────────────────────────────────────────────────────────────────────────
  47. def _parse_url(url: Any):
  48. """``urlparse`` of *url*; None for a non-string or a URL it cannot read (bad IPv6 literal or port)."""
  49. if not isinstance(url, str):
  50. return None
  51. try:
  52. parsed = urlparse(url)
  53. _ = parsed.port # urlparse checks the port only when it is read
  54. except ValueError:
  55. return None
  56. return parsed
  57. def _url_problems(where: str, url: Any) -> list[str]:
  58. parsed = _parse_url(url)
  59. if (parsed is None or not parsed.hostname or parsed.username is not None or parsed.password is not None
  60. or parsed.fragment):
  61. return [f"{where}: must be an absolute URL without user info or fragment"]
  62. if parsed.scheme != "https": # no loopback exception: the code, refresh token and client secret travel here
  63. return [f"{where}: must use https"]
  64. return []
  65. def _hermes_owned_env(name: str) -> bool:
  66. """A variable Hermes itself reads (a provider key, a platform secret): never a plugin's client variable,
  67. or a manifest could have Hermes POST that secret to the token URL it names."""
  68. from hermes_cli.auth import PROVIDER_REGISTRY
  69. from hermes_cli.config_env_routing import is_registered_env_name
  70. return is_registered_env_name(name) or any(name in p.api_key_env_vars for p in PROVIDER_REGISTRY.values())
  71. def _entry_problems(entry: dict, where: str) -> list[str]:
  72. oauth_id = entry.get("id")
  73. problems = [] if isinstance(oauth_id, str) and _ID_RE.match(oauth_id) else [
  74. f"{where}.id: {entry.get('id')!r} must be lowercase letters, digits and dashes"]
  75. for field in ("authorize_url", "token_url"):
  76. problems += _url_problems(f"{where}.{field}", entry.get(field))
  77. scopes = entry.get("scopes")
  78. if not (isinstance(scopes, list) and scopes and all(isinstance(s, str) and s.strip() for s in scopes)):
  79. problems.append(f"{where}.scopes: must be a non-empty list of scope strings")
  80. for field, required in (("client_id_env", True), ("client_secret_env", False)):
  81. name = entry.get(field)
  82. if (required or name) and not (isinstance(name, str) and _ENV_RE.match(name)):
  83. problems.append(f"{where}.{field}: {name!r} must be an UPPER_SNAKE environment variable name")
  84. elif name and _hermes_owned_env(name):
  85. problems.append(f"{where}.{field}: {name} is a variable Hermes uses itself; declare the plugin's own")
  86. hosts = entry.get("hosts")
  87. if not (isinstance(hosts, list) and hosts and all(isinstance(h, str) and _HOST_RE.match(h) for h in hosts)):
  88. problems.append(f"{where}.hosts: must list lowercase DNS host names (no scheme, port, path or IP address)")
  89. params = entry.get("authorize_params") or {}
  90. if not (isinstance(params, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in params.items())):
  91. problems.append(f"{where}.authorize_params: must map strings to strings")
  92. return problems
  93. def _client(entry: dict) -> OAuthClient:
  94. return OAuthClient(
  95. id=entry["id"], authorize_url=entry["authorize_url"], token_url=entry["token_url"],
  96. scopes=tuple(entry["scopes"]), client_id_env=entry["client_id_env"], hosts=tuple(entry["hosts"]),
  97. client_secret_env=entry.get("client_secret_env") or "",
  98. authorize_params=tuple(sorted((entry.get("authorize_params") or {}).items())))
  99. def parse_oauth_clients(manifest: Mapping[str, Any]) -> tuple[list[OAuthClient], list[str]]:
  100. """``oauth:`` from a manifest dict: the well-formed clients, and one problem string per defect."""
  101. raw = (manifest or {}).get("oauth")
  102. if raw is None or raw == []:
  103. return [], []
  104. if not isinstance(raw, list):
  105. return [], ["oauth: must be a list of client entries"]
  106. clients: list[OAuthClient] = []
  107. problems: list[str] = []
  108. for index, entry in enumerate(raw):
  109. where = f"oauth[{index}]"
  110. entry_problems = _entry_problems(entry, where) if isinstance(entry, dict) else [f"{where}: must be a mapping"]
  111. if not entry_problems and any(c.id == entry["id"] for c in clients):
  112. entry_problems = [f"{where}.id: {entry['id']!r} is declared twice"]
  113. problems += entry_problems
  114. if not entry_problems:
  115. clients.append(_client(entry))
  116. return clients, problems
  117. def _declared_clients(plugin_dir: Path) -> list[OAuthClient]:
  118. """The plugin's own ``oauth:`` clients; a malformed block fails loud instead of reading as undeclared."""
  119. from pm.plugin_declarations import native_manifest_file, read_native_manifest
  120. manifest_file = native_manifest_file(plugin_dir)
  121. clients, problems = parse_oauth_clients(read_native_manifest(manifest_file) if manifest_file else {})
  122. if problems:
  123. raise ValueError(f"Plugin '{plugin_dir.name}' has an invalid oauth: block in plugin.yaml: " + "; ".join(problems))
  124. return clients
  125. def plugin_key(plugin_dir: Path) -> str:
  126. """The plugin's key under the plugins root it lives in (``voice``, ``web/exa``); grants are stored by it."""
  127. from hermes_cli.plugin_provider_requests import _plugin_roots
  128. for path in (plugin_dir.absolute(), plugin_dir.resolve()):
  129. for root in _plugin_roots():
  130. if path != root and path.is_relative_to(root):
  131. return path.relative_to(root).as_posix()
  132. return plugin_dir.name
  133. def _idp_hosts(client: OAuthClient) -> str:
  134. return ", ".join(dict.fromkeys(urlparse(url).hostname for url in (client.authorize_url, client.token_url)))
  135. def oauth_notice(manifest: Mapping[str, Any]) -> str:
  136. """Install/show text for the declared clients; empty when the plugin declares none."""
  137. name = str((manifest or {}).get("name") or "<plugin>")
  138. return "; ".join(
  139. f"Signs in to {c.id} at {_idp_hosts(c)} for {', '.join(c.hosts)} with `hermes auth add {name}:{c.id}` "
  140. "(Hermes stores and refreshes the token; the plugin never receives it)"
  141. for c in parse_oauth_clients(manifest)[0])
  142. def oauth_surface(manifest: Mapping[str, Any]) -> set[str]:
  143. """One line per client for the re-pin consent delta: a new entry, or a changed authorize host, token host,
  144. hosts or scopes, shows up as added. Any other change only alters the fingerprint, so the user signs in again."""
  145. lines: set[str] = set()
  146. for c in parse_oauth_clients(manifest)[0]:
  147. lines.add(f"{c.id} ({_idp_hosts(c)} -> {', '.join(c.hosts)}; {' '.join(c.scopes)})")
  148. return lines
  149. def _declared_env_names(manifest: Mapping[str, Any]) -> set[str]:
  150. names: set[str] = set()
  151. for field in ("requires_env", "optional_env"):
  152. for entry in manifest.get(field) or []:
  153. names.add(str(entry.get("name") if isinstance(entry, dict) else entry))
  154. return names
  155. def oauth_admission_problems(manifest: Mapping[str, Any], plugin_dir: Path) -> list[str]:
  156. """Catalog admission on top of the shape: declared variables, no clash with core sign-ins or ``custom:``."""
  157. from hermes_cli.plugin_provider_requests import _PROVIDERS
  158. clients, problems = parse_oauth_clients(manifest)
  159. declared = _declared_env_names(manifest)
  160. for client in clients:
  161. if client.id in _PROVIDERS:
  162. problems.append(f"oauth id {client.id!r} is a Hermes sign-in provider; pick another id")
  163. for name in filter(None, (client.client_id_env, client.client_secret_env)):
  164. if name not in declared:
  165. problems.append(f"oauth {client.id!r}: {name} must be declared under requires_env or optional_env")
  166. if clients and plugin_dir.name == "custom":
  167. problems.append("a plugin named 'custom' cannot declare oauth: `hermes auth add custom:<name>` is a custom provider")
  168. return problems
  169. def _parent(host: str) -> str:
  170. """Registered domain, roughly: ``vendor.co.uk`` keeps three labels (no public-suffix list in core)."""
  171. labels = host.split(".")
  172. keep = 3 if len(labels) > 2 and len(labels[-1]) == 2 and len(labels[-2]) <= 3 else 2
  173. return ".".join(labels[-keep:])
  174. def oauth_admission_warnings(manifest: Mapping[str, Any], plugin_dir: Path) -> list[str]:
  175. """Reviewer warnings: a host outside the sign-in provider's domains (does the IdP own it?), and plugin
  176. code that names a declared token URL (Hermes refreshes the grant)."""
  177. clients = parse_oauth_clients(manifest)[0]
  178. warnings = [f"oauth {c.id!r}: host {host} shares no domain with {_idp_hosts(c)}; check the provider owns it"
  179. for c in clients for host in c.hosts
  180. if _parent(host) not in {_parent(urlparse(u).hostname or "") for u in (c.authorize_url, c.token_url)}]
  181. urls = sorted({c.token_url for c in clients})
  182. for path in sorted(plugin_dir.rglob("*.py")):
  183. try:
  184. text = path.read_text(encoding="utf-8-sig", errors="replace")
  185. except OSError:
  186. continue
  187. warnings += [f"oauth: {path.relative_to(plugin_dir).as_posix()} names the token URL {url}; Hermes "
  188. "refreshes the grant, so the plugin should not call it" for url in urls if url in text]
  189. return warnings
  190. # ── Grant store: section ``plugin_oauth`` of the active profile's auth.json ────────────────────────
  191. def _read_grant(key: str) -> Optional[dict]:
  192. from hermes_cli.auth import _load_auth_store
  193. section = _load_auth_store().get(_SECTION)
  194. row = section.get(key) if isinstance(section, dict) else None
  195. return dict(row) if isinstance(row, dict) else None
  196. def forget_plugin_grants(plugin: str) -> None:
  197. """Drop every grant of plugin key *plugin* from the active profile (``hermes plugins remove``)."""
  198. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
  199. with _auth_store_lock():
  200. store = _load_auth_store()
  201. section = store.get(_SECTION)
  202. stale = [k for k in section if k.rsplit(":", 1)[0] == plugin] if isinstance(section, dict) else []
  203. if stale:
  204. for key in stale:
  205. section.pop(key)
  206. _save_auth_store(store)
  207. def _write_grant(key: str, row: Optional[dict]) -> None:
  208. """Replace one grant (``None`` removes it) under the auth-store lock; other sections stay as they are."""
  209. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _store_section
  210. with _auth_store_lock():
  211. store = _load_auth_store()
  212. section = _store_section(store, _SECTION)
  213. if row is None:
  214. section.pop(key, None)
  215. else:
  216. section[key] = row
  217. _save_auth_store(store)
  218. # ── Token endpoint ─────────────────────────────────────────────────────────────────────────────────
  219. def _auth_error(key: str, message: str, code: str):
  220. from hermes_cli.auth_constants import AuthError
  221. return AuthError(f"{key}: {message}", provider=key, code=code)
  222. def _env(name: str, code: str, key: str) -> str:
  223. from agent.secret_scope import get_secret
  224. value = str(get_secret(name) or "").strip()
  225. if not value:
  226. raise _auth_error(key, f"{name} is not set. Add it to this profile's .env (the plugin declares it).", code)
  227. return value
  228. def _json_object(response: Any) -> dict:
  229. try:
  230. payload = response.json()
  231. except ValueError:
  232. return {}
  233. return payload if isinstance(payload, dict) else {}
  234. def _token_error(key: str, status: int, payload: Mapping[str, Any]):
  235. """Keep the OAuth ``error`` code a caller can act on; never echo the response body."""
  236. from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES
  237. error = str(payload.get("error") or "").strip()
  238. if error in _OAUTH_GRANT_DEAD_CODES or error in _CLIENT_ERROR_CODES:
  239. return _auth_error(key, f"the token endpoint refused the request (HTTP {status}, {error}).", error)
  240. return _auth_error(key, f"the token endpoint failed with HTTP {status}.", "oauth_refresh_failed")
  241. def _require_granted_scopes(client: OAuthClient, payload: Mapping[str, Any], key: str) -> None:
  242. granted = payload.get("scope")
  243. if not isinstance(granted, str) or not granted.strip():
  244. return # the IdP did not say which scopes it granted
  245. missing = [scope for scope in client.scopes if scope not in granted.split()]
  246. if missing:
  247. raise _auth_error(key, "not every permission was granted, so nothing was saved. Missing: "
  248. + ", ".join(missing), "oauth_scope_not_granted")
  249. def _token_request(client: OAuthClient, key: str) -> Callable[[dict[str, str]], Mapping[str, Any]]:
  250. """``OAuthPKCEConfig.token_request``: the client credentials are read right before each POST, so the
  251. secret never sits in the frozen config, whose repr would show it."""
  252. def post(fields: dict[str, str]) -> Mapping[str, Any]:
  253. from hermes_cli.auth import _default_verify
  254. from hermes_cli.auth_constants import httpx
  255. form = {**fields, "client_id": _env(client.client_id_env, "oauth_client_id_missing", key)}
  256. if client.client_secret_env:
  257. form["client_secret"] = _env(client.client_secret_env, "oauth_client_secret_missing", key)
  258. failure = ""
  259. try:
  260. response = httpx.post(client.token_url, data=form, headers={"Accept": "application/json"},
  261. timeout=_TOKEN_TIMEOUT, verify=_default_verify(), follow_redirects=False)
  262. except httpx.HTTPError as exc:
  263. failure = type(exc).__name__
  264. if failure: # raised outside the handler: httpx's error keeps the request, whose body holds the secrets
  265. raise _auth_error(key, f"the token request failed ({failure}).", "oauth_refresh_failed")
  266. payload = _json_object(response)
  267. if not 200 <= response.status_code < 300: # a redirect is a failure too: it is never followed
  268. raise _token_error(key, response.status_code, payload)
  269. if fields.get("grant_type") == "authorization_code":
  270. _require_granted_scopes(client, payload, key)
  271. return payload
  272. return post
  273. def _pkce_config(client: OAuthClient, key: str, *, timeout: Optional[float] = None):
  274. from hermes_cli.auth_oauth_pkce_plugin import OAuthPKCEConfig
  275. return OAuthPKCEConfig(
  276. client_id=_env(client.client_id_env, "oauth_client_id_missing", key), authorize_url=client.authorize_url,
  277. token_url=client.token_url, scopes=client.scopes, extra_authorize_params=dict(client.authorize_params),
  278. label=key, token_request=_token_request(client, key), timeout_seconds=timeout or 180.0)
  279. # ── Bearer for credentialed_provider_request ───────────────────────────────────────────────────────
  280. def _not_signed_in(message: str):
  281. from hermes_cli.plugin_provider_requests import ProviderNotSignedIn
  282. return ProviderNotSignedIn(message)
  283. def _revoked(client: OAuthClient, key: str, code: str):
  284. return _not_signed_in(f"The {client.id} sign-in for plugin '{key.rsplit(':', 1)[0]}' was revoked ({code}). "
  285. f"Run `hermes auth add {key}` to sign in again.")
  286. def _usable_grant(row: Optional[dict], client: OAuthClient, key: str) -> dict:
  287. plugin = key.rsplit(":", 1)[0]
  288. if row is None:
  289. raise _not_signed_in(f"Not signed in to {client.id} for plugin '{plugin}' in this Hermes profile. "
  290. f"Run `hermes auth add {key}`.")
  291. if row.get("dead"):
  292. raise _revoked(client, key, str(row["dead"]))
  293. if row.get("fingerprint") != client.fingerprint:
  294. raise _not_signed_in(f"Plugin '{plugin}' changed its oauth entry '{client.id}' since you signed in. "
  295. f"Run `hermes auth add {key}` to sign in again.")
  296. return row
  297. def _live_token(row: Mapping[str, Any]) -> str:
  298. token = str(row.get("access_token") or "")
  299. expires = row.get("expires_at_ms")
  300. live = expires is None or int(expires) > int(time.time() * 1000) + _EXPIRY_MARGIN_MS
  301. return token if token and live else ""
  302. def _refresh(client: OAuthClient, key: str, row: dict) -> str:
  303. """Rotate the grant; the caller holds the auth-store lock, so a peer process waits instead of spending
  304. the same refresh token, and a logout cannot be undone by a refresh in flight."""
  305. from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES
  306. from hermes_cli.auth_constants import AuthError
  307. from hermes_cli.auth_oauth_pkce_plugin import _post_token
  308. refresh_token = str(row.get("refresh_token") or "")
  309. if not refresh_token:
  310. raise _revoked(client, key, "no_refresh_token")
  311. try:
  312. fields = _post_token(key, _pkce_config(client, key),
  313. {"grant_type": "refresh_token", "refresh_token": refresh_token}, code="oauth_refresh_failed")
  314. except AuthError as exc:
  315. if exc.code in _OAUTH_GRANT_DEAD_CODES:
  316. _write_grant(key, {"dead": exc.code, "fingerprint": row.get("fingerprint")}) # keep no dead tokens
  317. raise _revoked(client, key, str(exc.code)) from None
  318. raise
  319. _write_grant(key, {**row, **fields})
  320. return str(fields["access_token"])
  321. def _bearer(plugin_dir: Path, client: OAuthClient) -> str:
  322. """A live access token for the plugin's grant. Reading takes no lock (writes are atomic); a refresh
  323. re-reads under the lock, because a peer may have rotated the grant meanwhile."""
  324. from hermes_cli.auth import _auth_store_lock
  325. key = f"{plugin_key(plugin_dir)}:{client.id}"
  326. token = _live_token(_usable_grant(_read_grant(key), client, key))
  327. if token:
  328. return token
  329. with _auth_store_lock():
  330. row = _usable_grant(_read_grant(key), client, key)
  331. return _live_token(row) or _refresh(client, key, row)
  332. def _plugin_oauth_spec(plugin_dir: Path, provider: str):
  333. """``(origins, resolver)`` for *provider* when the calling plugin declares it under ``oauth:``, else None.
  334. Core-only, like the ``_PROVIDERS`` resolvers: the resolver returns the bearer, so plugins go through
  335. ``credentialed_provider_request``, which attributes the caller and checks the origin first."""
  336. client = next((c for c in _declared_clients(plugin_dir) if c.id == provider), None)
  337. if client is None:
  338. return None
  339. def resolve(url: str) -> tuple[dict[str, str], str]:
  340. parsed = urlparse(url)
  341. if parsed.username is not None or parsed.password is not None:
  342. raise PermissionError(f"Refusing to send the {client.id} sign-in to a URL with user info")
  343. # The grant is valid for every declared host, so the request URL (origin already checked) is its base.
  344. return {"Authorization": f"Bearer {_bearer(plugin_dir, client)}"}, url
  345. return _origins(client), resolve
  346. def _origins(client: OAuthClient) -> frozenset:
  347. """Origins the bearer may go to: each declared host, HTTPS on the default port."""
  348. return frozenset(("https", host, 443) for host in client.hosts)
  349. # ── hermes auth add|status|refresh|logout <plugin>:<id> ────────────────────────────────────────────
  350. def _installed_client(plugin: str, oauth_id: str) -> Optional[tuple[Path, OAuthClient]]:
  351. """Resolve *plugin* the way ``hermes plugins show`` does, then its ``oauth:`` entry *oauth_id*."""
  352. from hermes_cli.plugins_cmd import _find_plugin_entry
  353. entry = _find_plugin_entry(plugin)
  354. if entry is None or not entry[4]:
  355. return None
  356. plugin_dir = Path(str(entry[4]))
  357. client = next((c for c in _declared_clients(plugin_dir) if c.id == oauth_id), None)
  358. return (plugin_dir, client) if client is not None else None
  359. def _unattended() -> bool:
  360. from tools.approval_context import _is_gateway_approval_context, _no_user_can_answer
  361. return _no_user_can_answer() or _is_gateway_approval_context()
  362. def _cli_add(args: Any, client: OAuthClient, key: str) -> bool:
  363. from hermes_cli.auth_constants import AuthError
  364. from hermes_cli.auth_oauth_pkce_plugin import login
  365. if _unattended():
  366. raise SystemExit(f"`hermes auth add {key}` signs you in through a browser; run it in your own terminal, "
  367. "not from a gateway, cron job or agent session.")
  368. secret = " and the client secret" if client.client_secret_env else ""
  369. print(f"Plugin '{key.rsplit(':', 1)[0]}' signs in to {client.id} at {urlparse(client.authorize_url).hostname}. "
  370. f"The sign-in code{secret} go to {urlparse(client.token_url).hostname}; the token is sent only to "
  371. f"{', '.join(client.hosts)}.")
  372. try:
  373. fields = login(key, _pkce_config(client, key, timeout=getattr(args, "timeout", None)),
  374. open_browser=not getattr(args, "no_browser", False))
  375. except AuthError as exc:
  376. raise SystemExit(f"Login failed: {exc}") from None
  377. _write_grant(key, {**fields, "fingerprint": client.fingerprint})
  378. print(f"Signed in to {client.id} for plugin '{key.rsplit(':', 1)[0]}'; the grant is stored in this Hermes profile.")
  379. return True
  380. def _cli_status(args: Any, client: OAuthClient, key: str) -> bool:
  381. from hermes_cli.plugin_provider_requests import ProviderNotSignedIn
  382. row = _read_grant(key)
  383. try:
  384. _usable_grant(row, client, key)
  385. except ProviderNotSignedIn as exc:
  386. state = "logged out" if row is None else "revoked" if row.get("dead") else "sign-in needed"
  387. print(f"{key}: {state}\n {exc}")
  388. return True
  389. expires = row.get("expires_at_ms") if row else None
  390. print(f"{key}: logged in\n hosts: {', '.join(client.hosts)}" + (
  391. f"\n access token valid until {datetime.fromtimestamp(int(expires) / 1000, UTC).isoformat(timespec='seconds')}"
  392. if expires else ""))
  393. return True
  394. def _cli_refresh(args: Any, client: OAuthClient, key: str) -> bool:
  395. from hermes_cli.auth import _auth_store_lock
  396. from hermes_cli.auth_constants import AuthError
  397. from hermes_cli.plugin_provider_requests import ProviderNotSignedIn
  398. try:
  399. with _auth_store_lock():
  400. _refresh(client, key, _usable_grant(_read_grant(key), client, key))
  401. except (AuthError, ProviderNotSignedIn) as exc:
  402. raise SystemExit(f"Refresh failed: {exc}") from None
  403. print(f"{key}: refreshed")
  404. return True
  405. def _cli_logout(args: Any, client: OAuthClient, key: str) -> bool:
  406. _write_grant(key, None)
  407. print(f"Signed out of {client.id} for plugin '{key.rsplit(':', 1)[0]}'; the grant was removed from this profile.")
  408. return True
  409. def _logout_key(plugin: str, oauth_id: str) -> Optional[str]:
  410. """The stored grant key ``hermes auth logout <plugin>:<id>`` means, without parsing the manifest."""
  411. from hermes_cli.plugins_cmd import _find_plugin_entry
  412. entry = _find_plugin_entry(plugin)
  413. names = [f"{plugin_key(Path(str(entry[4])))}:{oauth_id}"] if entry is not None and entry[4] else []
  414. return next((key for key in (*names, f"{plugin}:{oauth_id}") if _read_grant(key) is not None), None)
  415. _CLI_ACTIONS = {"add": _cli_add, "status": _cli_status, "refresh": _cli_refresh, "logout": _cli_logout}
  416. def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:
  417. """``hermes auth add|status|refresh|logout <plugin>:<id>``; None when *provider* is not a plugin's
  418. ``oauth:`` entry (``custom:<name>`` stays the custom-provider pool)."""
  419. plugin, sep, oauth_id = str(provider or "").partition(":")
  420. handler = _CLI_ACTIONS.get(action)
  421. if handler is None or not (sep and plugin and oauth_id) or plugin == "custom":
  422. return None
  423. if action == "logout" and (key := _logout_key(plugin, oauth_id)) is not None:
  424. _write_grant(key, None) # needs no valid oauth: entry: the plugin may be gone or its manifest broken
  425. print(f"Signed out of {key}; the grant was removed from this profile.")
  426. return True
  427. try:
  428. found = _installed_client(plugin, oauth_id)
  429. except ValueError as exc:
  430. raise SystemExit(str(exc)) from None
  431. if found is None:
  432. return None
  433. plugin_dir, client = found
  434. return handler(args, client, f"{plugin_key(plugin_dir)}:{client.id}")
  435. __all__ = [
  436. "OAuthClient", "forget_plugin_grants", "handle_auth_action", "oauth_admission_problems",
  437. "oauth_admission_warnings", "oauth_notice", "oauth_surface", "parse_oauth_clients", "plugin_key",
  438. ]