Module system

Each Microsoft 365 workload is a module: a Python package that implements one interface. The core never contains workload-specific code; it only calls the interface.

The module contract (draft)

class BackupModule(abc.ABC):
    """A backup workload such as Exchange or Entra ID."""

    id: ClassVar[str]                    # "exchange"
    display_name: ClassVar[str]          # "Exchange Online"
    version: ClassVar[str]               # module version, stored with each backup
    config_model: ClassVar[type[BaseModel]]  # module settings, rendered as a UI form

    def required_permissions(self, config, *, restore: bool) -> set[GraphPermission]:
        """Graph application permissions this module needs."""

    async def discover(self, ctx: ModuleContext) -> AsyncIterator[ProtectedObject]:
        """List objects that can be protected (mailboxes, sites, the tenant…)."""

    async def backup(self, ctx: ModuleContext, obj: ProtectedObject,
                     state: SyncState) -> AsyncIterator[ItemVersion]:
        """Yield new/changed/deleted items since `state`; update `state`."""

    async def restore(self, ctx: ModuleContext, request: RestoreRequest) -> RestoreResult:
        """Write items back to Microsoft 365 (original or alternate target)."""

    async def export(self, config: BaseModel, request: ExportRequest) -> AsyncIterator[ExportFile]:
        """Produce portable files (EML, ICS, JSON, original files) from stored items only."""

    def item_types(self) -> list[ItemTypeInfo]:
        """Describe item types for the browse UI (icons, columns, preview)."""

    def event_types(self) -> list[EventType]:
        """Module-specific notification events (e.g. CA policy changed)."""

    async def health_check(self, ctx: ModuleContext) -> HealthReport:
        """Check permissions and connectivity for this module."""

ModuleContext gives a module everything it may use: the Graph client, the repository writer, a logger, a cancellation token and progress reporting. Modules do not open their own database connections or storage handles.

Registration, enable and disable

  • Modules register through a Python entry point group, s365b.modules. Built-in modules are registered the same way as third-party ones, so a new module can ship as a separate package.

  • Two layers of control:

    1. Installed/allowed: S365B_MODULES=exchange,onedrive,entra in the environment (default: all installed). A module not listed is never imported. Use this to lock down what an instance can do.

    2. Enabled: a toggle per allowed module in the UI (stored in the DB).

  • When a module is disabled: no discovery, no scheduled jobs, its permission requirements drop out of the “required permissions” report, and its existing backups stay read-only browsable/restorable until retention removes them.

  • The setup page lists the union of Graph permissions for the enabled modules, so the app registration only needs what is actually used.

Planned modules

entra — Entra ID (built first, see Roadmap)

  • Objects: users, groups and memberships, administrative units, applications, service principals and app role assignments, directory role assignments (and PIM eligibility), Conditional Access policies, named locations, authentication methods policy, authorization policy, cross-tenant access settings, domains.

  • Method: full snapshot each run (directory data is small); objects stored as normalized JSON, deduplicated so unchanged objects cost nothing.

  • Built (backup): each category is a protected object, so a job can pick categories and one failing category does not fail the others:

    Category

    Contents

    Users

    profile, licences, manager, on-prem sync attributes

    Groups

    settings, members, owners

    Administrative units

    settings, members

    App registrations

    full object (credential metadata only), owners

    Enterprise apps and consents

    service principals, app role assignments, delegated grants

    Directory roles

    assignments, PIM eligibility, custom role definitions

    Conditional Access

    policies, named locations, custom authentication strengths

    Tenant policies

    authorization, authentication methods, security defaults, admin consent, cross-tenant access

    Organization and domains

    company info, domains

    Features the tenant is not licensed for (e.g. PIM without Entra ID P2) are skipped, and their earlier backups are not marked deleted. A missing permission fails only that category, with a hint to re-run Connect tenant. Members are stored as sorted ID lists, so reordering is not a change. Restore is not built yet, so the Restore app gets no Entra permissions until it is.

  • Restore: restore deleted objects from the Entra recycle bin where still possible; otherwise recreate. Property-level restore (patch selected attributes). Snapshot diff view (“what changed in Conditional Access since Tuesday”).

  • Limits: passwords and credentials secrets cannot be restored; recreated objects get new object IDs, so references are remapped.

  • Permissions: Directory.Read.All, Policy.Read.All, Application.Read.All, RoleManagement.Read.Directory, AuditLog.Read.All (optional); write equivalents for restore.

