"""Create or update the app registrations with a delegated admin token.
Idempotent: apps are found again by their ``s365b:<purpose>`` tag and
updated in place, so the wizard can be re-run (to add permissions for a
newly enabled module, renew certificates, or repair a half-finished run).
Entra replicates new objects between regions for a few seconds; calls that
depend on a just-created object are retried.
"""
from __future__ import annotations
import asyncio
import uuid
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass, field
from typing import Any, Literal
from s365b.auth.entra import ROLE_CLAIMS
from s365b.db.models import AppPurpose
from s365b.graph.client import GraphClient, GraphError
from s365b.setup.certs import AppCertificate, new_certificate
[docs]
GRAPH_APP_ID = "00000003-0000-0000-c000-000000000000"
[docs]
SIGNIN_SCOPES = ("openid", "profile", "email", "User.Read")
_ROLE_NS = uuid.UUID("6f7c3c1e-6a2f-4f43-9a51-3d3b1f0c5e10")
[docs]
DISPLAY_NAMES = {
AppPurpose.BACKUP: "Mail Safehouse – Backup", # noqa: RUF001
AppPurpose.RESTORE: "Mail Safehouse – Restore", # noqa: RUF001
AppPurpose.NOTIFICATIONS: "Mail Safehouse – Notifications", # noqa: RUF001
AppPurpose.SIGNIN: "Mail Safehouse – Sign-in", # noqa: RUF001
}
_ROLE_TEXT = {
"S365B.Admin": ("Administrator", "Full control, including settings and users."),
"S365B.Operator": ("Operator", "Run and manage backup jobs."),
"S365B.RestoreOperator": ("Restore operator", "Browse, restore and export backed-up data."),
"S365B.Auditor": ("Auditor", "Read-only access, including the audit log."),
}
[docs]
StepStatus = Literal["running", "done", "failed", "skipped"]
[docs]
Report = Callable[[str, StepStatus, str], Awaitable[None]]
[docs]
class ProvisionError(Exception):
"""Provisioning cannot continue. The message is safe to show."""
[docs]
def role_id(value: str) -> str:
"""Stable ID for one of the sign-in app's roles (same in every tenant).
Args:
value: App role value such as ``S365B.Admin``.
Returns:
The role's GUID.
"""
return str(uuid.uuid5(_ROLE_NS, value))
@dataclass(frozen=True, slots=True)
[docs]
class AppPlan:
"""What one app registration should look like.
Attributes:
purpose: Which app.
app_permissions: Microsoft Graph application permissions to grant.
delegated_scopes: Graph delegated scopes to consent for all users.
redirect_uri: Web redirect URI (sign-in app only).
previous_certificate: Base64 DER of the certificate in use now. It
stays registered next to the new one, so running jobs and
not-yet-replicated Entra servers keep working during rotation;
the next rotation drops it.
"""
[docs]
app_permissions: frozenset[str] = frozenset()
[docs]
delegated_scopes: tuple[str, ...] = ()
[docs]
redirect_uri: str | None = None
[docs]
previous_certificate: str | None = None
@dataclass(slots=True)
[docs]
class AppResult:
"""An app registration after provisioning.
Attributes:
purpose: Which app.
client_id: Application (client) ID.
object_id: Application object ID.
service_principal_id: Enterprise application object ID.
certificate: New credential (private key to be stored encrypted).
permissions: Graph application permissions now granted.
"""
[docs]
service_principal_id: str
[docs]
certificate: AppCertificate
@dataclass(slots=True)
[docs]
class ProvisionResult:
"""Everything the wizard needs to store.
Attributes:
tenant_id: Directory ID.
tenant_name: Organisation display name.
default_domain: Default verified domain.
admin_upn: The admin who signed in.
apps: Provisioned apps by purpose.
"""
[docs]
default_domain: str
[docs]
apps: dict[AppPurpose, AppResult] = field(default_factory=dict)
async def _retry[T](
fn: Callable[[], Awaitable[T]],
*,
sleep: Callable[[float], Awaitable[None]],
attempts: int = 8,
) -> T:
"""Retry calls that fail while Entra replicates a new object."""
for attempt in range(attempts):
try:
return await fn()
except GraphError as exc:
if exc.status not in (400, 404) or attempt == attempts - 1:
raise
await sleep(min(2**attempt, 15))
raise AssertionError("unreachable")
[docs]
class Provisioner:
"""Creates and updates app registrations in one tenant.
Args:
graph: Graph client authenticated with the admin's delegated token.
report: Async callback ``(step, status, detail)`` for progress.
sleep: Sleep function (replaced in tests).
"""
def __init__(
self,
graph: GraphClient,
report: Report,
*,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
) -> None:
self._graph_sp: dict[str, Any] = {}
[docs]
async def run(self, plans: Iterable[AppPlan]) -> ProvisionResult:
"""Provision every planned app.
Args:
plans: The apps to create or update.
Returns:
Tenant details and the provisioned apps.
Raises:
ProvisionError: If a permission is unknown or the admin lacks rights.
s365b.graph.client.GraphError: For other Graph failures.
"""
await self.report("tenant", "running", "Reading the tenant")
org = (await self.graph.get_json("organization"))["value"][0]
me = await self.graph.get_json("me", params={"$select": "id,userPrincipalName"})
domain = next((d["name"] for d in org.get("verifiedDomains", []) if d.get("isDefault")), "")
result = ProvisionResult(
tenant_id=org["id"],
tenant_name=org.get("displayName", ""),
default_domain=domain,
admin_upn=me.get("userPrincipalName", ""),
)
self._graph_sp = await self._service_principal_for(GRAPH_APP_ID)
await self.report("tenant", "done", f"{result.tenant_name} ({domain})")
for plan in plans:
name = DISPLAY_NAMES[plan.purpose]
await self.report(plan.purpose.value, "running", f"Creating {name}")
app = await self._ensure_app(plan)
await self.report(plan.purpose.value, "done", f"{name}: {app.client_id}")
result.apps[plan.purpose] = app
if plan.purpose is AppPurpose.SIGNIN:
await self.report("signin_admin", "running", "Assigning you the Admin role")
await self._assign_user_role(app.service_principal_id, me["id"], "S365B.Admin")
await self.report(
"signin_admin", "done", f"{result.admin_upn} can sign in as Admin"
)
return result
# --- lookups ------------------------------------------------------------
async def _service_principal_for(self, app_id: str) -> dict[str, Any]:
data = await self.graph.get_json(
"servicePrincipals", params={"$filter": f"appId eq '{app_id}'"}
)
if not data["value"]:
raise ProvisionError(f"service principal for {app_id} not found")
sp: dict[str, Any] = data["value"][0]
return sp
def _graph_ids(self, names: Iterable[str], kind: Literal["Role", "Scope"]) -> dict[str, str]:
"""Map Graph permission names to their IDs in this tenant."""
entries = self._graph_sp["appRoles" if kind == "Role" else "oauth2PermissionScopes"]
known = {e["value"]: e["id"] for e in entries}
missing = sorted(set(names) - known.keys())
if missing:
raise ProvisionError(f"unknown Microsoft Graph permission(s): {', '.join(missing)}")
return {n: known[n] for n in names}
async def _find_app(self, purpose: AppPurpose) -> dict[str, Any] | None:
resp = await self.graph.request(
"GET",
"applications",
params={"$filter": f"tags/any(t:t eq 's365b:{purpose.value}')", "$count": "true"},
headers={"ConsistencyLevel": "eventual"},
)
found: list[dict[str, Any]] = resp.json()["value"]
return found[0] if found else None
# --- apps ---------------------------------------------------------------
def _app_body(self, plan: AppPlan, cert: AppCertificate) -> dict[str, Any]:
access = [
{"id": i, "type": "Role"}
for i in self._graph_ids(plan.app_permissions, "Role").values()
] + [
{"id": i, "type": "Scope"}
for i in self._graph_ids(plan.delegated_scopes, "Scope").values()
]
body: dict[str, Any] = {
"displayName": DISPLAY_NAMES[plan.purpose],
"signInAudience": "AzureADMyOrg",
"tags": ["s365b", f"s365b:{plan.purpose.value}"],
"notes": "Managed by Mail Safehouse. Changes here may be overwritten.",
"requiredResourceAccess": (
[{"resourceAppId": GRAPH_APP_ID, "resourceAccess": access}] if access else []
),
"keyCredentials": [
{
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": der,
"displayName": f"CN={DISPLAY_NAMES[plan.purpose]}",
}
for der in [cert.der_base64, plan.previous_certificate]
if der
],
}
if plan.redirect_uri:
body["web"] = {
"redirectUris": [plan.redirect_uri],
"implicitGrantSettings": {
"enableIdTokenIssuance": False,
"enableAccessTokenIssuance": False,
},
}
if plan.purpose is AppPurpose.SIGNIN:
body["appRoles"] = [
{
"id": role_id(value),
"value": value,
"displayName": _ROLE_TEXT[value][0],
"description": _ROLE_TEXT[value][1],
"allowedMemberTypes": ["User"],
"isEnabled": True,
}
for value in ROLE_CLAIMS
]
return body
async def _ensure_app(self, plan: AppPlan) -> AppResult:
cert = new_certificate(DISPLAY_NAMES[plan.purpose])
body = self._app_body(plan, cert)
existing = await self._find_app(plan.purpose)
if existing:
await self.graph.request("PATCH", f"applications/{existing['id']}", json=body)
app = existing
else:
app = (
await self.graph.request("POST", "applications", json=body, idempotent=False)
).json()
sp = await _retry(
lambda: self._ensure_service_principal(app["appId"], plan), sleep=self.sleep
)
granted = await self._sync_app_permissions(sp["id"], plan.app_permissions)
if plan.delegated_scopes:
await self._grant_delegated(sp["id"], plan.delegated_scopes)
return AppResult(
purpose=plan.purpose,
client_id=app["appId"],
object_id=app["id"],
service_principal_id=sp["id"],
certificate=cert,
permissions=granted,
)
async def _ensure_service_principal(self, app_id: str, plan: AppPlan) -> dict[str, Any]:
data = await self.graph.get_json(
"servicePrincipals", params={"$filter": f"appId eq '{app_id}'"}
)
settings = {
"appRoleAssignmentRequired": plan.purpose is AppPurpose.SIGNIN,
"tags": ["WindowsAzureActiveDirectoryIntegratedApp"]
+ (["HideApp"] if plan.purpose is not AppPurpose.SIGNIN else []),
}
if data["value"]:
sp: dict[str, Any] = data["value"][0]
await self.graph.request("PATCH", f"servicePrincipals/{sp['id']}", json=settings)
return sp
created: dict[str, Any] = (
await self.graph.request(
"POST", "servicePrincipals", json={"appId": app_id, **settings}
)
).json()
return created
async def _sync_app_permissions(self, sp_id: str, wanted: frozenset[str]) -> list[str]:
"""Grant exactly ``wanted`` Graph application permissions (admin consent)."""
graph_sp = self._graph_sp["id"]
ids = self._graph_ids(wanted, "Role")
current = [
a
async for a in self.graph.paginate(f"servicePrincipals/{sp_id}/appRoleAssignments")
if a["resourceId"] == graph_sp
]
have = {a["appRoleId"] for a in current}
for _name, rid in sorted(ids.items()):
if rid not in have:
await _retry(
lambda rid=rid: self.graph.request( # type: ignore[misc]
"POST",
f"servicePrincipals/{graph_sp}/appRoleAssignedTo",
json={"principalId": sp_id, "resourceId": graph_sp, "appRoleId": rid},
),
sleep=self.sleep,
)
for a in current:
if a["appRoleId"] not in ids.values():
await self.graph.request(
"DELETE", f"servicePrincipals/{sp_id}/appRoleAssignments/{a['id']}"
)
return sorted(ids)
async def _grant_delegated(self, sp_id: str, scopes: tuple[str, ...]) -> None:
"""Consent delegated scopes for all users of the tenant."""
graph_sp = self._graph_sp["id"]
scope = " ".join(scopes)
data = await self.graph.get_json(
"oauth2PermissionGrants",
params={"$filter": f"clientId eq '{sp_id}' and resourceId eq '{graph_sp}'"},
)
if data["value"]:
grant_id = data["value"][0]["id"]
await self.graph.request(
"PATCH", f"oauth2PermissionGrants/{grant_id}", json={"scope": scope}
)
return
await _retry(
lambda: self.graph.request(
"POST",
"oauth2PermissionGrants",
json={
"clientId": sp_id,
"consentType": "AllPrincipals",
"resourceId": graph_sp,
"scope": scope,
},
),
sleep=self.sleep,
)
async def _assign_user_role(self, sp_id: str, user_id: str, value: str) -> None:
rid = role_id(value)
async for a in self.graph.paginate(f"servicePrincipals/{sp_id}/appRoleAssignedTo"):
if a["principalId"] == user_id and a["appRoleId"] == rid:
return
await _retry(
lambda: self.graph.request(
"POST",
f"servicePrincipals/{sp_id}/appRoleAssignedTo",
json={"principalId": user_id, "resourceId": sp_id, "appRoleId": rid},
),
sleep=self.sleep,
)