"""The "Connect tenant" step of the setup wizard.
State lives in the ``setting`` table (``setup.connect``; the device code
itself in the encrypted part), so the UI can poll and an API restart does
not lose track. Flow:
1. :func:`start` requests a device code and shows the user code.
2. The UI calls :func:`poll` every few seconds. Once the admin has signed in,
provisioning starts in the background and :func:`poll` reports its steps.
3. The result (tenant, app registrations, encrypted private keys) is stored
and Microsoft sign-in is switched on. The delegated token is then
dropped; nothing that could refresh it was ever requested.
"""
from __future__ import annotations
import asyncio
import base64
from datetime import UTC, datetime, timedelta
from typing import Literal
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from pydantic import BaseModel, Field
from sqlalchemy import select
from s365b.auth.entra import EntraSettings
from s365b.core import settings_store
from s365b.core.audit import audit
from s365b.core.logging import get_logger
from s365b.core.services import Services, app_key_context
from s365b.db.models import AppPurpose, AppRegistration, ModuleState, Tenant
from s365b.graph.auth import AuthError, StaticToken
from s365b.graph.client import GraphClient, GraphError
from s365b.setup.devicecode import DEFAULT_PUBLIC_CLIENT_ID, DeviceCodeClient, DeviceCodeError
from s365b.setup.provision import SIGNIN_SCOPES, AppPlan, Provisioner, ProvisionError
[docs]
log = get_logger(__name__)
[docs]
STEP_LABELS = {
"tenant": "Read tenant details",
"backup": "Backup app (read-only permissions)",
"restore": "Restore app (write permissions)",
"notifications": "Notifications app (sends alert email)",
"signin": "Sign-in app (Microsoft sign-in for this web UI)",
"signin_admin": "Give you the Admin role",
"store": "Store credentials (private keys stay on this server)",
"verify": "Test the Backup app's certificate sign-in",
}
[docs]
Status = Literal["idle", "waiting", "provisioning", "done", "failed"]
[docs]
class Step(BaseModel):
"""One line of the progress list."""
[docs]
status: Literal["pending", "running", "done", "failed", "skipped"] = "pending"
[docs]
class SetupOptions(settings_store.SettingsGroup):
"""Advanced wizard options.
Attributes:
public_client_id: Public client used for the device code sign-in.
Default: Microsoft Graph Command Line Tools.
"""
[docs]
public_client_id: str = DEFAULT_PUBLIC_CLIENT_ID
[docs]
class ConnectState(settings_store.SettingsGroup):
"""Progress of the "Connect tenant" step, as shown in the wizard."""
[docs]
status: Status = "idle"
[docs]
verification_uri: str = ""
[docs]
expires_at: datetime | None = None
[docs]
next_poll_at: datetime | None = None
[docs]
steps: list[Step] = Field(default_factory=list)
_lock = asyncio.Lock()
_tasks: set[asyncio.Task[None]] = set()
[docs]
def plans(
services: Services,
enabled: dict[str, object],
base_url: str,
current_certs: dict[AppPurpose, str] | None = None,
) -> list[AppPlan]:
"""Work out which apps to create and what each may do.
Args:
services: Process services (module registry).
enabled: Parsed configs of the enabled modules, by module ID.
base_url: Public URL of this server.
current_certs: Base64 DER of each app's certificate in use now, kept
registered during rotation.
Returns:
Plans for the Backup, Restore and Sign-in apps.
"""
reg = services.registry
backup = reg.required_permissions(enabled, restore=False) # type: ignore[arg-type]
restore = reg.required_permissions(enabled, restore=True) # type: ignore[arg-type]
prev = current_certs or {}
return [
AppPlan(
AppPurpose.BACKUP,
app_permissions=frozenset(backup),
previous_certificate=prev.get(AppPurpose.BACKUP),
),
AppPlan(
AppPurpose.RESTORE,
app_permissions=frozenset(restore),
previous_certificate=prev.get(AppPurpose.RESTORE),
),
# Sends notification email. Deliberately no Graph permission: Mail.Send
# is granted in Exchange, scoped to the sender mailbox only.
AppPlan(
AppPurpose.NOTIFICATIONS,
previous_certificate=prev.get(AppPurpose.NOTIFICATIONS),
),
AppPlan(
AppPurpose.SIGNIN,
delegated_scopes=SIGNIN_SCOPES,
redirect_uri=f"{base_url.rstrip('/')}/api/v1/auth/entra/callback",
previous_certificate=prev.get(AppPurpose.SIGNIN),
),
]
[docs]
async def current_certificates(services: Services) -> dict[AppPurpose, str]:
"""Return the stored, unexpired app certificates as base64 DER.
Args:
services: Process services.
Returns:
Certificate by app purpose.
"""
now = datetime.now(UTC)
async with services.db.session() as s:
rows = (await s.execute(select(AppRegistration))).scalars()
return {
r.purpose: base64.b64encode(
x509.load_pem_x509_certificate(r.certificate_pem.encode()).public_bytes(
serialization.Encoding.DER
)
).decode()
for r in rows
if r.certificate_pem and r.cert_not_after > now
}
[docs]
async def enabled_modules(services: Services) -> dict[str, object]:
"""Return parsed configs of the enabled, installed modules.
Args:
services: Process services.
Returns:
Config by module ID.
"""
async with services.db.session() as s:
states = (await s.execute(select(ModuleState).where(ModuleState.enabled))).scalars()
return {
st.module_id: services.registry.parse_config(st.module_id, st.config)
for st in states
if st.module_id in services.registry
}
[docs]
async def load_state(services: Services) -> ConnectState:
"""Return the current wizard state.
Args:
services: Process services.
Returns:
The state.
"""
async with services.db.session() as s:
return await settings_store.load(s, ConnectState)
async def _save(services: Services, state: ConnectState) -> None:
async with services.db.session() as s:
await settings_store.save(s, state)
def _device_client(services: Services, client_id: str) -> DeviceCodeClient:
if services.device_code_factory is not None:
client: DeviceCodeClient = services.device_code_factory(client_id)
return client
return DeviceCodeClient(client_id)
[docs]
async def start(services: Services, actor: str) -> ConnectState:
"""Request a device code for a tenant administrator.
Args:
services: Process services.
actor: Username starting the connection (for the audit log).
Returns:
The new state, with the user code to show.
Raises:
DeviceCodeError: If Entra refuses to start the flow.
RuntimeError: If provisioning is already running.
"""
async with _lock:
state = await load_state(services)
if state.status == "provisioning":
raise RuntimeError("a connection is already being set up")
async with services.db.session() as s:
options = await settings_store.load(s, SetupOptions)
client = _device_client(services, options.public_client_id)
try:
code = await client.start()
finally:
await client.aclose()
state = ConnectState(
status="waiting",
user_code=code.user_code,
verification_uri=code.verification_uri,
expires_at=code.expires_at,
interval=code.interval,
next_poll_at=datetime.now(UTC) + timedelta(seconds=code.interval),
started_by=actor,
steps=[Step(key=k, label=v) for k, v in STEP_LABELS.items()],
)
async with services.db.session() as s:
await settings_store.save(s, state)
await settings_store.save_secrets(
s,
ConnectState.key,
{"device_code": code.device_code, "client_id": options.public_client_id},
services.secrets,
)
await audit(s, actor, "setup.tenant.start")
return state
[docs]
async def cancel(services: Services) -> ConnectState:
"""Abandon a pending sign-in (not a running provisioning).
Args:
services: Process services.
Returns:
The reset state.
"""
async with _lock:
state = await load_state(services)
if state.status != "provisioning":
state = ConnectState()
async with services.db.session() as s:
await settings_store.save(s, state)
await settings_store.save_secrets(s, ConnectState.key, {}, services.secrets)
return state
[docs]
async def poll(services: Services) -> ConnectState:
"""Advance the flow: check the sign-in, or report provisioning progress.
Args:
services: Process services.
Returns:
The current state.
"""
async with _lock:
state = await load_state(services)
now = datetime.now(UTC)
if state.status != "waiting" or (state.next_poll_at and now < state.next_poll_at):
return state
if state.expires_at and now >= state.expires_at:
state.status, state.message = "failed", "The code expired. Start again."
await _save(services, state)
return state
async with services.db.session() as s:
secrets = await settings_store.load_secrets(s, ConnectState.key, services.secrets)
client = _device_client(services, secrets.get("client_id", DEFAULT_PUBLIC_CLIENT_ID))
try:
token = await client.poll(secrets.get("device_code", ""))
except DeviceCodeError as exc:
state.status, state.message = "failed", str(exc)
await _save(services, state)
return state
finally:
await client.aclose()
if token is None:
state.next_poll_at = now + timedelta(seconds=state.interval)
await _save(services, state)
return state
state.status, state.message = "provisioning", ""
await _save(services, state)
async with services.db.session() as s:
await settings_store.save_secrets(s, ConnectState.key, {}, services.secrets)
task = asyncio.create_task(_provision(services, token))
_tasks.add(task)
task.add_done_callback(_tasks.discard)
return state
[docs]
INTERRUPTED = (
"Interrupted: the server restarted while setting up. Start again: apps already "
"created in Microsoft Entra are found and reused."
)
[docs]
async def recover_interrupted(services: Services) -> bool:
"""At startup: end a provisioning the previous server process was running.
Provisioning runs inside the API process; after a restart nothing is
working on it any more, and the wizard would wait forever.
Args:
services: Process services.
Returns:
Whether a provisioning was marked interrupted.
"""
async with _lock:
state = await load_state(services)
if state.status != "provisioning" or _tasks:
return False
state.status, state.message = "failed", INTERRUPTED
for step in state.steps:
if step.status == "running":
step.status = "failed"
await _save(services, state)
return True
[docs]
async def wait_for_provisioning() -> None:
"""Wait for background provisioning to finish (tests, shutdown)."""
if _tasks:
await asyncio.gather(*_tasks, return_exceptions=True)
async def _provision(services: Services, token: str) -> None:
"""Run the provisioner with the delegated token, then store the result."""
state = await load_state(services)
async def report(key: str, status: str, detail: str) -> None:
"""Record one step's progress."""
for step in state.steps:
if step.key == key:
step.status, step.detail = status, detail # type: ignore[assignment]
await _save(services, state)
try:
enabled = await enabled_modules(services)
async with GraphClient(StaticToken(token)) as graph:
result = await Provisioner(graph, report).run(
plans(
services,
enabled,
services.settings.base_url,
await current_certificates(services),
)
)
state.admin_upn = result.admin_upn
await report("store", "running", "")
async with services.db.session() as s:
tenant = (
await s.execute(select(Tenant).where(Tenant.tenant_id == result.tenant_id))
).scalar_one_or_none()
if tenant is None:
tenant = Tenant(tenant_id=result.tenant_id)
s.add(tenant)
tenant.display_name = result.tenant_name
tenant.default_domain = result.default_domain
await s.flush()
stored: dict[AppPurpose, AppRegistration] = {}
for purpose, app in result.apps.items():
row = (
await s.execute(
select(AppRegistration).where(
AppRegistration.tenant_fk == tenant.id,
AppRegistration.purpose == purpose,
)
)
).scalar_one_or_none()
if row is None:
row = AppRegistration(tenant_fk=tenant.id, purpose=purpose, private_key_enc="")
s.add(row)
row.client_id = app.client_id
row.object_id = app.object_id
row.cert_thumbprint = app.certificate.thumbprint
row.cert_not_after = app.certificate.not_after
row.certificate_pem = app.certificate.certificate_pem
row.granted_permissions = app.permissions
row.sp_object_id = app.service_principal_id
row.private_key_enc = "pending"
await s.flush()
row.private_key_enc = services.secrets.encrypt(
app.certificate.private_key_pem.encode(), app_key_context(row)
)
stored[purpose] = row
if AppPurpose.SIGNIN in result.apps:
await settings_store.save(
s,
EntraSettings(
enabled=True,
tenant_id=result.tenant_id,
client_id=result.apps[AppPurpose.SIGNIN].client_id,
credential="certificate",
),
)
await audit(
s,
state.started_by,
"setup.tenant.connected",
target=result.tenant_id,
details={
"admin": result.admin_upn,
"apps": {p.value: a.client_id for p, a in result.apps.items()},
},
)
await report("store", "done", "Saved")
await report("verify", "running", "Waiting for Entra to accept the new certificate")
await _verify(services, tenant, stored[AppPurpose.BACKUP])
await report("verify", "done", "Signed in as the Backup app")
state.status, state.message = "done", f"Connected to {result.tenant_name}."
except (GraphError, ProvisionError, AuthError) as exc:
log.warning("setup.provision_failed", error=str(exc))
for step in state.steps:
if step.status == "running":
step.status, step.detail = "failed", str(exc)
state.status = "failed"
state.message = _explain(exc)
except Exception as exc: # keep the wizard usable whatever happened
log.exception("setup.provision_crashed")
state.status, state.message = "failed", f"Unexpected error: {exc}"
await _save(services, state)
async def _verify(services: Services, tenant: Tenant, app: AppRegistration) -> None:
"""Get an app-only token with the new certificate, allowing for replication delay."""
delay = 5.0
for attempt in range(8):
try:
await services.credential_for(tenant, app).get_token(force_refresh=True)
return
except AuthError:
if attempt == 7:
raise
await asyncio.sleep(delay)
delay = min(delay * 1.5, 30)
def _explain(exc: Exception) -> str:
if isinstance(exc, GraphError) and exc.status == 403:
return (
"Microsoft 365 refused the change. Sign in with a Global Administrator,"
" or a Privileged Role Administrator who is also an Application Administrator."
)
return str(exc)