Source code for s365b.modules.onedrive.module

"""The OneDrive for Business backup module.

Each user's drive is one protected object. A backup runs the drive's delta
query: the first run lists every file, later runs only what changed. File
content is streamed from Graph straight into the repository, so a file's
size does not matter.

Delta responses carry no folder paths (``parentReference.path`` is left
out, and renaming a folder does not report what is inside it), so the sync
state keeps every folder's name and parent, and paths are built from it. A
renamed or moved folder is a :class:`~s365b.modules.sdk.GroupChange` for it
and each folder below it.

Delta is not a history of operations: it gives each item's latest state,
in no promised order. So a deleted folder is only noted at first; when the
whole round of pages is in, it is deleted with the folders still below it
then (a folder moved out of it meanwhile survives). A file or folder whose
parent is not known yet has its parent's chain read, so its path is never
cut short.

Downloaded content is checked against the size and QuickXorHash the delta
gave; a file that changed while it was read fails the drive's run, which
the next run reads again from the last checkpoint.

The state, for a drive::

    {"drive_id": "...", "root": "<root item ID>",
     "folders": {"<ID>": ["<name>", "<parent ID>"], ...},
     "deleting": ["<folder ID>", ...],
     "delta": "<delta link>", "next": "<next page>", "resync": true}
"""

from __future__ import annotations

from collections.abc import AsyncIterator
from datetime import datetime
from typing import Any, ClassVar

from pydantic import BaseModel, Field

from s365b.graph.client import BatchRequest, DeltaExpiredError, GraphError
from s365b.modules.onedrive.quickxor import QuickXorHash
from s365b.modules.paths import file_path, join
from s365b.modules.sdk import (
    BackupModule,
    Checkpoint,
    Column,
    ExportFile,
    ExportRequest,
    GroupChange,
    ItemTypeInfo,
    ItemVersion,
    ModuleContext,
    ModuleError,
    NotSupportedError,
    ProtectedObject,
    RestoreRequest,
    RestoreResult,
    SyncState,
)

