Source code for s365b.setup.devicecode

"""OAuth 2.0 device authorisation grant against Entra ID.

Implemented directly on ``httpx`` (two endpoints) so polling is async and
the flow state can live in the database between UI requests.
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import UTC, datetime, timedelta

import httpx

[docs] LOGIN = "https://login.microsoftonline.com"
# Microsoft Graph Command Line Tools: Microsoft's first-party public client, # already present in most tenants. Overridable in the setup options.
[docs] DEFAULT_PUBLIC_CLIENT_ID = "14d82eec-204b-4c2f-b7e8-296a70dab67e"
[docs] SETUP_SCOPES = ( "https://graph.microsoft.com/Application.ReadWrite.All", "https://graph.microsoft.com/AppRoleAssignment.ReadWrite.All", "https://graph.microsoft.com/DelegatedPermissionGrant.ReadWrite.All", "https://graph.microsoft.com/User.Read", )
_GRANT = "urn:ietf:params:oauth:grant-type:device_code" # AADSTS codes worth explaining in plain words. _HINTS = { 53003: ( "Conditional Access blocked the sign-in. Many tenants block device code" " sign-in; exclude this admin from that policy for a few minutes, or use" " manual setup." ), 50076: "Multi-factor authentication is required; finish it in the browser and try again.", 65001: "Consent was not given for the requested permissions.", 7000218: "The public client is not allowed to use device code sign-in in this tenant.", }
[docs] class DeviceCodeError(Exception): """The device code flow failed. The message is safe to show. Args: code: OAuth error code (``expired_token``, ``authorization_declined``…). message: Explanation for the admin. """ def __init__(self, code: str, message: str) -> None: super().__init__(message)
[docs] self.code = code
@dataclass(frozen=True, slots=True)
[docs] class DeviceCode: """A pending device code sign-in. Attributes: device_code: Secret polling handle (keep server-side). user_code: Code the admin types at the verification URL. verification_uri: Where to type it. interval: Minimum seconds between polls. expires_at: When the code stops working. """
[docs] device_code: str
[docs] user_code: str
[docs] verification_uri: str
[docs] interval: int
[docs] expires_at: datetime
[docs] class DeviceCodeClient: """Starts and polls device code sign-ins. Args: client_id: Public client application ID. tenant: ``organizations`` (any work account) or a tenant ID. http: HTTP client (replaced in tests). """ def __init__( self, client_id: str = DEFAULT_PUBLIC_CLIENT_ID, *, tenant: str = "organizations", http: httpx.AsyncClient | None = None, ) -> None:
[docs] self.client_id = client_id
self._base = f"{LOGIN}/{tenant}/oauth2/v2.0" self._http = http or httpx.AsyncClient(timeout=30)
[docs] async def aclose(self) -> None: """Close the HTTP client.""" await self._http.aclose()
[docs] async def start(self, scopes: tuple[str, ...] = SETUP_SCOPES) -> DeviceCode: """Request a device code. Args: scopes: Delegated scopes to request. Returns: The pending sign-in. Raises: DeviceCodeError: If Entra refuses (unknown client, bad scope…). """ resp = await self._http.post( f"{self._base}/devicecode", data={"client_id": self.client_id, "scope": " ".join(scopes)}, ) data = resp.json() if resp.status_code != 200: raise _error(data) return DeviceCode( device_code=data["device_code"], user_code=data["user_code"], verification_uri=data["verification_uri"], interval=int(data.get("interval", 5)), expires_at=datetime.now(UTC) + timedelta(seconds=int(data["expires_in"])), )
[docs] async def poll(self, device_code: str) -> str | None: """Ask once whether the admin has finished signing in. Args: device_code: From :meth:`start`. Returns: The access token, or ``None`` while the sign-in is still pending. Raises: DeviceCodeError: If the sign-in was declined, expired or blocked. """ resp = await self._http.post( f"{self._base}/token", data={"grant_type": _GRANT, "client_id": self.client_id, "device_code": device_code}, ) data = resp.json() if resp.status_code == 200: return str(data["access_token"]) if data.get("error") in ("authorization_pending", "slow_down"): return None raise _error(data)
def _error(data: dict[str, object]) -> DeviceCodeError: code = str(data.get("error", "unknown_error")) codes = data.get("error_codes") or [] for c in codes if isinstance(codes, list) else []: if c in _HINTS: return DeviceCodeError(code, _HINTS[c]) if code == "expired_token": return DeviceCodeError(code, "The code expired before sign-in finished. Start again.") if code == "authorization_declined": return DeviceCodeError(code, "The sign-in was declined.") description = str(data.get("error_description", code)).split("\r\n")[0] return DeviceCodeError(code, description)