credential_source.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Name a callable API key's credential source without calling it.
  2. A callable ``api_key`` mints a bearer on first use (Entra ID, Vertex OAuth, a custom provider's
  3. ``key_cmd``, MiniMax OAuth). Display paths (``/config``, the agent's key banner) must say which
  4. kind it is, but calling it would mint a token just to mask it. Each builder tags the callable it
  5. returns with a source; display reads the tag through one source-to-label table. An untagged
  6. callable gets a neutral label, never another vendor's name.
  7. """
  8. from __future__ import annotations
  9. from typing import Any, Callable, Optional, TypeVar
  10. ENTRA_ID = "entra-id"
  11. VERTEX_OAUTH = "vertex-oauth"
  12. KEY_CMD = "key-cmd"
  13. MINIMAX_OAUTH = "minimax-oauth"
  14. # Attribute read with getattr only: reading it never invokes the callable.
  15. SOURCE_ATTR = "hermes_credential_source"
  16. # Credential source -> i18n key. Both display surfaces resolve labels here.
  17. SOURCE_LABEL_KEYS = {
  18. ENTRA_ID: "cli.config.microsoft_entra_id",
  19. VERTEX_OAUTH: "cli.config.google_vertex_oauth",
  20. KEY_CMD: "cli.config.key_cmd_token",
  21. MINIMAX_OAUTH: "cli.config.minimax_oauth",
  22. }
  23. UNKNOWN_LABEL_KEY = "cli.config.token_provider"
  24. _F = TypeVar("_F", bound=Callable[..., Any])
  25. def tag_credential_source(provider: _F, source: str) -> _F:
  26. """Record *source* on *provider* and return it (a no-op for objects that refuse attributes)."""
  27. try:
  28. setattr(provider, SOURCE_ATTR, source)
  29. except (AttributeError, TypeError):
  30. pass
  31. return provider
  32. def credential_source(key: Any) -> Optional[str]:
  33. """The source tag of a callable key, or None (string keys and untagged callables)."""
  34. if isinstance(key, str) or not callable(key):
  35. return None
  36. source = getattr(key, SOURCE_ATTR, None)
  37. return source if isinstance(source, str) else None
  38. def credential_label(key: Any) -> Optional[str]:
  39. """Translated label for a callable key's source (neutral when untagged); None for a non-callable."""
  40. if isinstance(key, str) or not callable(key):
  41. return None
  42. from agent.i18n import t
  43. return t(SOURCE_LABEL_KEYS.get(credential_source(key) or "", UNKNOWN_LABEL_KEY))