Source code for s365b.db.models

"""Database tables.

Groups of tables:

* **Configuration:** :class:`Tenant`, :class:`AppRegistration`,
  :class:`ModuleState`, :class:`Setting`, :class:`RepositoryConfig`,
  :class:`BackupJob`, :class:`Asset`.
* **Access:** :class:`UserAccount`, :class:`UserSession`.
* **Catalog** (what is backed up, and when): :class:`ProtectedObjectRow`,
  :class:`SyncStateRow`, :class:`Item`, :class:`ItemVersionRow`.
* **Operations:** :class:`JobRun`, :class:`Event`, :class:`AuditLog`.

Every catalog row carries a tenant reference so multi-tenant support can be
added later without changing the backup format.

Point-in-time rule: an item version is visible "as of T" when
``valid_from <= T`` and (``valid_to`` is null or ``valid_to > T``) and it is
not a deletion marker.
"""

from __future__ import annotations

import enum
from datetime import datetime
from typing import Any, ClassVar

from sqlalchemy import (
    BigInteger,
    Boolean,
    CheckConstraint,
    DateTime,
    Enum,
    ForeignKey,
    Index,
    Integer,
    LargeBinary,
    MetaData,
    String,
    Text,
    UniqueConstraint,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

[docs] NAMING = { "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s", }
[docs] JSON = dict[str, Any]
# Usernames, and every column that records who did something: one limit, so # whoever can sign in can also be recorded.
[docs] USERNAME_MAX = 256
[docs] class Base(DeclarativeBase): """Declarative base with consistent constraint names for migrations."""
[docs] metadata = MetaData(naming_convention=NAMING)
[docs] type_annotation_map: ClassVar[dict[Any, Any]] = {JSON: JSONB, datetime: DateTime(timezone=True)}
def _now() -> Any: return func.now() # --- enums ------------------------------------------------------------------
[docs] class AppPurpose(enum.StrEnum): """What an app registration is used for."""
[docs] BACKUP = "backup"
[docs] RESTORE = "restore"
[docs] NOTIFICATIONS = "notifications"
[docs] SIGNIN = "signin"
[docs] class RunKind(enum.StrEnum): """Kind of job run."""
[docs] BACKUP = "backup"
[docs] RESTORE = "restore"
[docs] EXPORT = "export"
[docs] RETENTION = "retention"
[docs] CHECK = "check"
[docs] class RunStatus(enum.StrEnum): """Lifecycle of a job run."""
[docs] QUEUED = "queued"
[docs] RUNNING = "running"
[docs] SUCCESS = "success"
[docs] WARNING = "warning"
[docs] FAILED = "failed"
[docs] CANCELLED = "cancelled"
[docs] class UserRole(enum.StrEnum): """Roles in the web UI."""
[docs] ADMIN = "admin"
[docs] OPERATOR = "operator"
[docs] RESTORE_OPERATOR = "restore_operator"
[docs] AUDITOR = "auditor"
def _enum(cls: type[enum.Enum], name: str) -> Enum: return Enum(cls, name=name, values_callable=lambda e: [m.value for m in e]) # --- configuration ----------------------------------------------------------
[docs] class Tenant(Base): """A connected Microsoft 365 tenant (one for now).""" __tablename__ = "tenant"
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] tenant_id: Mapped[str] = mapped_column(String(36), unique=True)
[docs] display_name: Mapped[str] = mapped_column(String(256), default="")
[docs] default_domain: Mapped[str] = mapped_column(String(256), default="")
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] apps: Mapped[list[AppRegistration]] = relationship(back_populates="tenant")
[docs] class AppRegistration(Base): """An Entra app registration created by the setup wizard.""" __tablename__ = "app_registration" __table_args__ = (UniqueConstraint("tenant_fk", "purpose"),)
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] tenant_fk: Mapped[int] = mapped_column(ForeignKey("tenant.id", ondelete="CASCADE"))
[docs] purpose: Mapped[AppPurpose] = mapped_column(_enum(AppPurpose, "app_purpose"))
[docs] client_id: Mapped[str] = mapped_column(String(36))
[docs] object_id: Mapped[str] = mapped_column(String(36))
[docs] cert_thumbprint: Mapped[str] = mapped_column(String(64))
[docs] cert_not_after: Mapped[datetime]
[docs] certificate_pem: Mapped[str] = mapped_column(Text)
[docs] private_key_enc: Mapped[str] = mapped_column(Text, doc="SecretBox-encrypted PEM")
[docs] granted_permissions: Mapped[list[str]] = mapped_column(JSONB, default=list)
[docs] sp_object_id: Mapped[str] = mapped_column( String(64), default="", server_default="", doc="Enterprise app (service principal) ID" )
[docs] updated_at: Mapped[datetime] = mapped_column(server_default=_now(), onupdate=_now())
[docs] tenant: Mapped[Tenant] = relationship(back_populates="apps")
[docs] class ModuleState(Base): """Whether a module is enabled, and its settings.""" __tablename__ = "module_state"
[docs] module_id: Mapped[str] = mapped_column(String(32), primary_key=True)
[docs] enabled: Mapped[bool] = mapped_column(Boolean, default=False)
[docs] config: Mapped[JSON] = mapped_column(default=dict)
[docs] updated_at: Mapped[datetime] = mapped_column(server_default=_now(), onupdate=_now())
[docs] class Setting(Base): """Key/value settings changed in the UI (e.g. ``notifications``). Secret parts of a setting go in ``secret_enc`` (SecretBox-encrypted JSON), never in ``value``. """ __tablename__ = "setting"
[docs] key: Mapped[str] = mapped_column(String(64), primary_key=True)
[docs] value: Mapped[JSON] = mapped_column(default=dict)
[docs] secret_enc: Mapped[str | None] = mapped_column(Text)
[docs] updated_at: Mapped[datetime] = mapped_column(server_default=_now(), onupdate=_now())
[docs] class RepositoryConfig(Base): """A backup repository the app writes to.""" __tablename__ = "repository"
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] name: Mapped[str] = mapped_column(String(128), unique=True)
[docs] backend: Mapped[str] = mapped_column(String(32), default="filesystem")
[docs] location: Mapped[str] = mapped_column(Text, doc="Path or bucket URL")
[docs] options: Mapped[JSON] = mapped_column(default=dict)
[docs] repo_id: Mapped[str] = mapped_column(String(32), doc="ID from the repository config file")
[docs] passphrase_enc: Mapped[str] = mapped_column( Text, doc="SecretBox-encrypted passphrase, so scheduled jobs can open it" )
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] retention: Mapped[JSON] = mapped_column( default=dict, doc='{"keep_days": int} or {} to keep forever (see jobs.retention)' )
[docs] generation: Mapped[int] = mapped_column( BigInteger, default=0, server_default="0", doc="Raised by every catalog commit of a backup; see core.generation", )
[docs] class BackupJob(Base): """A scheduled backup of selected objects of one or more modules.""" __tablename__ = "backup_job"
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] name: Mapped[str] = mapped_column(String(128), unique=True)
[docs] enabled: Mapped[bool] = mapped_column(Boolean, default=True)
[docs] schedule: Mapped[str] = mapped_column(String(64), doc="Cron expression, server time zone")
[docs] repository_fk: Mapped[int] = mapped_column(ForeignKey("repository.id"))
[docs] modules: Mapped[list[str]] = mapped_column(JSONB, default=list)
[docs] selection: Mapped[JSON] = mapped_column(default=dict, doc="Include/exclude rules per module")
[docs] retention: Mapped[JSON] = mapped_column(default=dict)
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] class AuthSource(enum.StrEnum): """Where a user account comes from."""
[docs] LOCAL = "local"
[docs] ENTRA = "entra"
[docs] class UserAccount(Base): """A web UI user. * **Entra** users are created on first sign-in; their role comes from the ``roles`` claim (app roles) at every sign-in, so removing someone in Entra takes effect at their next login. * **Local** users are the offline break-glass admins for when Microsoft 365 is unavailable. They always need a password *and* a TOTP code. """ __tablename__ = "user_account"
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] source: Mapped[AuthSource] = mapped_column(_enum(AuthSource, "auth_source"))
[docs] username: Mapped[str] = mapped_column( String(USERNAME_MAX), unique=True, doc="Lowercase; UPN for Entra" )
[docs] entra_oid: Mapped[str | None] = mapped_column(String(36), unique=True)
[docs] display_name: Mapped[str] = mapped_column(String(USERNAME_MAX), default="")
[docs] email: Mapped[str] = mapped_column(String(USERNAME_MAX), default="")
[docs] role: Mapped[UserRole | None] = mapped_column( _enum(UserRole, "user_role"), doc="Local users: fixed role. Entra: role at last sign-in" )
[docs] password_hash: Mapped[str | None] = mapped_column(Text)
[docs] totp_secret_enc: Mapped[str | None] = mapped_column(Text)
[docs] totp_confirmed: Mapped[bool] = mapped_column(Boolean, default=False)
[docs] totp_last_step: Mapped[int | None] = mapped_column( BigInteger, doc="Time step of the last accepted code; blocks replay" )
[docs] recovery_codes: Mapped[list[str]] = mapped_column(JSONB, default=list, doc="Argon2 hashes")
[docs] disabled: Mapped[bool] = mapped_column(Boolean, default=False)
[docs] failed_logins: Mapped[int] = mapped_column(Integer, default=0)
[docs] locked_until: Mapped[datetime | None]
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] last_login_at: Mapped[datetime | None]
[docs] class UserSession(Base): """A signed-in browser session. Only a hash of the cookie value is stored.""" __tablename__ = "user_session" __table_args__ = (Index("ix_user_session_expires", "expires_at"),)
[docs] id: Mapped[str] = mapped_column(String(64), primary_key=True, doc="SHA-256 of the token")
[docs] user_fk: Mapped[int] = mapped_column(ForeignKey("user_account.id", ondelete="CASCADE"))
[docs] auth_method: Mapped[AuthSource] = mapped_column(_enum(AuthSource, "auth_source"))
[docs] role: Mapped[UserRole] = mapped_column(_enum(UserRole, "user_role"))
[docs] csrf_token: Mapped[str] = mapped_column(String(64))
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] last_seen_at: Mapped[datetime]
[docs] expires_at: Mapped[datetime]
[docs] source_ip: Mapped[str | None] = mapped_column(String(64))
[docs] user_agent: Mapped[str] = mapped_column(Text, default="")
[docs] user: Mapped[UserAccount] = relationship()
[docs] class Asset(Base): """Small binary files managed in the UI, such as the branding logo.""" __tablename__ = "asset"
[docs] key: Mapped[str] = mapped_column(String(64), primary_key=True)
[docs] content_type: Mapped[str] = mapped_column(String(64))
[docs] data: Mapped[bytes] = mapped_column(LargeBinary)
[docs] sha256: Mapped[str] = mapped_column(String(64))
[docs] updated_at: Mapped[datetime] = mapped_column(server_default=_now(), onupdate=_now())
# --- catalog ----------------------------------------------------------------
[docs] class ProtectedObjectRow(Base): """A discovered mailbox, drive, site, directory… (see ``sdk.ProtectedObject``).""" __tablename__ = "protected_object" __table_args__ = (UniqueConstraint("tenant_fk", "module_id", "kind", "external_id"),)
[docs] id: Mapped[int] = mapped_column(primary_key=True)
[docs] tenant_fk: Mapped[int] = mapped_column(ForeignKey("tenant.id", ondelete="CASCADE"))
[docs] module_id: Mapped[str] = mapped_column(String(32))
[docs] kind: Mapped[str] = mapped_column(String(32))
[docs] external_id: Mapped[str] = mapped_column(String(256))
[docs] display_name: Mapped[str] = mapped_column(String(512))
[docs] meta: Mapped[JSON] = mapped_column("metadata", default=dict)
[docs] first_seen_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] last_seen_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] gone_at: Mapped[datetime | None] = mapped_column(doc="No longer discovered in the tenant")
[docs] hold: Mapped[bool] = mapped_column( Boolean, default=False, doc="Legal hold: retention never removes its backups" )
[docs] hold_reason: Mapped[str | None] = mapped_column(Text)
[docs] hold_by: Mapped[str | None] = mapped_column(String(USERNAME_MAX))
[docs] hold_at: Mapped[datetime | None]
[docs] item_count: Mapped[int] = mapped_column( BigInteger, default=0, server_default="0", doc="Current items, as of its last backup" )
[docs] last_backup_at: Mapped[datetime | None] = mapped_column( doc="When its newest current item was stored" )
[docs] class SyncStateRow(Base): """Last checkpointed sync state of a protected object.""" __tablename__ = "sync_state"
[docs] protected_object_fk: Mapped[int] = mapped_column( ForeignKey("protected_object.id", ondelete="CASCADE"), primary_key=True )
[docs] state: Mapped[JSON] = mapped_column(default=dict)
[docs] module_version: Mapped[str] = mapped_column(String(32), default="")
[docs] repository_fk: Mapped[int | None] = mapped_column( ForeignKey("repository.id", ondelete="SET NULL"), doc="Repository the backup that saved it wrote to; another one starts over", )
[docs] updated_at: Mapped[datetime] = mapped_column(server_default=_now(), onupdate=_now())
[docs] class Item(Base): """A backed-up item (message, file, directory object…), across versions.""" __tablename__ = "item" __table_args__ = (UniqueConstraint("protected_object_fk", "item_key"),)
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] protected_object_fk: Mapped[int] = mapped_column( ForeignKey("protected_object.id", ondelete="CASCADE") )
[docs] item_key: Mapped[str] = mapped_column(String(512))
[docs] item_type: Mapped[str] = mapped_column(String(64))
[docs] class ItemVersionRow(Base): """One version of an item, valid from ``valid_from`` until ``valid_to``.""" __tablename__ = "item_version" __table_args__ = ( # One current version per item: the catalog's central invariant. Index( "ix_item_version_current", "item_fk", unique=True, postgresql_where="valid_to IS NULL", ), CheckConstraint("valid_to IS NULL OR valid_to >= valid_from", name="window"), Index("ix_item_version_window", "item_fk", "valid_from", "valid_to"), Index("ix_item_version_repo_expiry", "repository_fk", "valid_to"), )
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] item_fk: Mapped[int] = mapped_column(ForeignKey("item.id", ondelete="CASCADE"))
[docs] run_fk: Mapped[int | None] = mapped_column(ForeignKey("job_run.id", ondelete="SET NULL"))
[docs] repository_fk: Mapped[int] = mapped_column(ForeignKey("repository.id"))
[docs] valid_from: Mapped[datetime]
[docs] valid_to: Mapped[datetime | None]
[docs] deleted: Mapped[bool] = mapped_column(Boolean, default=False)
[docs] name: Mapped[str] = mapped_column(Text, default="")
[docs] path: Mapped[str] = mapped_column(Text, default="")
[docs] modified_at: Mapped[datetime | None]
[docs] size: Mapped[int] = mapped_column(BigInteger, default=0)
[docs] content: Mapped[JSON | None] = mapped_column(doc="ContentRef JSON; null for metadata-only")
[docs] meta: Mapped[JSON] = mapped_column("metadata", default=dict)
# --- operations -------------------------------------------------------------
[docs] class JobRun(Base): """One execution of a backup, restore, export, retention or check job.""" __tablename__ = "job_run" __table_args__ = (Index("ix_job_run_started", "started_at"),)
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] job_fk: Mapped[int | None] = mapped_column(ForeignKey("backup_job.id", ondelete="SET NULL"))
[docs] kind: Mapped[RunKind] = mapped_column(_enum(RunKind, "run_kind"))
[docs] status: Mapped[RunStatus] = mapped_column( _enum(RunStatus, "run_status"), default=RunStatus.QUEUED )
[docs] requested_by: Mapped[str] = mapped_column(String(USERNAME_MAX), default="scheduler")
[docs] queued_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] started_at: Mapped[datetime | None]
[docs] finished_at: Mapped[datetime | None]
[docs] stats: Mapped[JSON] = mapped_column(default=dict)
[docs] error: Mapped[str | None] = mapped_column(Text)
[docs] progress: Mapped[JSON] = mapped_column( default=dict, doc="Live progress while running (see jobs.progress)" )
[docs] stop_requested_at: Mapped[datetime | None]
[docs] stop_requested_by: Mapped[str | None] = mapped_column(String(USERNAME_MAX))
[docs] class JobRunLog(Base): """One line of a job run's own log (see core.runlog).""" __tablename__ = "job_run_log" __table_args__ = (Index("ix_job_run_log_run", "run_fk", "id"),)
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] run_fk: Mapped[int] = mapped_column(ForeignKey("job_run.id", ondelete="CASCADE"))
[docs] at: Mapped[datetime] = mapped_column(index=True)
[docs] entry: Mapped[JSON] = mapped_column(doc="The line's fields: timestamp, level, event, ...")
[docs] class Event(Base): """Something worth telling admins about; delivered by the notifier.""" __tablename__ = "event" __table_args__ = ( Index("ix_event_pending", "created_at", postgresql_where="delivered_at IS NULL"), )
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] created_at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] type: Mapped[str] = mapped_column(String(64), doc="e.g. job_failed, entra.ca_policy_changed")
[docs] severity: Mapped[str] = mapped_column(String(16))
[docs] subject: Mapped[str] = mapped_column(Text)
[docs] body: Mapped[JSON] = mapped_column(default=dict)
[docs] dedup_key: Mapped[str | None] = mapped_column(String(256), index=True)
[docs] run_fk: Mapped[int | None] = mapped_column(ForeignKey("job_run.id", ondelete="SET NULL"))
[docs] delivered_at: Mapped[datetime | None]
[docs] delivery_error: Mapped[str | None] = mapped_column(Text)
[docs] delivery_status: Mapped[str] = mapped_column( String(16), default="pending", server_default="pending", index=True, doc="pending, sent, skipped (below threshold or email off), throttled, failed", )
[docs] delivery_attempts: Mapped[int] = mapped_column(default=0, server_default="0")
[docs] next_attempt_at: Mapped[datetime | None]
[docs] class AuditLog(Base): """Append-only record of security-relevant actions.""" __tablename__ = "audit_log" __table_args__ = (Index("ix_audit_log_at", "at"),)
[docs] id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
[docs] at: Mapped[datetime] = mapped_column(server_default=_now())
[docs] actor: Mapped[str] = mapped_column(String(USERNAME_MAX))
[docs] action: Mapped[str] = mapped_column(String(64), doc="e.g. restore.start, settings.update")
[docs] target: Mapped[str] = mapped_column(Text, default="")
[docs] details: Mapped[JSON] = mapped_column(default=dict)
[docs] source_ip: Mapped[str | None] = mapped_column(String(64))