azure_identity_adapter.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. """Microsoft Entra ID adapter for Microsoft Foundry.
  2. Keyless auth via the `azure-identity` ``DefaultAzureCredential`` chain (env service principal →
  3. workload identity → managed identity → VS Code → Azure CLI → azd → PowerShell → broker). Mirrors
  4. ``agent/bedrock_adapter.py``: `azure-identity` is imported lazily (only for ``auth_mode = entra_id``);
  5. ``build_token_provider`` returns the zero-arg callable the OpenAI SDK calls before every request
  6. (transparent refresh); consumer helpers are split by purpose so logging paths never mint tokens and
  7. tokens never leak into cache keys; no JWT is persisted (azure-identity caches in-process / OS keychain).
  8. Reference: https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/configure-entra-id
  9. """
  10. from __future__ import annotations
  11. from pm import install_hint
  12. import contextvars
  13. import functools
  14. import logging
  15. import os
  16. import threading
  17. from dataclasses import dataclass
  18. from typing import Any, Callable, Dict, Optional
  19. logger = logging.getLogger(__name__)
  20. # Microsoft-documented Foundry inference scope for ALL endpoint shapes. The older cognitiveservices.azure.com
  21. # scope is an ARM control-plane scope rejected for inference by newer resources; override via ``model.entra.scope``.
  22. SCOPE_AI_AZURE_DEFAULT = "https://ai.azure.com/.default"
  23. # ---------------------------------------------------------------------------
  24. # Lazy SDK import — only loaded when the Entra path is actually used.
  25. # ---------------------------------------------------------------------------
  26. _AZURE_IDENTITY_FEATURE = "azure-identity"
  27. _INSTALL_MSG = "The 'azure-identity' package is required for Azure AI Foundry Entra ID authentication. "
  28. _LAZY_INSTALL_HINT = (
  29. f"Run: {install_hint('azure-identity')}"
  30. )
  31. _AUTH_HEADERS = ("Authorization", "authorization", "Api-Key", "api-key", "X-Api-Key", "x-api-key")
  32. def has_azure_identity_installed() -> bool:
  33. """Cheap importability check — does not walk the credential chain."""
  34. try:
  35. import azure.identity
  36. return True
  37. except Exception:
  38. return False
  39. def _require_azure_identity():
  40. """Import ``azure.identity``, lazy-installing if allowed; ImportError with an actionable message otherwise."""
  41. try:
  42. import azure.identity as _ai
  43. return _ai
  44. except ImportError:
  45. try:
  46. from pm import InstallError, ensure_import
  47. except ImportError as exc:
  48. raise ImportError(_INSTALL_MSG + "Run: hermes pm repair") from exc
  49. try:
  50. ensure_import(_AZURE_IDENTITY_FEATURE)
  51. except InstallError as exc:
  52. raise ImportError(_INSTALL_MSG + str(exc)) from exc
  53. import azure.identity as _ai # noqa: WPS440 — retry after lazy install
  54. return _ai
  55. def reset_credential_cache() -> None:
  56. """Clear the cached credentials (tests, profile switches); tolerates a monkeypatched plain function."""
  57. cache_clear = getattr(_default_chain_credential, "cache_clear", None)
  58. if callable(cache_clear):
  59. cache_clear()
  60. _credentials_by_home.clear()
  61. @dataclass(frozen=True)
  62. class EntraIdentityConfig:
  63. """Hermes-managed Entra knobs; everything else (tenant, SP secret, federated token file, authority...) flows
  64. through azure-identity's standard ``AZURE_*`` env vars. ``exclude_interactive_browser`` keeps probes
  65. non-interactive (the setup wizard never writes it). Frozen: hashable for ``lru_cache``, picklable for workers."""
  66. scope: str = SCOPE_AI_AZURE_DEFAULT
  67. exclude_interactive_browser: bool = True
  68. def __post_init__(self) -> None:
  69. object.__setattr__(self, "scope", str(self.scope or "").strip() or SCOPE_AI_AZURE_DEFAULT)
  70. def to_dict(self) -> dict[str, Any]:
  71. return {"scope": self.scope, "exclude_interactive_browser": self.exclude_interactive_browser}
  72. @classmethod
  73. def from_dict(cls, data: Optional[dict[str, Any]], *, default_scope: Optional[str] = None) -> EntraIdentityConfig:
  74. data = data or {}
  75. return cls(
  76. scope=str(data.get("scope") or "").strip() or default_scope or SCOPE_AI_AZURE_DEFAULT,
  77. exclude_interactive_browser=bool(data.get("exclude_interactive_browser", True)),
  78. )
  79. @functools.lru_cache(maxsize=1)
  80. def _default_chain_credential(config: EntraIdentityConfig) -> Any:
  81. """Cached ``DefaultAzureCredential`` for the unscoped process. ``maxsize=1`` is intentional: a process uses
  82. one ``model.entra.*`` block at a time. Only Hermes knobs are passed as kwargs; the rest comes from ``AZURE_*``
  83. env vars."""
  84. ai = _require_azure_identity()
  85. # SDK default already excludes the browser; only pass the kwarg when opting in.
  86. kwargs = {} if config.exclude_interactive_browser else {"exclude_interactive_browser_credential": False}
  87. return ai.DefaultAzureCredential(**kwargs)
  88. # Routed multiplex profiles: (home key, config) -> credential. DefaultAzureCredential reads AZURE_* from the
  89. # process env, which under an override belongs to the LAUNCH profile, so a served profile's service principal
  90. # is built explicitly from its own secret scope (client secret first, then workload identity). Under multiplex
  91. # the ambient default chain is refused outright when the profile sets no credential of its own: every source it
  92. # could mint from (env SP, CLI/azd/PowerShell caches, host managed identity) is the launch context's identity,
  93. # and _inject_auth would ship it to whatever base_url the served profile configured.
  94. _credentials_by_home: dict[tuple, Any] = {}
  95. _AMBIENT_CHAIN_REFUSAL = (
  96. "Entra ID auth is refused for this profile: it sets no AZURE_* credential of its own, and under "
  97. "multiplexed profiles the ambient DefaultAzureCredential chain (process env, az CLI caches, host "
  98. "managed identity) mints the LAUNCH profile's identity, which would be sent to this profile's "
  99. "base_url. Set AZURE_TENANT_ID + AZURE_CLIENT_ID + AZURE_CLIENT_SECRET or "
  100. "AZURE_FEDERATED_TOKEN_FILE in this profile's own config; AZURE_CLIENT_ID alone selects the "
  101. "host's user-assigned managed identity."
  102. )
  103. def _scoped_credential(ai: Any, config: EntraIdentityConfig) -> Any:
  104. from agent.secret_scope import current_secret_scope, is_multiplex_active
  105. scope = current_secret_scope() or {}
  106. read = lambda name: (scope.get(name) or "").strip()
  107. tenant, client = read("AZURE_TENANT_ID"), read("AZURE_CLIENT_ID")
  108. if tenant and client and read("AZURE_CLIENT_SECRET"):
  109. return ai.ClientSecretCredential(tenant, client, read("AZURE_CLIENT_SECRET"))
  110. if tenant and client and read("AZURE_FEDERATED_TOKEN_FILE"):
  111. return ai.WorkloadIdentityCredential(tenant_id=tenant, client_id=client, token_file_path=read("AZURE_FEDERATED_TOKEN_FILE"))
  112. if client and not tenant and not read("AZURE_CLIENT_SECRET") and not read("AZURE_FEDERATED_TOKEN_FILE"):
  113. # AZURE_CLIENT_ID alone names a user-assigned managed identity: an explicit
  114. # per-profile choice, not an ambient borrow (same as the SDK's env-driven MI).
  115. return ai.ManagedIdentityCredential(client_id=client)
  116. if is_multiplex_active():
  117. raise RuntimeError(_AMBIENT_CHAIN_REFUSAL)
  118. kwargs = {} if config.exclude_interactive_browser else {"exclude_interactive_browser_credential": False}
  119. return ai.DefaultAzureCredential(**kwargs)
  120. def build_credential(config: EntraIdentityConfig) -> Any:
  121. """Cached Entra credential: the process-wide default chain when unscoped, the routed profile's own
  122. credential (built from its secret scope) under a HERMES_HOME override."""
  123. from hermes_constants import get_hermes_home_override, hermes_home_key
  124. if get_hermes_home_override() is None:
  125. return _default_chain_credential(config)
  126. key = (hermes_home_key(), config)
  127. credential = _credentials_by_home.get(key)
  128. if credential is None:
  129. credential = _credentials_by_home[key] = _scoped_credential(_require_azure_identity(), config)
  130. return credential
  131. def _resolve_config(config: Optional[EntraIdentityConfig], scope: Optional[str], **overrides: Any) -> EntraIdentityConfig:
  132. if config is not None:
  133. return config
  134. return EntraIdentityConfig(scope=(scope or "").strip() or SCOPE_AI_AZURE_DEFAULT, **overrides)
  135. def _install_failure(allow_install: bool) -> Optional[dict[str, Any]]:
  136. """None when ``azure.identity`` is importable (lazy-installing if allowed), else ``{"error", "hint"}``."""
  137. if has_azure_identity_installed():
  138. return None
  139. if not allow_install:
  140. return {"error": "azure-identity not installed", "hint": _LAZY_INSTALL_HINT}
  141. try:
  142. _require_azure_identity()
  143. except ImportError as exc:
  144. return {"error": str(exc) or "azure-identity not installed", "hint": _LAZY_INSTALL_HINT, "exc": exc}
  145. return None
  146. def build_token_provider(scope: Optional[str] = None, *, config: Optional[EntraIdentityConfig] = None,
  147. exclude_interactive_browser: bool = True) -> Callable[[], str]:
  148. """Zero-arg callable minting a fresh Entra bearer JWT — pass as ``OpenAI(api_key=...)``. Scope precedence:
  149. ``config.scope`` > ``scope`` kwarg > default. Not picklable: ship the ``EntraIdentityConfig`` and rebuild
  150. in the worker."""
  151. ai = _require_azure_identity()
  152. config = _resolve_config(config, scope, exclude_interactive_browser=exclude_interactive_browser)
  153. from agent.credential_source import ENTRA_ID, tag_credential_source
  154. return tag_credential_source(ai.get_bearer_token_provider(build_credential(config), config.scope), ENTRA_ID)
  155. def _probe_token(config: EntraIdentityConfig, timeout_seconds: float) -> Optional[dict[str, Any]]:
  156. """``get_token`` on a daemon thread under a hard deadline → ``{"token"}`` / ``{"error"}`` / None on timeout."""
  157. result: dict[str, Any] = {}
  158. ctx = contextvars.copy_context()
  159. def _probe() -> None:
  160. try:
  161. result["token"] = build_credential(config).get_token(config.scope)
  162. except Exception as exc:
  163. result["error"] = str(exc)
  164. # A bare Thread drops contextvars, so the probe would run UNSCOPED under
  165. # multiplexing — minting the launch profile's chain and hiding the refusal.
  166. thread = threading.Thread(target=lambda: ctx.run(_probe), daemon=True)
  167. thread.start()
  168. thread.join(timeout=max(0.01, timeout_seconds))
  169. return None if thread.is_alive() else result
  170. def has_azure_identity_credentials(scope: Optional[str] = None, *, config: Optional[EntraIdentityConfig] = None,
  171. timeout_seconds: float = 10.0, allow_install: bool = True,
  172. **overrides: Any) -> bool:
  173. """Timeout-bounded probe: can the chain mint a token now? Never raises. ``allow_install=False`` makes it a
  174. strict "is installed?" check for hot paths (CLI startup) where pip must never run. NOT used by
  175. ``is_provider_configured()`` (structural, no mint)."""
  176. failure = _install_failure(allow_install)
  177. if failure is not None:
  178. if "exc" in failure:
  179. logger.debug("azure-identity lazy install unavailable: %s", failure["exc"])
  180. return False
  181. result = _probe_token(_resolve_config(config, scope, **overrides), timeout_seconds)
  182. if result is None:
  183. logger.debug("Entra token service probe timed out after %ss", timeout_seconds)
  184. return False
  185. if "error" in result:
  186. logger.debug("Entra credential probe failed: %s", result["error"])
  187. return False
  188. return bool(getattr(result.get("token"), "token", None))
  189. def _env(name: str) -> str:
  190. return os.environ.get(name, "").strip()
  191. def _scoped_env(name: str) -> str:
  192. """Credential-bearing env read via the profile secret scope so a multiplexed profile never reports
  193. another profile's env-bridged credentials. Unscoped CLI probes (multiplex off) read the process
  194. env through ``get_secret`` itself; a scope-less multiplex caller raises — spawn-site bug."""
  195. from agent.secret_scope import get_secret
  196. return (get_secret(name) or "").strip()
  197. # (label, predicate) for env-var-driven credential sources, in chain order.
  198. _ENV_SOURCE_CHECKS = (
  199. ("WorkloadIdentityCredential (AZURE_FEDERATED_TOKEN_FILE)", lambda: _scoped_env("AZURE_FEDERATED_TOKEN_FILE")),
  200. ("EnvironmentCredential (client secret)",
  201. lambda: _scoped_env("AZURE_CLIENT_ID") and _scoped_env("AZURE_CLIENT_SECRET") and _scoped_env("AZURE_TENANT_ID")),
  202. ("ManagedIdentityCredential (IDENTITY_ENDPOINT)", lambda: _env("IDENTITY_ENDPOINT") or _env("MSI_ENDPOINT")),
  203. )
  204. def describe_active_credential(config: Optional[EntraIdentityConfig] = None, *, scope: Optional[str] = None,
  205. timeout_seconds: float = 10.0, allow_install: bool = True,
  206. **overrides: Any) -> dict[str, Any]:
  207. """Doctor / preflight diagnostics. Never raises; ``{"ok": False, "error": ...}`` on failure. azure-identity
  208. hides the winning inner credential, so this reports a coarse picture (env sources, token expiry) rather
  209. than a class name; ``AZURE_LOG_LEVEL=DEBUG`` shows the chain."""
  210. info: dict[str, Any] = {"ok": False}
  211. failure = _install_failure(allow_install)
  212. if failure is not None:
  213. info["error"], info["hint"] = failure["error"], failure["hint"]
  214. return info
  215. config = _resolve_config(config, scope, **overrides)
  216. info["scope"] = config.scope
  217. if tenant := _scoped_env("AZURE_TENANT_ID"):
  218. info["tenant_id_env"] = tenant
  219. info["env_sources"] = [label for label, present in _ENV_SOURCE_CHECKS if present()]
  220. result = _probe_token(config, timeout_seconds)
  221. if result is None:
  222. info["error"] = f"Token probe timed out after {timeout_seconds:.0f}s"
  223. info["hint"] = ("DefaultAzureCredential can be slow when the token service is unreachable "
  224. "or when az login state is stale. Try `az login` or set "
  225. "AZURE_CLIENT_ID / AZURE_TENANT_ID / AZURE_CLIENT_SECRET.")
  226. return info
  227. if "error" in result:
  228. info["error"] = result["error"]
  229. return info
  230. token = result.get("token")
  231. if token is None:
  232. info["error"] = "credential chain exhausted"
  233. return info
  234. info["ok"] = True
  235. info["expires_on"] = getattr(token, "expires_on", None)
  236. return info
  237. # Consumer-side helpers — split by purpose so logging / cache-key / dashboard paths never mint tokens.
  238. def is_token_provider(value: Any) -> bool:
  239. """True when ``value`` is a callable Entra token provider (vs. a string API key)."""
  240. return callable(value) and not isinstance(value, str)
  241. def materialize_bearer_for_http(value: Any) -> str:
  242. """Mint a fresh Bearer JWT for a manual HTTP request (calls the provider once). Only for sites building
  243. ``Authorization`` outside the OpenAI SDK; the Anthropic SDK can't take a callable, so
  244. :func:`build_bearer_http_client` calls this from an httpx hook. ``ValueError`` on an unusable value/empty token."""
  245. if is_token_provider(value):
  246. token = value()
  247. if not isinstance(token, str) or not token:
  248. raise ValueError("token provider returned empty value")
  249. return token
  250. if isinstance(value, str) and value:
  251. return value
  252. raise ValueError("no usable api_key / token provider")
  253. def _strip_auth_headers(request: Any) -> None:
  254. for header_name in _AUTH_HEADERS:
  255. request.headers.pop(header_name, None)
  256. def build_bearer_http_client(
  257. token_provider: Callable[[], str], *, sends_as_api_key: Callable[[str], bool] | None = None, **httpx_kwargs: Any
  258. ) -> Any:
  259. """``httpx.Client`` minting a fresh Entra bearer JWT per outbound request. The Anthropic SDK computes
  260. ``Authorization`` once at construction, so per-request refresh needs a ``request`` hook: mint (cheap —
  261. azure-identity caches), strip pre-set auth headers, set ``Authorization: Bearer``. ``httpx_kwargs`` are
  262. forwarded verbatim (``timeout``, ``transport``...). ``sends_as_api_key(token)`` True puts the minted
  263. token in ``x-api-key`` instead (a ``key_cmd`` printing a native Anthropic Console key)."""
  264. if not is_token_provider(token_provider):
  265. raise ValueError("build_bearer_http_client requires a zero-arg callable token provider")
  266. import httpx
  267. def _inject_auth(request: httpx.Request) -> None:
  268. try:
  269. token = materialize_bearer_for_http(token_provider)
  270. except ValueError as exc:
  271. # Chain exhausted / az login expired: strip ALL auth headers (incl. the anthropic_adapter placeholder
  272. # sentinel) so Azure returns a clean "missing auth" 401 and the sentinel never reaches upstream logs.
  273. # WARNING so the misconfiguration is visible at default levels.
  274. logger.warning("Bearer hook: Entra ID token provider returned empty (%s) "
  275. "— stripping Authorization headers. Azure will respond 401. "
  276. "Run `hermes doctor` or `az login` to recover.", exc)
  277. _strip_auth_headers(request)
  278. return
  279. _strip_auth_headers(request)
  280. if sends_as_api_key is not None and sends_as_api_key(token):
  281. request.headers["x-api-key"] = token
  282. else:
  283. request.headers["Authorization"] = f"Bearer {token}"
  284. return httpx.Client(event_hooks={"request": [_inject_auth]}, **httpx_kwargs)
  285. __all__ = [
  286. "SCOPE_AI_AZURE_DEFAULT",
  287. "EntraIdentityConfig",
  288. "build_bearer_http_client",
  289. "build_credential",
  290. "build_token_provider",
  291. "describe_active_credential",
  292. "has_azure_identity_credentials",
  293. "has_azure_identity_installed",
  294. "is_token_provider",
  295. "materialize_bearer_for_http",
  296. "reset_credential_cache",
  297. ]