Files
coulobre/src/coulobre/account_backup.py
T

431 lines
16 KiB
Python

import argparse
import gzip
import json
import os
import tarfile
import zlib
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from shutil import copyfileobj
from tempfile import NamedTemporaryFile, TemporaryDirectory
from uuid import UUID
from zipfile import ZIP_STORED, BadZipFile, ZipFile
from .database_node import DEFAULT_SOCKET, DatabaseSpec
from .mail_node import MailboxSpec
from .node_files import check_root_file, require_root_directory, write_new_file
from .web_node import WebSite
BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
SELECTIVE_MANIFEST_VERSION = 4
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
CHUNK_BYTES = 1024 * 1024
@dataclass(frozen=True)
class AccountBackup:
website: WebSite
databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
include_website: bool = True
def __post_init__(self):
if type(self.include_website) is not bool or (
not self.include_website and self.additional_websites
):
raise ValueError("Choose whether to include the account websites.")
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
)
sites = {self.website.domain}
site_ids = set()
for site in self.additional_websites:
if (
site.account_id != self.website.account_id
or site.site_id is None
):
raise ValueError(
"All websites must belong to the backup account."
)
if site.domain in sites or site.site_id in site_ids:
raise ValueError("The account backup lists a website twice.")
sites.add(site.domain)
site_ids.add(site.site_id)
names = set()
for database in self.databases:
if database.account_id != self.website.account_id:
raise ValueError(
"All databases must belong to the website's account."
)
if database.name in names:
raise ValueError("The account backup lists a database twice.")
names.add(database.name)
if self.mailboxes is not None and len(self.mailboxes) != len(
{mailbox.address for mailbox in self.mailboxes}
):
raise ValueError("The account backup lists a mailbox twice.")
def manifest(self):
manifest = {
"version": BASE_MANIFEST_VERSION,
"kind": MANIFEST_KIND,
"website": self.website.manifest(),
"databases": [database.manifest() for database in self.databases],
}
if self.mailboxes is not None:
manifest["version"] = MAIL_MANIFEST_VERSION
manifest["mailboxes"] = [
mailbox.manifest() for mailbox in self.mailboxes
]
if self.additional_websites:
manifest["version"] = MULTI_SITE_MANIFEST_VERSION
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
if not self.include_website:
manifest["version"] = SELECTIVE_MANIFEST_VERSION
manifest["include_website"] = False
return manifest
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND:
raise ValueError("Expected a Coulobre account backup manifest.")
version = data.get("version")
if type(version) is not int or version not in (
BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
SELECTIVE_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
if version == SELECTIVE_MANIFEST_VERSION:
fields.add("include_website")
if data.get("include_website") is not False:
raise ValueError("Expected a selective account backup.")
if version == MAIL_MANIFEST_VERSION or (
version
in (MULTI_SITE_MANIFEST_VERSION, SELECTIVE_MANIFEST_VERSION)
and "mailboxes" in data
):
fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list):
raise ValueError("Expected a Coulobre account backup manifest.")
mailboxes = None
if "mailboxes" in fields:
if not isinstance(data["mailboxes"], list):
raise ValueError("Expected a list of mailbox manifests.")
mailboxes = tuple(
MailboxSpec.from_manifest(item) for item in data["mailboxes"]
)
sites = data.get("additional_websites", [])
if not isinstance(sites, list):
raise ValueError(
"Expected a list of additional website manifests."
)
return cls(
WebSite.from_manifest(data["website"]),
tuple(
DatabaseSpec.from_manifest(item) for item in data["databases"]
),
mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
data.get("include_website", True),
)
def components(self):
if self.include_website:
yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
for database in self.databases:
name = f"database-{database.suffix}"
yield database, f"{name}.json", f"{name}.sql.gz"
for mailbox in self.mailboxes or ():
name = f"mailboxes/{mailbox.domain}/{mailbox.local_part}"
yield mailbox, f"{name}.json", f"{name}.tar.gz"
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-account-backup")
commands = parser.add_subparsers(dest="command", required=True)
create = commands.add_parser(
"create", help="Back up the resources in a local account manifest."
)
create.add_argument("manifest", type=Path)
create.add_argument("archive", type=Path)
create.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
pack = commands.add_parser(
"pack", help="Bundle existing native backups from the nodes."
)
pack.add_argument("manifest", type=Path)
pack.add_argument("directory", type=Path)
pack.add_argument("archive", type=Path)
unpack = commands.add_parser(
"unpack", help="Verify and recover the native backups and manifests."
)
unpack.add_argument("archive", type=Path)
unpack.add_argument("directory", type=Path)
commands.add_parser(
"create-request", help="Create a local backup for the panel worker."
)
commands.add_parser(
"restore-website-request",
help="Restore website files for the panel worker.",
)
commands.add_parser(
"restore-request", help="Restore a component for the panel worker."
)
commands.add_parser(
"offsite-request", help="Transfer a scheduled backup for the worker."
)
verify = commands.add_parser(
"verify-offsite", help="Check access to an off-site destination."
)
verify.add_argument("destination")
recover = commands.add_parser(
"recover-offsite", help="Retrieve and verify an off-site archive."
)
recover.add_argument("destination")
recover.add_argument("account_id", type=int)
recover.add_argument("backup_id", type=UUID)
recover.add_argument("output", type=Path)
args = parser.parse_args(argv)
if args.command == "restore-request":
from .account_restore_request import serve_account_restore
return serve_account_restore()
if args.command == "restore-website-request":
from .account_restore_request import serve_website_restore
return serve_website_restore()
if args.command == "create-request":
from .account_backup_request import serve_backup_request
return serve_backup_request()
if args.command == "offsite-request":
from .offsite_node import serve_offsite_request
return serve_offsite_request()
try:
if args.command == "verify-offsite":
from .offsite_node import verify_destination
verify_destination(args.destination)
print("Off-site repository access verified.")
return 0
if args.command == "recover-offsite":
from .offsite_backup import OffsiteBackupRequest
from .offsite_node import recover_offsite_backup
request = OffsiteBackupRequest(
args.account_id, args.backup_id, args.destination
)
snapshot = recover_offsite_backup(request, args.output)
print(f"Verified archive recovered from snapshot {snapshot}.")
return 0
if args.command == "unpack":
backup = unpack_backup(args.archive, args.directory)
else:
with args.manifest.open("rb") as source:
backup = read_backup_manifest(source)
if args.command == "create":
create_backup(backup, args.archive, args.socket)
else:
pack_backup(backup, args.directory, args.archive)
except (OSError, ValueError, BadZipFile) as error:
parser.exit(1, f"coulobre-account-backup: {error}\n")
print(json.dumps(backup.manifest(), indent=2))
return 0
def read_backup_manifest(source):
content = source.read(MAX_MANIFEST_BYTES + 1)
if len(content) > MAX_MANIFEST_BYTES:
raise ValueError("The account backup manifest exceeds the size limit.")
return AccountBackup.from_manifest(json.loads(content))
def private_path(path, *, new=False):
if os.geteuid() != 0:
raise ValueError("Run the account backup command as root.")
path = path.absolute()
require_root_directory(path.parent)
if new and os.path.lexists(path):
raise ValueError(f"Choose a new path. {path} already exists.")
return path
def create_backup(backup, archive, socket, *, remote_mail=False):
from .database_node_backup import backup_database
from .mail_archive_transport import download_mailbox_backup
from .mail_node_backup import backup_mailbox
from .web_node_backup import backup_website
archive = private_path(archive, new=True)
with TemporaryDirectory(dir=archive.parent) as directory:
directory = Path(directory)
captured = 0
for resource, _, filename in backup.components():
path = directory / filename
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
if isinstance(resource, WebSite):
backup_website(resource, path)
elif isinstance(resource, DatabaseSpec):
backup_database(resource, socket, path)
elif not remote_mail:
backup_mailbox(resource, path)
else:
try:
download_mailbox_backup(resource, path)
except (OSError, ValueError) as error:
raise ValueError(
f"Mail collection stopped at {resource.address} "
f"({captured} of {len(backup.mailboxes)} captured). "
"No account archive was published. "
f"{error}"
) from None
captured += 1
pack_backup(backup, directory, archive)
def pack_backup(backup, directory, archive):
archive = private_path(archive, new=True)
directory = directory.absolute()
require_root_directory(directory)
manifest = manifest_text(backup)
with NamedTemporaryFile(dir=archive.parent) as staged:
with ZipFile(staged, mode="w", compression=ZIP_STORED) as bundle:
bundle.writestr(MANIFEST_NAME, manifest)
for resource, _, filename in backup.components():
path = directory / filename
require_root_directory(path.parent)
check_root_file(path, mode=0o600)
validate_component(resource, path)
bundle.write(path, filename)
staged.flush()
os.fsync(staged.fileno())
os.link(staged.name, archive)
@contextmanager
def open_account_bundle(archive):
archive = private_path(archive)
check_root_file(archive, mode=0o600)
with ZipFile(archive) as bundle:
entries = bundle.infolist()
if any(
entry.compress_type != ZIP_STORED or entry.flag_bits & 1
for entry in entries
):
raise ValueError(
"Expected uncompressed entries in the account backup."
)
manifests = [
entry for entry in entries if entry.filename == MANIFEST_NAME
]
if len(manifests) != 1:
raise ValueError("Expected one account backup manifest.")
with bundle.open(manifests[0]) as source:
backup = read_backup_manifest(source)
validate_bundle_entries(entries, backup)
yield bundle, backup
def unpack_backup(archive, directory):
directory = private_path(directory, new=True)
with (
open_account_bundle(archive) as (bundle, backup),
TemporaryDirectory(dir=directory.parent) as temporary,
):
staged = Path(temporary)
write_new_file(
staged / MANIFEST_NAME, manifest_text(backup), mode=0o600
)
for resource, manifest, filename in backup.components():
path = staged / filename
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
with bundle.open(filename) as source, path.open("xb") as target:
os.fchmod(target.fileno(), 0o600)
copyfileobj(source, target, length=CHUNK_BYTES)
validate_component(resource, path)
write_new_file(
staged / manifest, manifest_text(resource), mode=0o600
)
directory.mkdir(mode=0o700)
try:
staged.rename(directory)
except OSError:
directory.rmdir()
raise
return backup
def manifest_text(resource):
text = json.dumps(resource.manifest(), indent=2) + "\n"
if len(text.encode("ascii")) > MAX_MANIFEST_BYTES:
raise ValueError("The account backup manifest exceeds the size limit.")
return text
def validate_bundle_entries(entries, backup):
expected = {MANIFEST_NAME}
expected.update(filename for _, _, filename in backup.components())
if (
len(entries) != len(expected)
or {entry.filename for entry in entries} != expected
):
raise ValueError(
"The account backup has missing or unexpected entries."
)
def validate_component(resource, path):
from .database_node_backup import validate_dump_header
from .mail_node_backup import (
validate_metadata as validate_mailbox_metadata,
)
from .web_node_backup import validate_metadata as validate_website_metadata
try:
with gzip.open(path, "rb") as data:
if isinstance(resource, DatabaseSpec):
validate_dump_header(resource, data)
if not data.read(1):
raise ValueError(
"The MariaDB backup is missing its SQL dump."
)
else:
validate_metadata = (
validate_website_metadata
if isinstance(resource, WebSite)
else validate_mailbox_metadata
)
with tarfile.open(fileobj=data, mode="r|") as archive:
validate_metadata(archive, archive.next(), resource)
while data.read(CHUNK_BYTES):
pass
except (EOFError, gzip.BadGzipFile, tarfile.TarError, zlib.error):
raise ValueError(
f"The native backup {path.name} is damaged."
) from None
except ValueError as error:
raise ValueError(f"Could not validate {path.name}. {error}") from None