credential_sources.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. """Unified removal contract for every credential source Hermes reads from.
  2. Readers live in ``agent.credential_pool``; what is unified here is **removal**:
  3. ``hermes auth remove <provider> <N>`` must make the entry stay gone across
  4. ``load_pool()`` calls. Each source registers a ``RemovalStep`` whose
  5. ``remove_fn`` cleans the external state the source reads from, and the
  6. dispatcher suppresses ``(provider, source_id)`` in auth.json so the seeding
  7. branch skips the upsert. Adding a source: wire a reader branch in
  8. ``_seed_from_*``, gate it behind ``is_source_suppressed``, register a step here.
  9. Also home to the one policy switch over *borrowed* CLI logins (Codex CLI's
  10. ``~/.codex/auth.json``, Claude Code's ``~/.claude/.credentials.json``):
  11. ``auth.adopt_external_logins`` in config.yaml.
  12. """
  13. from __future__ import annotations
  14. import logging
  15. import os
  16. from dataclasses import dataclass, field
  17. from typing import Callable, List, Optional
  18. logger = logging.getLogger(__name__)
  19. EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE = (
  20. "External CLI logins (Codex CLI, Claude Code) are not adopted: auth.adopt_external_logins is false. "
  21. "Hermes uses only its own logins; run `hermes auth add <provider>` to add one."
  22. )
  23. _notice_logged = False
  24. def adopt_external_logins_enabled() -> bool:
  25. """``auth.adopt_external_logins`` (default True).
  26. Codex and Claude OAuth refresh tokens are single-use and rotate, so once Hermes borrows a CLI's
  27. token pair the two programs hold one token family and whichever refreshes first logs the other
  28. out. When the user opts out, Hermes never reads or refreshes those files and says so once per
  29. process (INFO) the first time it would have."""
  30. global _notice_logged
  31. try:
  32. from hermes_cli.config import load_config_readonly
  33. auth_cfg = (load_config_readonly() or {}).get("auth")
  34. except Exception:
  35. return True
  36. enabled = not isinstance(auth_cfg, dict) or bool(auth_cfg.get("adopt_external_logins", True))
  37. if not enabled and not _notice_logged:
  38. _notice_logged = True
  39. logger.info(EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE)
  40. return enabled
  41. @dataclass
  42. class RemovalResult:
  43. """Outcome of removing a credential source.
  44. ``cleaned``: external state actually mutated (printed to the user).
  45. ``hints``: diagnostics about state left intact or that the user must clean
  46. up. ``suppress``: call ``suppress_credential_source`` afterwards so
  47. ``load_pool`` skips the source; only ``manual`` entries legitimately use False.
  48. """
  49. cleaned: list[str] = field(default_factory=list)
  50. hints: list[str] = field(default_factory=list)
  51. suppress: bool = True
  52. @dataclass
  53. class RemovalStep:
  54. """How to remove one credential source.
  55. ``provider`` ``"*"`` matches any provider. ``match_fn`` overrides literal
  56. ``source_id`` matching (prefix patterns like ``env:*`` / ``config:*``).
  57. ``remove_fn(provider, removed_entry) -> RemovalResult``.
  58. """
  59. provider: str
  60. source_id: str
  61. remove_fn: Callable[..., RemovalResult]
  62. match_fn: Optional[Callable[[str], bool]] = None
  63. description: str = ""
  64. def matches(self, provider: str, source: str) -> bool:
  65. if self.provider != "*" and self.provider != provider:
  66. return False
  67. if self.match_fn is not None:
  68. return self.match_fn(source)
  69. return source == self.source_id
  70. def find_removal_step(provider: str, source: str) -> Optional[RemovalStep]:
  71. """The provider profile's own step when it claims *source*, else the first matching registry
  72. step, or None (``manual``: nothing external to clean)."""
  73. return _profile_removal_step(provider, source) or next(
  74. (step for step in _REGISTRY if step.matches(provider, source)), None)
  75. def _profile_removal_step(provider: str, source: str) -> Optional[RemovalStep]:
  76. """``ProviderProfile.remove_credential_source``: a provider seeding one token under several
  77. sources suppresses every variant, or the duplicates resurrect the entry."""
  78. from providers import get_provider_profile
  79. profile = get_provider_profile(provider)
  80. claimed = profile.remove_credential_source(source) if profile else None
  81. if claimed is None:
  82. return None
  83. sources, hints = claimed
  84. def remove_fn(provider: str, removed) -> RemovalResult:
  85. from hermes_cli.auth import suppress_credential_source
  86. for variant in sources:
  87. suppress_credential_source(provider, variant)
  88. return RemovalResult(hints=list(hints))
  89. return RemovalStep(provider=provider, source_id=source, remove_fn=remove_fn)
  90. def _remove_env_source(provider: str, removed) -> RemovalResult:
  91. """env:<VAR> — clear from ~/.hermes/.env; hint when the shell exports it."""
  92. from hermes_cli.config import get_env_path, remove_env_value
  93. result = RemovalResult()
  94. env_var = removed.source[len("env:"):]
  95. if not env_var:
  96. return result
  97. # Detect shell vs .env BEFORE remove_env_value pops os.environ. Read the
  98. # .env as utf-8-sig like hermes_cli/config.py: a BOM-sensitive read would
  99. # misreport a Notepad-edited .env var as a shell export.
  100. env_in_process = bool(os.getenv(env_var))
  101. env_in_dotenv = False
  102. try:
  103. env_path = get_env_path()
  104. if env_path.exists():
  105. env_in_dotenv = any(
  106. line.strip().startswith(f"{env_var}=")
  107. for line in env_path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
  108. )
  109. except OSError:
  110. pass
  111. if remove_env_value(env_var):
  112. result.cleaned.append(f"Cleared {env_var} from .env")
  113. if env_in_process and not env_in_dotenv:
  114. result.hints.extend([
  115. f"Note: {env_var} is still set in your shell environment "
  116. f"(not in ~/.hermes/.env).",
  117. " Unset it there (shell profile, systemd EnvironmentFile, "
  118. "launchd plist, etc.) or it will keep being visible to Hermes.",
  119. f" The pool entry is now suppressed — Hermes will ignore "
  120. f"{env_var} until you run `hermes auth add {provider}`.",
  121. ])
  122. else:
  123. result.hints.append(
  124. f"Suppressed env:{env_var} — it will not be re-seeded even "
  125. f"if the variable is re-exported later."
  126. )
  127. return result
  128. def _remove_hermes_pkce(provider: str, removed) -> RemovalResult:
  129. """~/.hermes/.anthropic_oauth.json is ours — delete it outright."""
  130. from hermes_constants import get_hermes_home
  131. result = RemovalResult()
  132. oauth_file = get_hermes_home() / ".anthropic_oauth.json"
  133. if oauth_file.exists():
  134. try:
  135. oauth_file.unlink()
  136. result.cleaned.append("Cleared Hermes Anthropic OAuth credentials")
  137. except OSError as exc:
  138. result.hints.append(f"Could not delete {oauth_file}: {exc}")
  139. return result
  140. def _remove_auth_store_oauth(provider: str, removed) -> RemovalResult:
  141. """Clear auth.json ``providers.<provider>`` (nous, minimax-oauth, xai-oauth, openai-codex).
  142. Suppression by the dispatcher is still required — otherwise
  143. ``_seed_from_singletons`` re-seeds from any path that rewrites the block.
  144. """
  145. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
  146. result = RemovalResult()
  147. with _auth_store_lock():
  148. auth_store = _load_auth_store()
  149. providers_dict = auth_store.get("providers")
  150. if isinstance(providers_dict, dict) and provider in providers_dict:
  151. del providers_dict[provider]
  152. _save_auth_store(auth_store)
  153. result.cleaned.append(f"Cleared {provider} OAuth tokens from auth store")
  154. return result
  155. def _remove_xai_oauth_device_code(provider: str, removed) -> RemovalResult:
  156. result = _remove_auth_store_oauth(provider, removed)
  157. result.hints.append(
  158. "Run `hermes model` → xAI Grok OAuth (SuperGrok / Premium+) to re-authenticate if needed."
  159. )
  160. return result
  161. def _remove_codex_device_code(provider: str, removed) -> RemovalResult:
  162. """Codex tokens also live in ~/.codex/auth.json (Codex CLI's file, kept).
  163. Suppress the canonical ``device_code`` key — not just ``removed.source`` —
  164. so a ``manual:device_code`` removal still blocks the re-seed path.
  165. """
  166. from hermes_cli.auth import suppress_credential_source
  167. result = _remove_auth_store_oauth(provider, removed)
  168. suppress_credential_source(provider, "device_code")
  169. result.hints.extend([
  170. "Suppressed openai-codex device_code source — it will not be re-seeded.",
  171. "Note: Codex CLI credentials still live in ~/.codex/auth.json",
  172. "Run `hermes auth add openai-codex` to re-enable if needed.",
  173. ])
  174. return result
  175. def _suppress_only(*hints: str) -> Callable[..., RemovalResult]:
  176. """remove_fn for sources whose backing file/config belongs to another tool
  177. (Claude Code, Qwen CLI, config.yaml): never delete it, just suppress and
  178. explain. ``{source}`` in a hint is the removed entry's source string."""
  179. def remove_fn(provider: str, removed) -> RemovalResult:
  180. return RemovalResult(hints=[h.format(source=removed.source) for h in hints])
  181. return remove_fn
  182. # ORDER MATTERS — ``find_removal_step`` returns the first match (after a provider profile's own
  183. # ``remove_credential_source`` claim, so a profile's ``env:*`` rows skip the generic .env removal).
  184. _REGISTRY: list[RemovalStep] = [
  185. RemovalStep(
  186. provider="*", source_id="env:",
  187. match_fn=lambda src: src.startswith("env:"),
  188. remove_fn=_remove_env_source,
  189. description="Any env-seeded credential (XAI_API_KEY, DEEPSEEK_API_KEY, etc.)",
  190. ),
  191. RemovalStep(
  192. provider="anthropic", source_id="claude_code",
  193. remove_fn=_suppress_only(
  194. "Suppressed claude_code credential — it will not be re-seeded.",
  195. "Note: Claude Code credentials still live in ~/.claude/.credentials.json",
  196. "Run `hermes auth add anthropic` to re-enable if needed.",
  197. ),
  198. description="~/.claude/.credentials.json",
  199. ),
  200. RemovalStep(
  201. provider="anthropic", source_id="hermes_pkce",
  202. remove_fn=_remove_hermes_pkce,
  203. description="~/.hermes/.anthropic_oauth.json",
  204. ),
  205. RemovalStep(
  206. provider="nous", source_id="device_code",
  207. remove_fn=_remove_auth_store_oauth,
  208. description="auth.json providers.nous",
  209. ),
  210. RemovalStep(
  211. provider="openai-codex", source_id="device_code",
  212. match_fn=lambda src: src == "device_code" or src.endswith(":device_code"),
  213. remove_fn=_remove_codex_device_code,
  214. description="auth.json providers.openai-codex + ~/.codex/auth.json",
  215. ),
  216. RemovalStep(
  217. provider="xai-oauth", source_id="device_code",
  218. remove_fn=_remove_xai_oauth_device_code,
  219. description="auth.json providers.xai-oauth",
  220. ),
  221. RemovalStep(
  222. provider="qwen-oauth", source_id="qwen-cli",
  223. remove_fn=_suppress_only(
  224. "Suppressed qwen-cli credential — it will not be re-seeded.",
  225. "Note: Qwen CLI credentials still live in ~/.qwen/oauth_creds.json",
  226. "Run `hermes auth add qwen-oauth` to re-enable if needed.",
  227. ),
  228. description="~/.qwen/oauth_creds.json",
  229. ),
  230. RemovalStep(
  231. provider="minimax-oauth", source_id="oauth",
  232. remove_fn=_remove_auth_store_oauth,
  233. description="auth.json providers.minimax-oauth",
  234. ),
  235. RemovalStep(
  236. provider="*", source_id="config:",
  237. match_fn=lambda src: src.startswith("config:") or src == "model_config",
  238. remove_fn=_suppress_only(
  239. "Suppressed {source} — it will not be re-seeded.",
  240. "Note: The underlying value in config.yaml is unchanged. Edit it "
  241. "directly if you want to remove the credential from disk.",
  242. ),
  243. description="Custom provider config.yaml api_key field",
  244. ),
  245. ]