exchange — Exchange Online

  • Objects: user, shared and resource mailboxes.

  • Items: mail (full MIME via /messages/{id}/$value), folders, calendar events, contacts, To Do tasks, mailbox settings.

  • Method: per-folder delta queries for messages; per-folder listings compared with the catalog for events and contacts (Graph v1.0 has no change feed for every calendar).

  • Built (mail backup): one protected object per mailbox (user and shared; rooms and equipment optional). Discovery reads each user’s mailboxSettings.userPurpose, so unlicensed users and guests are left out. Each message is stored as its original MIME (an .eml file). Incremental runs use one delta query per folder and download only new and changed messages; an interrupted first sync resumes from the last page. Graph is asked for immutable IDs, so a message moved between folders becomes a new version in the new folder rather than a deletion and a new item; a delta “removal” is checked and counts as a deletion only if the message is gone or now in a folder that is not backed up. Renamed, moved or removed folders are applied to every message in them with the SDK’s GroupChange. Settings: shared mailboxes (on), room and equipment mailboxes (off), Junk Email (off), Deleted Items (on). Browse backups shows a message’s headers, text and attachment list, converted on the server (HTML is shown as text, so nothing in a message runs or loads in the browser), and offers the .eml download. Each message also gets a restore copy, Exchange’s own full-fidelity export of it, fetched after each mailbox’s backup for every message that has none (ADR 0009: Restore mail from Exchange’s own export, kept beside the .eml). Backup needs User.Read.All, Mail.Read, MailboxSettings.Read and MailboxItem.Export.All.

  • Built (calendars and contacts): each mailbox’s own calendars (calendars other people share with it are theirs to back up) and its contact folders, as Graph’s JSON, browsable under “Calendar”, “Holidays”, “Contacts/Family” and so on. Each folder is listed with only IDs and change keys; only new or changed items are fetched in full, and a folder’s first backup lists full items. Immutable IDs make a move between folders a new version, not a deletion; an item missing from its folder counts as deleted only if it is in none of the folders backed up. Calendar and contact folders that are renamed or removed are applied with GroupChange, like mail folders. Events and contacts get restore copies like messages. Settings: Calendars (on), Contacts (on), which add Calendars.Read and Contacts.Read to the Backup app (run Update permissions after upgrading). Limits: a recurring meeting is stored as its series (Graph’s seriesMaster); changed or cancelled single occurrences and attachments are only in the restore copy, not the JSON. Restore imports their restore copies into calendars and contact folders (see Restore); events download as .ics and contacts as .vcf (see Export).

  • Built (tasks): each mailbox’s own Microsoft To Do lists, with their tasks and checklist steps, as Graph’s JSON, browsable by list name. Read with the To Do API, which grants reading (Tasks.Read.All, setting “Tasks”, on) but not writing to an application; every run lists all tasks and the catalog keeps only what changed. Left out: “Flagged email” (it mirrors flagged messages, which are backed up as mail) and lists shared by other people. Shared, room and equipment mailboxes without To Do are skipped quietly. Restore uses the restore copy, like events. To Do gives a task moved to another list a new ID, so a move shows as a deletion from the old list and a new task in the other one. If Graph refuses to return checklist steps with the tasks, they are read task by task.

  • Folder paths: folders are browsed and restored by path, their names joined with /. A / inside a folder, calendar or list name (“Projects/2026”) is stored as U+2215 DIVISION SLASH, which looks the same, so the path is not mistaken for a subfolder; restore turns it back into /. Items backed up before this get the new path at their next backup, as a rename. Known limit: a name that really contains U+2215 is restored with / instead, and “A/B” and “A∕B” side by side share one path in Browse (rare enough not to change the stored format for). OneDrive names cannot contain /, so OneDrive restores them exactly.

  • Restore: selected messages or folders, as of any point in time, into the original mailbox or another one; each restore asks whether to put them back in their original folders or in a new folder (e.g. “Restored 2026-12-03”, keeping the folder structure). Imports the restore copy with the mailbox import API, so read state, dates and flags come back as they were and nothing is a draft. Restoring into the original folders of the same mailbox skips messages still in their folder, and events, contacts and tasks still in their folder and unchanged (same change key, or for tasks the same modification time), checked with the Backup app’s read access. An event, contact or task edited since the chosen version comes back as a copy beside the current one. The Restore app needs User.Read.All, MailboxFolder.ReadWrite.All and MailboxItem.ImportExport.All. Events, contacts and tasks are restored the same way into calendars, contact folders and task folders: an event into the calendar of its name and a task into the list of its name (created under the default calendar or task folder if missing), a contact along its contact folder path. The default calendar, task folder and contacts folder are found by the names Graph gives them (the import API does not mark them). A “new folder” restore puts events in a new calendar under the default calendar, tasks in a new list under the default task folder and contacts in a new folder under the default contacts folder. Restored meetings send no invitations.

  • Export: calendar events and tasks download from Browse backups as iCalendar (.ics): one item, a calendar or To Do list, a search or a selection, as of any point in time (audited as browse.export). Events are VEVENTs in the organizer’s time zone (Windows zone names mapped to IANA, with VTIMEZONEs), so recurring meetings keep their local time across daylight saving; recurrence, attendees, reminders and categories are kept. Tasks are VTODOs with due date, status, priority, reminder and checklist steps in the description. Not included: changed or cancelled single occurrences of a series, attachments. Contacts download the same way as vCard 3.0 (.vcf, many cards in one file), which Outlook, Apple Contacts, Google Contacts and Thunderbird import: names, company, email addresses, phones, addresses, birthday, notes and categories (not photos, which are not backed up). A message downloads as its own .eml; a mail folder, search or selection as a ZIP of .eml files in their folders, streamed while it is written, so a large folder starts downloading at once (names are cut to 80 characters and made unique). Item types declare their formats (ItemTypeInfo.exports). Later: PST.

  • PST export: no maintained open-source library can write PST files (the common ones, such as libpff, only read them). Options to evaluate in a spike: (a) implement a writer from Microsoft’s published [MS-PST] specification, limited to what an export needs (folders, messages, attachments, calendar, contacts; Unicode PST only); (b) a separate export container using an existing converter, if one with a compatible licence exists. The exporter sits behind the same export() interface, so EML ships first and PST is added without changing the module.

  • Known gaps to research: Online Archive (In-Place Archive) mailboxes and Recoverable Items are not fully exposed through the standard Graph mail API; evaluate the Graph Exchange mailbox import/export API for full-fidelity and archive support. EWS is not used because Microsoft is retiring it for Exchange Online.

  • Permissions: Mail.ReadWrite, Calendars.ReadWrite, Contacts.ReadWrite, MailboxSettings.Read, Tasks.ReadWrite.All. Mailbox scope can be limited with Exchange RBAC for Applications.

