microsoft_graph_auth.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. """Microsoft Graph app-only (client-credentials) authentication helpers."""
  2. from __future__ import annotations
  3. import asyncio
  4. import os
  5. import time
  6. from dataclasses import dataclass
  7. from typing import Any
  8. import httpx
  9. DEFAULT_GRAPH_SCOPE = "https://graph.microsoft.com/.default"
  10. DEFAULT_GRAPH_AUTHORITY_URL = "https://login.microsoftonline.com"
  11. DEFAULT_TOKEN_SKEW_SECONDS = 120
  12. _REQUIRED_ENV = ("MSGRAPH_TENANT_ID", "MSGRAPH_CLIENT_ID", "MSGRAPH_CLIENT_SECRET")
  13. class MicrosoftGraphAuthError(RuntimeError):
  14. """Base class for Microsoft Graph auth failures."""
  15. class MicrosoftGraphConfigError(MicrosoftGraphAuthError):
  16. """Graph credentials are missing or invalid."""
  17. class MicrosoftGraphTokenError(MicrosoftGraphAuthError):
  18. """Token acquisition failed."""
  19. def format_graph_error(error: Any) -> str | None:
  20. """Render Graph's ``{"error": {"code", "message"}}`` (or bare-string ``error``) as
  21. ``code: message``; shared by token endpoint and REST client. None if unusable."""
  22. if isinstance(error, str):
  23. return error
  24. if not isinstance(error, dict):
  25. return None
  26. code, message = error.get("code"), error.get("message")
  27. return f"{code}: {message}" if code and message else (str(message) if message else None)
  28. @dataclass(frozen=True)
  29. class GraphCredentials:
  30. """Normalized Microsoft Graph app-only credentials."""
  31. tenant_id: str
  32. client_id: str
  33. client_secret: str
  34. scope: str = DEFAULT_GRAPH_SCOPE
  35. authority_url: str = DEFAULT_GRAPH_AUTHORITY_URL
  36. @property
  37. def token_url(self) -> str:
  38. return f"{self.authority_url.rstrip('/')}/{self.tenant_id.strip().strip('/')}/oauth2/v2.0/token"
  39. @classmethod
  40. def from_env(cls, environ: dict[str, str] | None = None, *, required: bool = True) -> GraphCredentials | None:
  41. env = environ if environ is not None else os.environ
  42. values = [(env.get(name) or "").strip() for name in _REQUIRED_ENV]
  43. missing = [name for name, value in zip(_REQUIRED_ENV, values) if not value]
  44. if missing and not required:
  45. return None
  46. if missing:
  47. raise MicrosoftGraphConfigError(f"Missing Microsoft Graph configuration: {', '.join(missing)}")
  48. return cls(*values, scope=(env.get("MSGRAPH_SCOPE") or DEFAULT_GRAPH_SCOPE).strip(),
  49. authority_url=(env.get("MSGRAPH_AUTHORITY_URL") or DEFAULT_GRAPH_AUTHORITY_URL).strip())
  50. @dataclass
  51. class CachedAccessToken:
  52. """Cached app-only Graph access token."""
  53. access_token: str
  54. expires_at: float
  55. token_type: str = "Bearer"
  56. def is_expired(self, *, skew_seconds: int = DEFAULT_TOKEN_SKEW_SECONDS) -> bool:
  57. return self.expires_at <= (time.time() + max(0, int(skew_seconds)))
  58. @property
  59. def expires_in_seconds(self) -> int:
  60. return max(0, int(self.expires_at - time.time()))
  61. class MicrosoftGraphTokenProvider:
  62. """Acquire and cache Microsoft Graph app-only access tokens."""
  63. def __init__(self, credentials: GraphCredentials, *, timeout: float = 20.0,
  64. skew_seconds: int = DEFAULT_TOKEN_SKEW_SECONDS,
  65. transport: httpx.AsyncBaseTransport | None = None) -> None:
  66. self.credentials, self.timeout, self.skew_seconds = credentials, timeout, max(0, int(skew_seconds))
  67. self._transport = transport
  68. self._cached_token: CachedAccessToken | None = None
  69. self._lock = asyncio.Lock()
  70. @classmethod
  71. def from_env(cls, environ: dict[str, str] | None = None, **kwargs: Any) -> MicrosoftGraphTokenProvider:
  72. return cls(GraphCredentials.from_env(environ), **kwargs)
  73. def clear_cache(self) -> None:
  74. self._cached_token = None
  75. def inspect_token_health(self) -> dict[str, Any]:
  76. cached, creds = self._cached_token, self.credentials
  77. return {"configured": True, "tenant_id": creds.tenant_id, "client_id": creds.client_id,
  78. "scope": creds.scope, "authority_url": creds.authority_url, "token_url": creds.token_url,
  79. "cached": bool(cached), "expires_in_seconds": cached.expires_in_seconds if cached else None,
  80. "is_expired": cached.is_expired(skew_seconds=0) if cached else None,
  81. "refresh_skew_seconds": self.skew_seconds}
  82. def _fresh_cached(self) -> CachedAccessToken | None:
  83. """The cached token unless it expires within ``skew_seconds``."""
  84. cached = self._cached_token
  85. return cached if cached and not cached.is_expired(skew_seconds=self.skew_seconds) else None
  86. async def get_access_token(self, *, force_refresh: bool = False) -> str:
  87. # Double-checked under the lock so concurrent callers share one fetch.
  88. if not force_refresh and (cached := self._fresh_cached()):
  89. return cached.access_token
  90. async with self._lock:
  91. if not force_refresh and (cached := self._fresh_cached()):
  92. return cached.access_token
  93. self._cached_token = await self._fetch_access_token()
  94. return self._cached_token.access_token
  95. async def _fetch_access_token(self) -> CachedAccessToken:
  96. data = {"grant_type": "client_credentials", "client_id": self.credentials.client_id,
  97. "client_secret": self.credentials.client_secret, "scope": self.credentials.scope}
  98. async with httpx.AsyncClient(timeout=httpx.Timeout(self.timeout), transport=self._transport) as client:
  99. response = await client.post(self.credentials.token_url, data=data,
  100. headers={"Content-Type": "application/x-www-form-urlencoded"})
  101. if response.status_code >= 400:
  102. raise MicrosoftGraphTokenError("Microsoft Graph token request failed with HTTP "
  103. f"{response.status_code}: {_extract_error_detail(response)}")
  104. try:
  105. payload = response.json()
  106. except ValueError as exc:
  107. raise MicrosoftGraphTokenError("Microsoft Graph token response was not valid JSON.") from exc
  108. access_token = str(payload.get("access_token") or "").strip()
  109. if not access_token:
  110. raise MicrosoftGraphTokenError("Microsoft Graph token response did not include access_token.")
  111. try:
  112. expires_in_seconds = int(payload.get("expires_in"))
  113. except (TypeError, ValueError) as exc:
  114. raise MicrosoftGraphTokenError(
  115. "Microsoft Graph token response did not include a valid expires_in.") from exc
  116. return CachedAccessToken(access_token, time.time() + max(0, expires_in_seconds),
  117. str(payload.get("token_type") or "Bearer").strip() or "Bearer")
  118. def _extract_error_detail(response: httpx.Response) -> str:
  119. """Best human-readable detail from a token-endpoint error body: ``error_description``,
  120. then the Graph-style ``error`` object/string, then a bare ``code``, then raw text."""
  121. try:
  122. payload = response.json()
  123. except ValueError:
  124. return response.text.strip() or "unknown error"
  125. if not isinstance(payload, dict):
  126. return str(payload)
  127. if isinstance(payload.get("error_description"), str):
  128. return payload["error_description"]
  129. error = payload.get("error")
  130. detail = format_graph_error(error)
  131. if detail is not None:
  132. return detail
  133. return str(error["code"]) if isinstance(error, dict) and error.get("code") else str(payload)