[docs] READ_PERMISSIONS = frozenset({"User.Read.All", "Files.Read.All"})
[docs] RESTORE_PERMISSIONS = frozenset({"Files.ReadWrite.All"})
[docs] ITEM_TYPE = "file"
[docs] PAGE = {"Prefer": "odata.maxpagesize=200"}
[docs] NO_DRIVE = ("itemNotFound", "ResourceNotFound", "MysiteNotFound", "notFound")
[docs] Folders = dict[str, list[str]] # ID → [name, parent ID]
[docs] class OneDriveConfig(BaseModel): """OneDrive module settings."""
[docs] include_disabled_users: bool = Field( True, title="Disabled users", description="Back up the drives of users who can no longer sign in.", )
[docs] def path_of(folders: Folders, root: str, fid: str) -> str: """The path of a folder, from the drive's root ("" for the root). Args: folders: Known folders. root: The root item's ID. fid: The folder. Returns: Folder names joined with ``/``; an unknown parent ends the path. """ names: list[str] = [] seen: set[str] = set() while fid and fid != root and fid in folders and fid not in seen: seen.add(fid) name, fid = folders[fid] names.append(name) path = "" for name in reversed(names): path = join(path, name) return path
[docs] def below(folders: Folders, fid: str) -> list[str]: """A folder and every folder inside it, outermost first. Args: folders: Known folders. fid: The folder. Returns: Folder IDs. """ children: dict[str, list[str]] = {} for f, (_, parent) in folders.items(): children.setdefault(parent, []).append(f) out, queue = [], [fid] while queue: f = queue.pop(0) if f in out: continue out.append(f) queue.extend(sorted(children.get(f, []))) return out
def _when(value: str | None) -> datetime | None: if not value: return None try: return datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None
[docs] def file_metadata(item: dict[str, Any], parent: str) -> dict[str, Any]: """Pick the fields shown and compared for a file. Args: item: The drive item from Graph. parent: Its folder's ID. Returns: Metadata for the item version. """ file = item.get("file") or {} by = ((item.get("lastModifiedBy") or {}).get("user") or {}).get("displayName") meta: dict[str, Any] = { "folder_id": parent, "modified": item.get("lastModifiedDateTime"), "modified_by": by or "", "mime_type": file.get("mimeType") or "", } if ctag := item.get("cTag"): meta["ctag"] = ctag if digest := (file.get("hashes") or {}).get("quickXorHash"): meta["quick_xor_hash"] = digest return meta
[docs] class OneDriveModule(BackupModule): """Backs up the files in users' OneDrive for Business drives."""
[docs] id: ClassVar[str] = "onedrive"
[docs] display_name: ClassVar[str] = "OneDrive"
[docs] description: ClassVar[str] = "Files and folders in each user's OneDrive for Business."
[docs] version: ClassVar[str] = "1.0.0"
[docs] config_model: ClassVar[type[BaseModel]] = OneDriveConfig
[docs] object_noun: ClassVar[tuple[str, str]] = ("drive", "drives")
# Graph throttles OneDrive per tenant and app rather than per drive.
[docs] parallel_objects: ClassVar[int] = 2
[docs] def required_permissions(self, config: BaseModel, *, restore: bool) -> set[str]: """Return the Graph application permissions needed. Args: config: Module settings. restore: True for the Restore app. Returns: Reading users and every drive's files; writing files to restore. """ return set(RESTORE_PERMISSIONS) if restore else set(READ_PERMISSIONS)
[docs] async def restore(self, ctx: ModuleContext, request: RestoreRequest) -> RestoreResult: """Upload files into a drive. See :func:`s365b.modules.onedrive.restore.restore_files` for the options. Args: ctx: Module context (Restore app). request: Files and where to put them. Returns: The outcome. """ from s365b.modules.onedrive.restore import restore_files return await restore_files(ctx, request)
[docs] def item_types(self) -> list[ItemTypeInfo]: """Describe the item types. Returns: Files. """ return [ ItemTypeInfo( id=ITEM_TYPE, label="File", icon="file", columns=( Column("modified", "Modified", "datetime"), Column("modified_by", "Modified by"), ), media_type="application/octet-stream", extension="", exports=("zip",), ) ]
[docs] async def export(self, config: BaseModel, request: ExportRequest) -> AsyncIterator[ExportFile]: """Files in their folders, for a ZIP archive. Args: config: Module settings. request: The files. Yields: Each file, read when it is written. Raises: NotSupportedError: For a format other than ``zip``. """ if request.format != "zip": raise NotSupportedError(f"OneDrive does not export to {request.format}") taken: set[str] = set() for item in request.items: v = item.version yield ExportFile(file_path(v.path, v.name or "file", "", taken), item.read())
[docs] def state_for_new_repository(self, state: SyncState) -> SyncState: """List the drive again; keep the folders, to find deletions. Args: state: The state saved by the backup into the other repository. Returns: The state to start from. """ data = {k: v for k, v in state.data.items() if k not in ("delta", "next")} data["resync"] = True return SyncState(data)
[docs] async def discover(self, ctx: ModuleContext) -> AsyncIterator[ProtectedObject]: """Yield every user with a OneDrive. Guests and users whose OneDrive was never set up are left out. Args: ctx: Module context. Yields: Drives, by user ID. Raises: ModuleError: If users or drives cannot be read at all. """ cfg = ctx.config assert isinstance(cfg, OneDriveConfig) # noqa: S101 - set by the registry try: users = [ u async for u in ctx.graph.paginate( "/users", params={ "$select": "id,displayName,userPrincipalName,accountEnabled,userType", "$top": "999", }, ) if u.get("userType") != "Guest" and (cfg.include_disabled_users or u.get("accountEnabled", True)) ] except GraphError as exc: if exc.status == 403: raise ModuleError( f"Users could not be read ({exc}). In Microsoft 365 tenant, choose Update" " permissions." ) from exc raise responses = await ctx.graph.batch( [BatchRequest(u["id"], "GET", f"/users/{u['id']}/drive?$select=id") for u in users] ) # Only a 404 says a user has no OneDrive. A user whose drive could # not be read is still listed: the backup then reports why, and a # drive backed up before is not taken for gone. found: list[ProtectedObject] = [] denied = 0 for user, resp in zip(users, responses, strict=True): if resp.status == 404: continue if resp.status in (401, 403): denied += 1 elif resp.status != 200: ctx.log.info("onedrive.drive_unreadable", user=user["id"], status=resp.status) found.append( ProtectedObject( "drive", str(user["id"]), str(user.get("displayName") or user.get("userPrincipalName") or user["id"]), {"upn": user.get("userPrincipalName") or ""}, ) ) if denied and denied == len(users): raise ModuleError( "The Backup app may not read OneDrive. In Microsoft 365 tenant, choose Update" " permissions." ) for obj in found: yield obj
[docs] async def backup( self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState ) -> AsyncIterator[ItemVersion | GroupChange | Checkpoint]: """Back up one drive: everything at first, then what changed. Args: ctx: Module context. obj: The drive (its user's ID). state: State saved at the last checkpoint. Yields: Files, folder changes and checkpoints. Raises: ModuleError: If the drive may not be read. """ try: drive = await ctx.graph.get_json( f"/users/{obj.external_id}/drive", params={"$select": "id"} ) except GraphError as exc: if exc.status == 404 or exc.code in NO_DRIVE: ctx.log.info("onedrive.no_drive", user=obj.display_name) return if exc.status == 403: raise ModuleError( f"Access to {obj.display_name}'s OneDrive was denied ({exc}). In Microsoft" " 365 tenant, choose Update permissions." ) from exc raise drive_id = str(drive["id"]) data: dict[str, Any] = dict(state.data) if data.get("drive_id") != drive_id: data = {"drive_id": drive_id, "folders": {}} folders: Folders = {k: list(v) for k, v in (data.get("folders") or {}).items()} data["folders"] = folders def snapshot() -> SyncState: """The drive's whole state, as it is now.""" return SyncState({**data, "folders": {k: list(v) for k, v in folders.items()}}) url = f"/drives/{drive_id}/root/delta" if data.get("resync") and data.get("next"): # A full listing was cut short. Which files its earlier pages # listed is not kept, and deletions are found by what it did not # list, so it starts again (unchanged files are not read again). data["next"] = None resume = data.get("next") or data.get("delta") seen: set[str] = set() try: pages = ctx.graph.delta(url, delta_link=resume, headers=PAGE) async for page in _restart_if_expired(ctx, pages, url, data, resume): ctx.check_cancelled() await _learn_parents(ctx, drive_id, page.items, folders, data) for record in self._page(ctx, drive_id, page.items, folders, data, seen): yield record if page.delta_link: for change in _apply_deletions(folders, data): yield change data["delta"], data["next"] = page.delta_link, None else: data["next"] = page.next_link ctx.progress(done=len(seen), message=obj.display_name, unit="items") yield Checkpoint(snapshot()) except GraphError as exc: if exc.status == 403: raise ModuleError( f"Access to {obj.display_name}'s OneDrive was denied ({exc}). In Microsoft" " 365 tenant, choose Update permissions." ) from exc raise if data.get("resync") and not data.get("next"): # A full listing does not report what was deleted meanwhile. if ctx.current_items is not None: for fid in ["", data.get("root", ""), *folders]: known = await ctx.current_items("folder_id", fid) for key in sorted(set(known) - seen): yield ItemVersion(item_key=key, item_type=ITEM_TYPE, name="", deleted=True) data.pop("resync", None) yield Checkpoint(snapshot())
def _page( self, ctx: ModuleContext, drive_id: str, items: list[dict[str, Any]], folders: Folders, data: dict[str, Any], seen: set[str], ) -> list[ItemVersion | GroupChange]: """The records for one delta page; ``folders`` is updated. Folders first, so a file's folder is known even if it comes later in the page. """ out: list[ItemVersion | GroupChange] = [] root = str(data.get("root") or "") for item in items: iid = str(item["id"]) if "root" in item: data["root"] = root = iid continue if "folder" not in item and "package" not in item and iid not in folders: continue deleting: list[str] = data.setdefault("deleting", []) if "deleted" in item or "@removed" in item: # Applied when the round is complete (see _apply_deletions). if iid in folders and iid not in deleting: deleting.append(iid) continue if iid in deleting: # back again later in the round deleting.remove(iid) parent = str((item.get("parentReference") or {}).get("id") or root) new = [str(item.get("name") or ""), parent] old = folders.get(iid) folders[iid] = new if old is not None and old != new: out.extend( GroupChange("folder_id", f, path=path_of(folders, root, f)) for f in below(folders, iid) ) for item in items: iid = str(item["id"]) if "root" in item or iid in folders or "folder" in item or "package" in item: continue seen.add(iid) if "deleted" in item or "@removed" in item: out.append(ItemVersion(item_key=iid, item_type=ITEM_TYPE, name="", deleted=True)) continue if "file" not in item: continue # e.g. a OneNote section group's metadata parent = str((item.get("parentReference") or {}).get("id") or root) meta = file_metadata(item, parent) path = path_of(folders, root, parent) name = str(item.get("name") or "") where = f"{path}/{name}".lstrip("/") out.append( ItemVersion( item_key=iid, item_type=ITEM_TYPE, name=name, path=path, modified_at=_when(item.get("lastModifiedDateTime")), metadata=meta, content=_checked(ctx, drive_id, iid, item.get("size"), meta, where), ) ) return out
def _apply_deletions(folders: Folders, data: dict[str, Any]) -> list[GroupChange]: """Delete the folders deleted this round, with the folders below them now. Args: folders: Known folders; updated. data: The drive's state; its ``deleting`` list is emptied. Returns: A deletion for each folder gone. """ out: list[GroupChange] = [] for fid in data.pop("deleting", None) or []: if fid in folders: gone = below(folders, fid) out.extend(GroupChange("folder_id", f, deleted=True) for f in gone) for f in gone: folders.pop(f, None) return out async def _learn_parents( ctx: ModuleContext, drive_id: str, items: list[dict[str, Any]], folders: Folders, data: dict[str, Any], ) -> None: """Read the folders that items name as parent but are not known yet. Delta promises no order, so a file can come before its folder. Each unknown folder, and its own unknown parents, is read once. Args: ctx: Module context. drive_id: The drive. items: One delta page. folders: Known folders; added to. data: The drive's state (its ``root`` may be learned). """ in_page = {str(i["id"]) for i in items if {"folder", "package", "root"} & i.keys()} wanted: dict[str, None] = {} for item in items: if "deleted" in item or "@removed" in item: continue parent = str((item.get("parentReference") or {}).get("id") or "") if parent and parent not in folders and parent not in in_page: wanted[parent] = None for fid in wanted: for _ in range(200): # a chain this deep is not real if not fid or fid in folders or fid == data.get("root"): break try: got = await ctx.graph.get_json( f"/drives/{drive_id}/items/{fid}", params={"$select": "id,name,parentReference,root"}, ) except GraphError as exc: if exc.status == 404: break # deleted meanwhile: the path ends here raise if "root" in got: data["root"] = fid break parent = str((got.get("parentReference") or {}).get("id") or "") folders[fid] = [str(got.get("name") or ""), parent] fid = parent async def _checked( ctx: ModuleContext, drive_id: str, iid: str, size: Any, meta: dict[str, Any], where: str ) -> AsyncIterator[bytes]: """A file's content, checked against the size and hash the delta gave. If they differ, the file's metadata is read again: changed meanwhile, the run fails and the next one reads it again with matching metadata. Unchanged, the content cannot be trusted and the run fails too, naming the file: a backup never keeps content it could not verify. Args: ctx: Module context. drive_id: The drive. iid: The file. size: Its size per the delta, if given. meta: Its metadata (``quick_xor_hash``, ``ctag``). where: Its path and name, for the error. Yields: The content. Raises: ModuleError: If the content does not match its size or hash. """ digest = meta.get("quick_xor_hash") h = QuickXorHash() n = 0 async for part in ctx.graph.stream(f"/drives/{drive_id}/items/{iid}/content"): n += len(part) h.update(part) yield part if (size is None or n == int(size)) and (not digest or h.b64digest() == digest): return now = await ctx.graph.get_json( f"/drives/{drive_id}/items/{iid}", params={"$select": "id,cTag,size,file"} ) now_digest = ((now.get("file") or {}).get("hashes") or {}).get("quickXorHash") if ( now.get("cTag") != meta.get("ctag") or now_digest != digest or (size is not None and now.get("size") != size) ): raise ModuleError( f"A file changed while it was read (item {iid}); the next backup reads it again." ) ctx.log.warning("onedrive.content_differs", item=iid, size=size, read=n) raise ModuleError( f"{where or iid}: the content OneDrive sent does not match its size or hash" f" ({n} of {size} bytes); it was not kept." ) async def _restart_if_expired( ctx: ModuleContext, pages: AsyncIterator[Any], url: str, data: dict[str, Any], resume: str | None, ) -> AsyncIterator[Any]: """Delta pages, listing the drive again if the saved link expired. A restart is marked in ``data["resync"]``: when the new listing is complete, deletions it cannot report are found by comparison. """ try: async for page in pages: yield page except DeltaExpiredError: if not resume: raise ctx.log.info("onedrive.delta_expired", url=url) data["resync"], data["next"], data["delta"] = True, None, None async for page in ctx.graph.delta(url, headers=PAGE): yield page