Source code for s365b.graph.auth

"""App-only authentication to Microsoft Graph with a certificate.

Each app registration (Backup, Restore, Notifications) has its own
certificate whose private key never leaves the server. Tokens are cached by
MSAL and refreshed shortly before they expire.
"""

from __future__ import annotations

import asyncio
from typing import Protocol

import msal
from cryptography import x509
from cryptography.hazmat.primitives import hashes

[docs] GRAPH_SCOPE = "https://graph.microsoft.com/.default"
[docs] class AuthError(Exception): """Raised when a token cannot be obtained."""
[docs] class TokenProvider(Protocol): """Anything that can supply a bearer token for Graph."""
[docs] async def get_token(self, *, force_refresh: bool = False) -> str: """Return an access token. Args: force_refresh: Ignore any cached token (used after a 401). Returns: The access token. """ ...
[docs] class CertificateCredential: """Client-credentials flow using a certificate (no client secret). Args: tenant_id: Entra tenant ID. client_id: Application (client) ID of the app registration. private_key_pem: PEM private key matching the uploaded certificate. certificate_pem: PEM certificate uploaded to the app registration. authority_host: Login host; change only for sovereign clouds. """ def __init__( self, tenant_id: str, client_id: str, private_key_pem: str, certificate_pem: str, authority_host: str = "https://login.microsoftonline.com", ) -> None: cert = x509.load_pem_x509_certificate(certificate_pem.encode())
[docs] self.thumbprint = cert.fingerprint(hashes.SHA1()).hex() # noqa: S303 - Entra x5t uses SHA-1
[docs] self.not_after = cert.not_valid_after_utc
self._client_id = client_id self._authority = f"{authority_host}/{tenant_id}" self._credential = { "private_key": private_key_pem, "thumbprint": self.thumbprint, "public_certificate": certificate_pem, } # MSAL fetches the tenant's OpenID configuration when the app object # is created, so it is created lazily in a worker thread. self._app: msal.ConfidentialClientApplication | None = None self._lock = asyncio.Lock() def _acquire(self, force_refresh: bool) -> dict[str, object]: if self._app is None: self._app = msal.ConfidentialClientApplication( self._client_id, authority=self._authority, client_credential=self._credential ) if force_refresh: # acquire_token_for_client() rejects force_refresh (MSAL >= 1.23); # dropping the cached app token has the same effect. self._app.remove_tokens_for_client() result: dict[str, object] = self._app.acquire_token_for_client(scopes=[GRAPH_SCOPE]) return result
[docs] async def get_token(self, *, force_refresh: bool = False) -> str: """Return an access token for Microsoft Graph. Args: force_refresh: Skip MSAL's token cache. Returns: The access token. Raises: AuthError: If Entra refuses the request (wrong certificate, app deleted, consent missing…). """ async with self._lock: try: result = await asyncio.to_thread(self._acquire, force_refresh) except ValueError as exc: # MSAL reports discovery failures this way raise AuthError(str(exc)) from exc if "access_token" not in result: raise AuthError( f"{result.get('error', 'unknown_error')}: {result.get('error_description', '')}" ) return str(result["access_token"])
[docs] class StaticToken: """A fixed token, for tests and one-off scripts. Args: token: The access token to return. """ def __init__(self, token: str) -> None: self._token = token
[docs] async def get_token(self, *, force_refresh: bool = False) -> str: """Return the fixed token. Args: force_refresh: Ignored. Returns: The token. """ return self._token