Source code for s365b.modules.entra.module

"""The Entra ID backup module."""

from __future__ import annotations

import asyncio
import json
from collections.abc import AsyncIterator
from typing import Any, ClassVar

from pydantic import BaseModel

from s365b.core.concurrency import all_or_cancel
from s365b.graph.client import GraphError
from s365b.modules.entra.sources import BY_ID, CATEGORIES, Item, Link, Source
from s365b.modules.sdk import (
    BackupModule,
    Checkpoint,
    Column,
    EmptyConfig,
    EventType,
    ItemTypeInfo,
    ItemVersion,
    ModuleContext,
    ModuleError,
    ProtectedObject,
    Severity,
    SyncState,
)

[docs] READ_PERMISSIONS = frozenset( { "Directory.Read.All", "Policy.Read.All", "Application.Read.All", "RoleManagement.Read.Directory", } )
# Which changes are worth an alert, by item type. Users and groups change # every day and are left out; they are still in the backup and the diff view.
[docs] CHANGE_EVENTS: dict[str, str] = { "role_assignment": "privileged_roles_changed", "role_eligibility": "privileged_roles_changed", "role_definition": "privileged_roles_changed", "ca_policy": "conditional_access_changed", "named_location": "conditional_access_changed", "authentication_strength": "conditional_access_changed", "policy": "tenant_policies_changed", "cross_tenant_partner": "tenant_policies_changed", "domain": "tenant_policies_changed", "oauth2_grant": "app_consents_changed", "application": "apps_changed", "service_principal": "apps_changed", }
def _canonical(value: Any) -> Any: """Put every list in a fixed order, at any depth. Graph returns some lists in a different order from one call to the next (a user's licence plans, an organisation's provisioned plans), and Entra's lists are sets: their order means nothing. """ if isinstance(value, dict): return {k: _canonical(v) for k, v in value.items()} if isinstance(value, list): items = [_canonical(v) for v in value] return sorted( items, key=lambda v: ( str(v.get("id", "")) if isinstance(v, dict) else "", json.dumps(v, sort_keys=True, ensure_ascii=False), ), ) return value
[docs] def normalise(item: Item) -> bytes: """Serialise an object so unchanged objects produce identical bytes. Drops OData annotations other than ``@odata.type`` (they carry request context, not data), sorts keys, and sorts lists (see :func:`_canonical`). Args: item: A Graph object. Returns: UTF-8 JSON. """ clean = {k: v for k, v in item.items() if not k.startswith("@odata.") or k == "@odata.type"} return json.dumps(_canonical(clean), sort_keys=True, indent=2, ensure_ascii=False).encode()
[docs] def unavailable(exc: GraphError) -> bool: """Whether an error means "this tenant does not have the feature". Conditional Access and PIM need Entra ID P1/P2; tenants without them get an error, which is not a backup failure. Args: exc: The Graph error. Returns: True for licence / feature-not-available errors. """ text = f"{exc.code} {exc}".lower() return exc.status in (400, 403) and any( word in text for word in ("license", "licence", "premium", "not supported for this tenant") )
[docs] def display_name(item: Item, role_names: dict[str, str]) -> str: """Choose a readable name for an item. Args: item: A Graph object. role_names: Role definition names by ID (for role assignments). Returns: A name for the browse view. """ if "roleDefinitionId" in item and "principalId" in item: principal = item.get("principal") or {} who = principal.get("userPrincipalName") or principal.get("displayName") role = role_names.get(item["roleDefinitionId"], item["roleDefinitionId"]) return f"{role}: {who or item['principalId']}" if "clientId" in item and "consentType" in item: return f"{item['clientId']} ({item['consentType']}): {item.get('scope', '').strip()}" for key in ("displayName", "userPrincipalName", "id"): if item.get(key): return str(item[key]) return "(unnamed)"
[docs] class EntraModule(BackupModule): """Backs up Entra ID (Azure AD) directory objects and policies."""
[docs] id: ClassVar[str] = "entra"
[docs] display_name: ClassVar[str] = "Entra ID"
[docs] description: ClassVar[str] = ( "Users, groups, apps, roles, Conditional Access and tenant policies." )
# 0.2.0: lists stored in a fixed order (the first run after it re-stores # objects without alerting).
[docs] version: ClassVar[str] = "0.2.0"
[docs] config_model: ClassVar[type[BaseModel]] = EmptyConfig
[docs] object_noun: ClassVar[tuple[str, str]] = ("category", "categories")
[docs] def required_permissions(self, config: BaseModel, *, restore: bool) -> set[str]: """Return the Graph application permissions needed. Args: config: Module settings (none). restore: Restore is not implemented yet, so it needs nothing. Returns: Read permissions for backup; nothing for restore. """ return set() if restore else set(READ_PERMISSIONS)
[docs] def event_types(self) -> list[EventType]: """Alerts for security-relevant directory changes. Returns: The event types. """ return [ EventType( "privileged_roles_changed", "Directory role assignments changed", Severity.WARNING ), EventType("conditional_access_changed", "Conditional Access changed", Severity.WARNING), EventType( "tenant_policies_changed", "Tenant policies or domains changed", Severity.WARNING ), EventType( "app_consents_changed", "Delegated permission grants changed", Severity.WARNING ), EventType( "apps_changed", "App registrations or enterprise apps changed", Severity.INFO ), ]
[docs] def change_event(self, item_type: str, change: str, version: ItemVersion) -> str | None: """Map a change to an alert (see ``CHANGE_EVENTS``). Args: item_type: The item's type. change: ``new``, ``changed`` or ``deleted``. version: The new version. Returns: The event ID, or ``None`` for changes that do not alert. """ return CHANGE_EVENTS.get(item_type)
[docs] def item_types(self) -> list[ItemTypeInfo]: """Describe the item types. Returns: One entry per Graph object type. """ mail = Column("mail", "Primary email address") enabled = Column("accountEnabled", "Enabled", "bool") app_id = Column("appId", "Application ID") scope = Column("directoryScopeId", "Scope") labels: dict[str, tuple[str, str, tuple[Column, ...]]] = { "user": ("User", "user", (mail, enabled)), "group": ("Group", "users", (mail, Column("groupTypes", "Group type", "list"))), "administrative_unit": ("Administrative unit", "folder", ()), "application": ("App registration", "app", (app_id,)), "service_principal": ( "Enterprise app", "app", (app_id, Column("servicePrincipalType", "Kind"), enabled), ), "oauth2_grant": ( "Delegated permission grant", "key", (Column("consentType", "Consent"), Column("scope", "Permissions")), ), "role_definition": ("Role definition", "shield", ()), "role_assignment": ("Role assignment", "shield", (scope,)), "role_eligibility": ("Eligible role assignment", "shield", (scope,)), "ca_policy": ("Conditional Access policy", "policy", (Column("state", "State"),)), "named_location": ("Named location", "globe", ()), "authentication_strength": ("Authentication strength", "key", ()), "policy": ("Tenant policy", "policy", ()), "cross_tenant_partner": ("Cross-tenant partner", "globe", ()), "organization": ("Organization", "building", ()), "domain": ( "Domain", "globe", (Column("isVerified", "Verified", "bool"), Column("isDefault", "Default", "bool")), ), } return [ ItemTypeInfo(id=k, label=label, icon=icon, columns=cols, preview=True) for k, (label, icon, cols) in labels.items() ]
[docs] async def discover(self, ctx: ModuleContext) -> AsyncIterator[ProtectedObject]: """Yield one protected object per category. Args: ctx: Module context. Yields: The categories. """ for cat in CATEGORIES: yield ProtectedObject("category", cat.id, cat.label, {"description": cat.description})
[docs] def state_for_new_repository(self, state: SyncState) -> SyncState: """Keep the state: every run reads everything, and it finds deletions. Args: state: The state saved by the backup into the other repository. Returns: The same state. """ return state
[docs] async def backup( self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState ) -> AsyncIterator[ItemVersion | Checkpoint]: """Snapshot one category. Every object is yielded each run (the catalog keeps only changed ones); objects seen last time but not now are yielded as deleted. A checkpoint follows each source. Args: ctx: Module context. obj: The category. state: ``{"seen": {source key: [item keys]}}`` from the last run. Yields: Item versions and checkpoints. Raises: ModuleError: For an unknown category or missing permissions. """ category = BY_ID.get(obj.external_id) if category is None: raise ModuleError(f"unknown Entra category {obj.external_id!r}") seen: dict[str, list[str]] = dict(state.data.get("seen", {})) role_names: dict[str, str] = {} for n, source in enumerate(category.sources): ctx.check_cancelled() ctx.progress(done=n, total=len(category.sources), message=source.label, unit="steps") try: items = await self._read(ctx, source) except GraphError as exc: if unavailable(exc): ctx.log.info("entra.source_unavailable", source=source.key, error=str(exc)) continue # keep what was seen before; nothing is marked deleted if exc.status == 403: raise ModuleError( f"{source.label}: access denied ({exc}). Re-run Connect tenant so the" " Backup app gets the Entra permissions." ) from exc raise if source.key == "role_definitions": role_names = {d["id"]: str(d.get("displayName") or d["id"]) for d in items} kept = [i for i in items if source.keep(i)] now: list[str] = [] for item in kept: key = source.key if source.singleton else str(item["id"]) now.append(key) yield ItemVersion( item_key=key, item_type=source.item_type, name=display_name(item, role_names) if not source.singleton else source.key, path=source.label, metadata={f: item[f] for f in source.meta if f in item}, content=normalise(item), ) for gone in sorted(set(seen.get(source.key, [])) - set(now)): yield ItemVersion( item_key=gone, item_type=source.item_type, name=gone, deleted=True ) seen[source.key] = sorted(now) yield Checkpoint(SyncState({"seen": dict(seen)}))
async def _read(self, ctx: ModuleContext, source: Source) -> list[Item]: if source.singleton: return [await ctx.graph.get_json(source.url)] items = [i async for i in ctx.graph.paginate(source.url, params=source.params)] if source.links: sem = asyncio.Semaphore(LINK_CONCURRENCY) async def fill(item: Item) -> None: """Fetch the item's related lists.""" async with sem: for link in source.links: if link.when(item): item[link.field] = await _related(ctx, link, item["id"]) await all_or_cancel(fill(i) for i in items if source.keep(i)) return items
async def _related(ctx: ModuleContext, link: Link, item_id: str) -> list[Any]: """Read a related list, sorted so ordering changes are not versions.""" rows = [r async for r in ctx.graph.paginate(link.url.format(id=item_id))] return sorted(rows, key=lambda r: (str(r.get("id", "")), json.dumps(r, sort_keys=True)))