plugin_provider_requests.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. """Signed-in provider requests that core makes FOR plugins; the token never reaches plugin code.
  2. A plugin that needs the user's subscription sign-in (today: Codex / ChatGPT) must not read, refresh
  3. or rewrite Hermes's auth store or ``~/.codex/auth.json``. Codex refresh tokens are single-use, so a
  4. second refresher races Hermes's locked refresh and can sign the user out. Instead the plugin declares
  5. ``requires_auth: [openai-codex]`` in its ``plugin.yaml`` and calls :func:`credentialed_provider_request`.
  6. Hermes resolves the credential through its own locked-refresh path, attaches ``Authorization``
  7. itself, sends only to that provider's origins, never follows a redirect, and hands back
  8. status, headers and body.
  9. The caller is identified by file location: the nearest stack frame inside an installed plugin
  10. directory. Like capabilities this is consent and visibility, not a sandbox. In-process plugin code
  11. can still read any file the user can.
  12. """
  13. from __future__ import annotations
  14. import json as _json
  15. import sys
  16. from dataclasses import dataclass
  17. from pathlib import Path
  18. from typing import Any, Callable, Mapping, Optional
  19. from hermes_cli.urllib_security import url_origin
  20. class ProviderNotSignedIn(RuntimeError):
  21. """The user has no usable sign-in for the provider in this Hermes profile."""
  22. @dataclass(frozen=True)
  23. class ProviderResponse:
  24. status: int
  25. headers: dict[str, str]
  26. body: bytes
  27. @property
  28. def text(self) -> str:
  29. return self.body.decode("utf-8", "replace")
  30. def json(self) -> Any:
  31. return _json.loads(self.body)
  32. def _codex_auth(url: str) -> tuple[dict[str, str], str]:
  33. """``(auth headers, credential base URL)`` from Hermes's own locked-refresh resolver."""
  34. from agent.codex_headers import codex_account_headers
  35. from agent.turn_failure_copy import oauth_relogin_command
  36. from hermes_cli.auth_codex import resolve_codex_runtime_credentials
  37. from hermes_cli.auth_constants import AuthError
  38. try:
  39. creds = resolve_codex_runtime_credentials()
  40. except AuthError as exc:
  41. if not exc.relogin_required:
  42. raise
  43. creds = {}
  44. token = str(creds.get("api_key") or "").strip()
  45. if not token:
  46. raise ProviderNotSignedIn(
  47. f"Not signed in to Codex in Hermes. Run `{oauth_relogin_command('openai-codex')}` "
  48. "or sign in to OpenAI Codex under Providers in the Hermes desktop app.")
  49. headers = codex_account_headers(token) if url_origin(url)[1] == "chatgpt.com" else {}
  50. headers["Authorization"] = f"Bearer {token}"
  51. return headers, str(creds.get("base_url") or "")
  52. # provider -> (origins its token may be sent to, auth resolver). chatgpt.com is the Codex backend
  53. # core itself calls; api.openai.com hosts the Realtime client-secret endpoint Codex clients use.
  54. _PROVIDERS: dict[str, tuple[frozenset, Callable[[str], tuple[dict[str, str], str]]]] = {
  55. "openai-codex": (frozenset({("https", "chatgpt.com", 443), ("https", "api.openai.com", 443)}), _codex_auth),
  56. }
  57. def _plugin_roots() -> set[Path]:
  58. """Every plugins directory an installed plugin can live under, as given and resolved."""
  59. from hermes_cli.plugins import get_bundled_plugins_dir
  60. from hermes_constants import get_default_hermes_root, get_hermes_home, get_process_hermes_home
  61. bases = (get_hermes_home() / "plugins", get_process_hermes_home() / "plugins",
  62. get_default_hermes_root() / "plugins", get_bundled_plugins_dir())
  63. return {r for base in bases for r in (base.absolute(), base.resolve())}
  64. def _calling_plugin_dir() -> Optional[Path]:
  65. """Directory of the plugin whose code is nearest on the calling stack, or None."""
  66. roots = _plugin_roots()
  67. frame = sys._getframe(2)
  68. while frame is not None:
  69. raw = Path(frame.f_code.co_filename)
  70. for path in (raw.absolute(), raw.resolve()):
  71. root = next((r for r in roots if path.is_relative_to(r) and path != r), None)
  72. if root is None:
  73. continue
  74. for parent in path.parents:
  75. if parent == root:
  76. break
  77. if (parent / "plugin.yaml").is_file() or (parent / "plugin.yml").is_file():
  78. return parent
  79. return root / path.relative_to(root).parts[0]
  80. frame = frame.f_back
  81. return None
  82. def _detached(exc: BaseException) -> BaseException:
  83. """*exc* without traceback or chain: those frames hold the token, refresh token or client secret."""
  84. exc.__cause__ = exc.__context__ = None
  85. return exc.with_traceback(None)
  86. def declared_auth_providers(manifest: Mapping[str, Any]) -> list[str]:
  87. """``requires_auth`` from a manifest dict: the providers whose sign-in the plugin uses."""
  88. raw = (manifest or {}).get("requires_auth")
  89. return [str(p).strip() for p in raw if str(p).strip()] if isinstance(raw, list) else []
  90. def requires_auth_notice(manifest: Mapping[str, Any]) -> str:
  91. """One line for install/show surfaces; empty when the plugin declares no sign-in use."""
  92. from hermes_cli.plugin_oauth import oauth_notice
  93. providers = declared_auth_providers(manifest)
  94. sign_in = (f"Uses your sign-in for: {', '.join(providers)} (Hermes sends the requests; "
  95. "the plugin never receives the token)") if providers else ""
  96. return "; ".join(part for part in (sign_in, oauth_notice(manifest)) if part)
  97. def _declared_providers(plugin_dir: Path) -> list[str]:
  98. from pm.plugin_declarations import native_manifest_file, read_native_manifest
  99. manifest = native_manifest_file(plugin_dir)
  100. return declared_auth_providers(read_native_manifest(manifest)) if manifest else []
  101. def credentialed_provider_request(
  102. provider: str, method: str, url: str, *, json: Any = None,
  103. headers: Optional[Mapping[str, str]] = None, timeout: float = 30.0,
  104. ) -> ProviderResponse:
  105. """Send ``method url`` with the user's *provider* sign-in attached by Hermes.
  106. *provider* is a Hermes sign-in (listed under ``requires_auth``) or an ``id`` the calling plugin
  107. declares under ``oauth:`` (:mod:`hermes_cli.plugin_oauth`); the plugin's own entry wins.
  108. Refuses (``PermissionError``) a caller outside an installed plugin, a plugin whose ``plugin.yaml``
  109. does not list *provider* under ``requires_auth``, and any origin outside the provider's
  110. allowlist; raises :class:`ProviderNotSignedIn` when this profile has no sign-in. Redirects are
  111. returned as-is, never followed. The result carries no credential.
  112. """
  113. from hermes_cli.plugin_oauth import _plugin_oauth_spec
  114. plugin_dir = _calling_plugin_dir()
  115. if plugin_dir is None:
  116. raise PermissionError("credentialed_provider_request must be called from an installed plugin's code")
  117. # The plugin's own oauth: entry first, so a core provider added later under the same id cannot take it over.
  118. spec = _plugin_oauth_spec(plugin_dir, provider)
  119. if spec is None:
  120. spec = _PROVIDERS.get(provider)
  121. if spec is None:
  122. raise ValueError(f"No signed-in requests for provider {provider!r} (supported: {', '.join(_PROVIDERS)}, "
  123. "or an id the plugin declares under oauth: in plugin.yaml)")
  124. if provider not in _declared_providers(plugin_dir):
  125. raise PermissionError(
  126. f"Plugin '{plugin_dir.name}' must declare `requires_auth: [{provider}]` in plugin.yaml")
  127. origins, resolve = spec
  128. if url_origin(url) not in origins:
  129. raise PermissionError(f"Refusing to send the {provider} sign-in to {url_origin(url)[1] or url!r}")
  130. import httpx
  131. # Every error the plugin receives past this point is rebuilt without traceback, chain or request: those
  132. # reach the frames and httpx objects that hold the token, refresh token or client secret.
  133. refusal: Optional[BaseException] = None
  134. with httpx.Client(timeout=timeout, follow_redirects=False) as client:
  135. request = client.build_request(method, url, json=json, headers=dict(headers or {})) # no credential yet
  136. try:
  137. auth_headers, credential_base = resolve(url)
  138. except httpx.HTTPError as exc: # a resolver's own refresh POST failed: its request holds the refresh token
  139. refusal = type(exc)(str(exc))
  140. except (RuntimeError, OSError, ValueError, LookupError, TypeError) as exc:
  141. refusal = _detached(exc)
  142. else:
  143. if url_origin(credential_base) not in origins:
  144. # A pooled gateway key belongs to its own host only (#121486).
  145. refusal = PermissionError(
  146. f"This profile's {provider} credential routes to a custom endpoint; refusing")
  147. else:
  148. for name in auth_headers:
  149. request.headers.pop(name, None)
  150. request.headers.update(auth_headers)
  151. try:
  152. response = client.send(request)
  153. except httpx.HTTPError as exc:
  154. refusal = type(exc)(str(exc))
  155. auth_headers = request = None
  156. if refusal is not None:
  157. raise refusal
  158. return ProviderResponse(response.status_code, dict(response.headers), response.content)
  159. __all__ = [
  160. "ProviderNotSignedIn", "ProviderResponse", "credentialed_provider_request", "declared_auth_providers",
  161. "requires_auth_notice",
  162. ]