"""Day-to-day sign-in with Entra ID (OpenID Connect, authorisation code + PKCE).
The sign-in app registration (created by the setup wizard, or entered
manually) defines **app roles**; assigning users or groups to those roles in
Entra decides who may sign in and with what role:
========================= =========================
App role value Mail Safehouse role
========================= =========================
``S365B.Admin`` admin
``S365B.Operator`` operator
``S365B.RestoreOperator`` restore_operator
``S365B.Auditor`` auditor
========================= =========================
A user with none of these roles is refused. With several, the most
privileged wins. Roles are re-read at every sign-in.
MSAL handles state, nonce and PKCE, and validates the ID token's issuer,
audience, expiry and nonce. The token comes straight from the token endpoint
over TLS (back channel), so its signature does not need separate checking.
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from typing import Any, Literal
import msal
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from s365b.core.settings_store import SettingsGroup
from s365b.db.models import UserRole
[docs]
ROLE_CLAIMS: dict[str, UserRole] = {
"S365B.Admin": UserRole.ADMIN,
"S365B.Operator": UserRole.OPERATOR,
"S365B.RestoreOperator": UserRole.RESTORE_OPERATOR,
"S365B.Auditor": UserRole.AUDITOR,
}
[docs]
ROLE_PRIORITY = [UserRole.ADMIN, UserRole.OPERATOR, UserRole.RESTORE_OPERATOR, UserRole.AUDITOR]
[docs]
class EntraLoginError(Exception):
"""Entra sign-in failed. The message is safe to show."""
[docs]
class EntraSettings(SettingsGroup):
"""Entra sign-in configuration (non-secret part).
Attributes:
enabled: Show "Sign in with Microsoft" and accept Entra sign-ins.
tenant_id: Entra tenant ID users sign in from.
client_id: Application ID of the sign-in app registration.
credential: ``certificate`` (wizard-created app, key held by the
server) or ``secret`` (client secret entered manually).
"""
[docs]
credential: Literal["certificate", "secret"] = "certificate"
[docs]
def role_from_claims(claims: dict[str, Any]) -> UserRole | None:
"""Pick the user's role from the ID token ``roles`` claim.
Args:
claims: Validated ID token claims.
Returns:
The most privileged mapped role, or ``None`` if none is assigned.
"""
granted = {ROLE_CLAIMS[r] for r in claims.get("roles", []) if r in ROLE_CLAIMS}
return next((r for r in ROLE_PRIORITY if r in granted), None)
[docs]
def certificate_credential(private_key_pem: str, certificate_pem: str) -> dict[str, str]:
"""Build an MSAL client credential from a certificate.
Args:
private_key_pem: PEM private key.
certificate_pem: PEM certificate.
Returns:
The credential dict MSAL expects.
"""
cert = x509.load_pem_x509_certificate(certificate_pem.encode())
return {
"private_key": private_key_pem,
"thumbprint": cert.fingerprint(hashes.SHA1()).hex(), # noqa: S303 - Entra x5t is SHA-1
"public_certificate": certificate_pem,
}
[docs]
AppFactory = Callable[..., Any]
[docs]
class EntraLogin:
"""Runs the OIDC authorisation code flow through MSAL.
Args:
tenant_id: Entra tenant ID.
client_id: Sign-in app's application ID.
credential: Client secret string or certificate credential dict.
app_factory: MSAL app class (replaced in tests).
"""
def __init__(
self,
tenant_id: str,
client_id: str,
credential: str | dict[str, str],
*,
app_factory: AppFactory = msal.ConfidentialClientApplication,
) -> None:
[docs]
self.tenant_id = tenant_id
self._client_id = client_id
self._credential = credential
self._factory = app_factory
def _make(self) -> Any:
return self._factory(
self._client_id,
authority=f"https://login.microsoftonline.com/{self.tenant_id}",
client_credential=self._credential,
)
[docs]
async def start(self, redirect_uri: str) -> dict[str, Any]:
"""Begin a sign-in.
Args:
redirect_uri: The callback URL registered on the app.
Returns:
The MSAL flow: ``auth_uri`` to redirect the browser to, plus
state/PKCE data to keep (encrypted) until the callback.
Raises:
EntraLoginError: If Entra cannot be reached.
"""
def run() -> dict[str, Any]:
"""Call MSAL (blocking)."""
flow: dict[str, Any] = self._make().initiate_auth_code_flow(
scopes=[], redirect_uri=redirect_uri, response_mode="query"
)
return flow
try:
return await asyncio.to_thread(run)
except ValueError as exc: # MSAL discovery failure
raise EntraLoginError(f"cannot reach Microsoft sign-in: {exc}") from exc
[docs]
async def finish(self, flow: dict[str, Any], params: dict[str, str]) -> dict[str, Any]:
"""Complete a sign-in from the callback's query parameters.
Args:
flow: The flow returned by :meth:`start`.
params: Query parameters Entra sent to the callback.
Returns:
Validated ID token claims.
Raises:
EntraLoginError: If Entra reports an error, the state does not
match, or the user is from another tenant.
"""
if "error" in params:
raise EntraLoginError(params.get("error_description") or params["error"])
def run() -> dict[str, Any]:
"""Call MSAL (blocking)."""
result: dict[str, Any] = self._make().acquire_token_by_auth_code_flow(flow, params)
return result
try:
result = await asyncio.to_thread(run)
except ValueError as exc: # state mismatch, discovery failure
raise EntraLoginError(f"sign-in could not be completed: {exc}") from exc
if "error" in result:
raise EntraLoginError(result.get("error_description") or result["error"])
claims: dict[str, Any] = result.get("id_token_claims") or {}
if claims.get("tid") != self.tenant_id:
raise EntraLoginError("this account belongs to a different Microsoft 365 tenant")
if not claims.get("oid"):
raise EntraLoginError("the sign-in response did not identify the user")
return claims