onedrive — OneDrive for Business

  • Objects: each user’s drive.

  • Method: drive/root/delta; content streamed into the repository; optional capture of previous file versions; sharing permissions as metadata.

  • Restore: to original path, alternate folder or another user’s drive; export as ZIP.

  • Permissions: Files.ReadWrite.All (or Files.Read.All for backup-only).

  • Built (backup, 2026-12-05): each user with a OneDrive (guests and users whose OneDrive was never set up are left out; disabled users are kept unless turned off in the settings). The drive’s delta query lists every file at first and later only what changed; content is streamed from Graph straight into the repository and checked against the size and QuickXorHash the listing gave. A file changed while it was read fails the drive’s run, and the next run reads it again; content that does not match although the file did not change is not kept either: the run fails and names the file. The drive’s backup stops there, so a file that OneDrive always serves this way stops it on every run until someone looks at it: loud rather than a backup that quietly holds the wrong content. Checkpoints after every page of 200, so an interrupted first backup resumes. A user whose drive could not be read (other than “no OneDrive”) is still listed, so the backup reports why and the drive is not taken for gone. Needs User.Read.All and Files.Read.All.

  • Paths: delta responses leave out parentReference.path, and renaming a folder does not report what is inside it. The sync state therefore keeps every folder’s name and parent; paths are built from it (a “/” in a name is stored as a lookalike, see Exchange). A renamed or moved folder is a group change for it and each folder below it. Delta gives each item’s latest state in no promised order, so a deleted folder is deleted (with the folders still below it) only when the whole round of pages is in, and a folder moved out of it first survives; an item whose parent is not known yet has its parent chain read. A renamed or moved file is read again, but its content is the same, so the repository stores nothing new.

  • Expired delta link (or a job moved to another repository): the drive is listed again and files the catalog has that the listing lacks are recorded as deleted. A listing cut short (stopped, or the worker restarted) starts again from the beginning, since what its earlier pages listed is not kept; unchanged files are not read again.

  • Browse: files by folder, newest first; one file downloads under its own name, a folder, search or selection as a ZIP.

  • Restore (built): selected files or folders, as of any point in time, into the drive they came from or another user’s, in their original folders (created where missing) or under a new folder at the top of the drive. Content is uploaded through an upload session in 10 MiB pieces, and the modification time comes back too. A file counts as restored only when OneDrive confirms it complete at its size. A stop is honoured between files and between pieces (the unfinished upload is abandoned). Tested on a real tenant with files up to 0.5 MB; larger ones only in tests. Nothing is overwritten: a name already taken gets a number from OneDrive (“report 1.pdf”). Restoring into the original folders of the same drive skips files still in their folder with the same content tag, and files in their place (same folder and name) with the same size and content hash, such as ones restored before, which have new IDs (checked with the Backup app). The Restore app needs Files.ReadWrite.All (Microsoft’s page for upload sessions lists Sites.ReadWrite.All, but uploads through sessions work with Files.ReadWrite.All, checked on a real tenant).

  • Folders are not items: only files are backed up and listed; a folder exists in a backup through the files in it. An empty folder is therefore not backed up and cannot be restored.

  • Not yet: previous file versions (off; one global setting later, if wanted); sharing permissions.

