154 lines
4.8 KiB
Python
154 lines
4.8 KiB
Python
import os
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from uuid import UUID
|
|
from zipfile import BadZipFile, ZipFile
|
|
|
|
from .account_backup import (
|
|
MANIFEST_NAME,
|
|
MAX_MANIFEST_BYTES,
|
|
AccountBackup,
|
|
create_backup,
|
|
read_backup_manifest,
|
|
)
|
|
from .database_node import DEFAULT_SOCKET
|
|
from .node_files import check_root_file, locked_root_directory
|
|
from .node_requests import serve_apply_request
|
|
|
|
REQUEST_VERSION = 1
|
|
REMOTE_MAIL_VERSION = 2
|
|
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
|
|
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
|
|
BACKUP_TIMEOUT_SECONDS = 30 * 60
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class AccountBackupRequest:
|
|
backup_id: UUID
|
|
backup: AccountBackup
|
|
remote_mail: bool = False
|
|
|
|
@classmethod
|
|
def from_manifest(cls, data):
|
|
if (
|
|
not isinstance(data, dict)
|
|
or data.keys() != {"version", "backup_id", "backup"}
|
|
or type(data["version"]) is not int
|
|
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
|
|
or not isinstance(data["backup_id"], str)
|
|
):
|
|
raise ValueError("Expected a local account backup request.")
|
|
backup_id = UUID(data["backup_id"])
|
|
if str(backup_id) != data["backup_id"]:
|
|
raise ValueError("Expected a canonical backup ID.")
|
|
backup = AccountBackup.from_manifest(data["backup"])
|
|
remote_mail = data["version"] == REMOTE_MAIL_VERSION
|
|
if remote_mail and backup.mailboxes is None:
|
|
raise ValueError(
|
|
"Expected mailboxes in the remote backup request."
|
|
)
|
|
return cls(backup_id, backup, remote_mail)
|
|
|
|
def manifest(self):
|
|
return {
|
|
"version": self.version,
|
|
"backup_id": str(self.backup_id),
|
|
"backup": self.backup.manifest(),
|
|
}
|
|
|
|
def identity(self):
|
|
return {
|
|
"version": self.version,
|
|
"backup_id": str(self.backup_id),
|
|
"account_id": self.backup.website.account_id,
|
|
}
|
|
|
|
@property
|
|
def version(self):
|
|
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
|
|
|
|
|
|
def backup_archive(account_id, backup_id):
|
|
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
|
|
|
|
|
def expiration_marker(archive):
|
|
return archive.with_suffix(".expired")
|
|
|
|
|
|
def parse_backup_request(data):
|
|
if isinstance(data, dict) and data.get("operation") == "expire":
|
|
from .account_backup_retention import ArchiveExpirationRequest
|
|
|
|
return ArchiveExpirationRequest.from_manifest(data)
|
|
return AccountBackupRequest.from_manifest(data)
|
|
|
|
|
|
def apply_backup_request(request):
|
|
if isinstance(request, AccountBackupRequest):
|
|
return create_requested_backup(request)
|
|
|
|
from .account_backup_retention import expire_requested_archive
|
|
|
|
return expire_requested_archive(request)
|
|
|
|
|
|
def serve_backup_request():
|
|
return serve_apply_request(
|
|
REQUEST_VERSION,
|
|
parse_backup_request,
|
|
apply_backup_request,
|
|
limit=MAX_MANIFEST_BYTES + 4096,
|
|
identity=lambda request: request.identity(),
|
|
include_result=True,
|
|
)
|
|
|
|
|
|
def create_requested_backup(request):
|
|
if os.geteuid() != 0:
|
|
raise ValueError("Run create-request as root on the backup node.")
|
|
if request.backup.mailboxes is not None:
|
|
setting = (
|
|
"COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL"
|
|
if request.remote_mail
|
|
else "COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL"
|
|
)
|
|
if os.environ.get(setting) != "1":
|
|
location = "remote" if request.remote_mail else "local"
|
|
raise ValueError(
|
|
f"Enable mailbox backups on the {location} backup node."
|
|
)
|
|
with locked_root_directory(BACKUP_DIRECTORY):
|
|
archive = ensure_requested_archive(request)
|
|
return {"archive_bytes": archive.stat().st_size}
|
|
|
|
|
|
def ensure_requested_archive(request):
|
|
archive = backup_archive(
|
|
request.backup.website.account_id, request.backup_id
|
|
)
|
|
if os.path.lexists(expiration_marker(archive)):
|
|
raise ValueError("This account backup has expired.")
|
|
if not os.path.lexists(archive):
|
|
if request.remote_mail:
|
|
create_backup(
|
|
request.backup, archive, DEFAULT_SOCKET, remote_mail=True
|
|
)
|
|
else:
|
|
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
|
return archive
|
|
|
|
check_root_file(archive, mode=0o600)
|
|
try:
|
|
with ZipFile(archive) as bundle, bundle.open(MANIFEST_NAME) as source:
|
|
existing = read_backup_manifest(source)
|
|
except (BadZipFile, KeyError, RuntimeError, ValueError):
|
|
raise ValueError(
|
|
"An unreadable archive already exists for this request."
|
|
) from None
|
|
if existing != request.backup:
|
|
raise ValueError(
|
|
"An archive with a different manifest already exists."
|
|
)
|
|
return archive
|