sharepoint — SharePoint Online

  • Objects: sites (including Teams-connected and channel sites).

  • Items: document libraries (drive delta), lists and list items, site pages, site/library permissions.

  • Restore: files and list items to original or alternate site.

  • Permissions: Sites.ReadWrite.All or, preferably, Sites.Selected with per-site grants for least privilege.

teams — Microsoft Teams (later, not in v1)

Deferred because Teams is not used in the initial tenant. Kept here so the module contract stays general enough for it.

  • Objects: teams.

  • Items: team and channel settings, members and owners, tabs, channel messages and replies (with hosted content).

  • Restore: recreate teams/channels/settings/membership; messages are restored as an export (HTML/JSON) because Graph cannot write historical messages into an existing channel.

  • Known constraints to research: channel message APIs used at scale are protected (require Microsoft approval) and may be metered (billed per message). 1:1/group chats are out of scope for v1 for the same reason.

  • Permissions: Team.ReadBasic.All, TeamSettings.Read.All, Channel.ReadBasic.All, TeamMember.Read.All, ChannelMessage.Read.All.

Testing modules

Each module ships with:

  • Unit tests against recorded Graph responses (fixtures, no tenant needed).

  • A contract test suite from the SDK that every module must pass (e.g. “an item yielded twice with no change is stored once”).

  • Optional live tests against a Microsoft 365 developer tenant, run manually or on a schedule in CI with secrets.