diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py index 9ef6aca..9452453 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -11,10 +11,12 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory 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 -MANIFEST_VERSION = 1 +BASE_MANIFEST_VERSION = 1 +MAIL_MANIFEST_VERSION = 2 MANIFEST_KIND = "coulobre_account_backup" MANIFEST_NAME = "manifest.json" MAX_MANIFEST_BYTES = 1024 * 1024 @@ -25,6 +27,7 @@ CHUNK_BYTES = 1024 * 1024 class AccountBackup: website: WebSite databases: tuple[DatabaseSpec, ...] + mailboxes: tuple[MailboxSpec, ...] | None = None def __post_init__(self): names = set() @@ -36,34 +39,53 @@ class AccountBackup: 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( + set(self.mailboxes) + ): + raise ValueError("The account backup lists a mailbox twice.") def manifest(self): - return { - "version": MANIFEST_VERSION, + 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 + ] + return manifest @classmethod def from_manifest(cls, data): - if ( - not isinstance(data, dict) - or data.keys() != {"version", "kind", "website", "databases"} - or data["kind"] != MANIFEST_KIND - or not isinstance(data["databases"], list) - ): + if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND: raise ValueError("Expected a Coulobre account backup manifest.") - if ( - type(data["version"]) is not int - or data["version"] != MANIFEST_VERSION + version = data.get("version") + if type(version) is not int or version not in ( + BASE_MANIFEST_VERSION, + MAIL_MANIFEST_VERSION, ): raise ValueError("Unsupported account backup manifest version.") + fields = {"version", "kind", "website", "databases"} + if version == MAIL_MANIFEST_VERSION: + fields.add("mailboxes") + if data.keys() != fields or not isinstance(data["databases"], list): + raise ValueError("Expected a Coulobre account backup manifest.") + mailboxes = None + if version == MAIL_MANIFEST_VERSION: + 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"] + ) return cls( WebSite.from_manifest(data["website"]), tuple( DatabaseSpec.from_manifest(item) for item in data["databases"] ), + mailboxes, ) def components(self): @@ -71,13 +93,16 @@ class AccountBackup: 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 website and databases on this server." + "create", help="Back up the resources in a local account manifest." ) create.add_argument("manifest", type=Path) create.add_argument("archive", type=Path) @@ -139,6 +164,7 @@ def private_path(path, *, new=False): def create_backup(backup, archive, socket): from .database_node_backup import backup_database + from .mail_node_backup import backup_mailbox from .web_node_backup import backup_website archive = private_path(archive, new=True) @@ -146,10 +172,13 @@ def create_backup(backup, archive, socket): directory = Path(directory) 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) - else: + elif isinstance(resource, DatabaseSpec): backup_database(resource, socket, path) + else: + backup_mailbox(resource, path) pack_backup(backup, directory, archive) @@ -163,6 +192,7 @@ def pack_backup(backup, directory, archive): 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) @@ -201,6 +231,7 @@ def unpack_backup(archive, directory): ) 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) @@ -238,19 +269,27 @@ def validate_bundle_entries(entries, backup): def validate_component(resource, path): from .database_node_backup import validate_dump_header - from .web_node_backup import validate_metadata + 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, WebSite): - with tarfile.open(fileobj=data, mode="r|") as archive: - validate_metadata(archive, archive.next(), resource) - else: + 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): diff --git a/src/coulobre/account_backup_request.py b/src/coulobre/account_backup_request.py index b47c4c2..9b3b664 100644 --- a/src/coulobre/account_backup_request.py +++ b/src/coulobre/account_backup_request.py @@ -39,7 +39,12 @@ class AccountBackupRequest: backup_id = UUID(data["backup_id"]) if str(backup_id) != data["backup_id"]: raise ValueError("Expected a canonical backup ID.") - return cls(backup_id, AccountBackup.from_manifest(data["backup"])) + backup = AccountBackup.from_manifest(data["backup"]) + if backup.mailboxes: + raise ValueError( + "Use the account backup CLI to include mailboxes." + ) + return cls(backup_id, backup) def manifest(self): return { diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index 8db2f47..8cf589d 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -3,13 +3,21 @@ from django.db import transaction from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite +from .models import HostingMailbox from .resource_requests import lock_hosting_account -def account_backup_manifest(account): +def account_backup_manifest(account, *, include_mailboxes=False): + mailboxes = None + if include_mailboxes: + requests = HostingMailbox.objects.filter( + mail_domain__account=account + ).select_related("mail_domain") + mailboxes = tuple(mailbox.spec for mailbox in requests) return AccountBackup( WebSite(account.pk, account.primary_domain), tuple(database.spec for database in account.databases.all()), + mailboxes, ).manifest() diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a11d01e..5fcfbca 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -15,6 +15,9 @@ {% if export_backup_manifest %} Download backup manifest {% endif %} + {% if export_mail_backup_manifest %} + Download backup manifest with mail + {% endif %} {% if is_operator and perms.hosting.change_hostingaccount %} Edit account {% endif %} diff --git a/src/coulobre/hosting/test_account_backup.py b/src/coulobre/hosting/test_account_backup.py index 895997c..594cac7 100644 --- a/src/coulobre/hosting/test_account_backup.py +++ b/src/coulobre/hosting/test_account_backup.py @@ -4,7 +4,7 @@ import os import stat import tarfile from contextlib import redirect_stdout -from io import StringIO +from io import BytesIO, StringIO from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch @@ -19,10 +19,17 @@ from coulobre import account_backup from coulobre.account_backup import AccountBackup from coulobre.database_node import DatabaseSpec from coulobre.database_node_backup import backup_header +from coulobre.mail_node import MailboxSpec from coulobre.web_node import WebSite from coulobre.web_node_backup import write_metadata -from .models import HostingAccount, HostingDatabase, Reseller +from .models import ( + HostingAccount, + HostingDatabase, + HostingMailbox, + HostingMailDomain, + Reseller, +) class AccountBackupManifestTests(TestCase): @@ -97,6 +104,59 @@ class AccountBackupManifestTests(TestCase): self.assertEqual(self.client.get(self.url).status_code, 403) + def test_operator_can_include_mailboxes_from_all_domains_of_the_account( + self, + ): + permission = Permission.objects.get( + content_type__app_label="hosting", codename="view_hostingmailbox" + ) + self.operator.user_permissions.add(permission) + retained = HostingMailDomain.objects.create( + account=self.account, domain="mail-before.example" + ) + current = HostingMailDomain.objects.create( + account=self.account, domain=self.account.primary_domain + ) + old_mailbox = HostingMailbox.objects.create( + mail_domain=retained, local_part="support" + ) + current_mailbox = HostingMailbox.objects.create( + mail_domain=current, local_part="info" + ) + other_mail_domain = HostingMailDomain.objects.create( + account=HostingAccount.objects.get(primary_domain="other.example"), + domain="other.example", + ) + HostingMailbox.objects.create( + mail_domain=other_mail_domain, local_part="sales" + ) + self.client.force_login(self.operator) + + response = self.client.get(self.url, {"include_mail": "1"}) + + self.assertEqual(response.status_code, 200) + self.assertIn("backup-with-mail.json", response["Content-Disposition"]) + self.assertEqual(response.json()["version"], 2) + self.assertEqual( + AccountBackup.from_manifest(response.json()).mailboxes, + (old_mailbox.spec, current_mailbox.spec), + ) + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "Download backup manifest with mail", + ) + self.assertEqual(self.client.get(self.url).json()["version"], 1) + + def test_mail_backup_manifest_requires_permission_to_view_mailboxes(self): + self.client.force_login(self.operator) + self.assertEqual( + self.client.get(self.url, {"include_mail": "1"}).status_code, 403 + ) + self.assertNotContains( + self.client.get(self.account.get_absolute_url()), + "Download backup manifest with mail", + ) + class AccountBackupCommandTests(SimpleTestCase): def setUp(self): @@ -132,6 +192,23 @@ class AccountBackupCommandTests(SimpleTestCase): gzip.compress(backup_header(database) + b"SELECT 1;\n") ) + def write_mailbox(self, mailbox, path): + path.parent.mkdir(parents=True, exist_ok=True) + metadata = json.dumps( + { + "version": 1, + "kind": "coulobre_mailbox_backup", + "mailbox": mailbox.manifest(), + } + ).encode() + with tarfile.open(path, "w:gz") as archive: + manifest = tarfile.TarInfo("manifest.json") + manifest.size = len(metadata) + archive.addfile(manifest, BytesIO(metadata)) + directory = tarfile.TarInfo("Maildir") + directory.type = tarfile.DIRTYPE + archive.addfile(directory) + def test_create_and_unpack_recover_the_native_archives_and_manifests(self): with ( patch( @@ -217,3 +294,60 @@ class AccountBackupCommandTests(SimpleTestCase): account_backup.unpack_backup(self.archive, self.restored) self.assertFalse(self.restored.exists()) + + def test_pack_and_unpack_keep_matching_local_parts_on_separate_domains( + self, + ): + support = MailboxSpec("site.example", "support") + retained = MailboxSpec("retained.example", "support") + backup = AccountBackup(self.site, (), (support, retained)) + self.manifest.write_text(json.dumps(backup.manifest())) + self.write_website(self.site, self.root / "website.tar.gz") + for mailbox in (support, retained): + self.write_mailbox( + mailbox, + self.root / "mailboxes" / mailbox.domain / "support.tar.gz", + ) + + self.run_backup("pack", self.manifest, self.root, self.archive) + self.run_backup("unpack", self.archive, self.restored) + + self.assertEqual( + json.loads((self.restored / "manifest.json").read_text()), + backup.manifest(), + ) + for mailbox in (support, retained): + directory = Path("mailboxes") / mailbox.domain + restored_archive = self.restored / directory / "support.tar.gz" + self.assertEqual( + restored_archive.read_bytes(), + (self.root / directory / "support.tar.gz").read_bytes(), + ) + self.assertEqual( + json.loads( + (self.restored / directory / "support.json").read_text() + ), + mailbox.manifest(), + ) + + def test_pack_rejects_an_archive_for_another_mailbox(self): + mailbox = MailboxSpec("site.example", "support") + backup = AccountBackup(self.site, (), (mailbox,)) + self.write_website(self.site, self.root / "website.tar.gz") + self.write_mailbox( + MailboxSpec("other.example", "support"), + self.root / "mailboxes/site.example/support.tar.gz", + ) + + with self.assertRaisesMessage(ValueError, "for a different mailbox"): + account_backup.pack_backup(backup, self.root, self.archive) + + self.assertFalse(self.archive.exists()) + + def test_manifest_rejects_a_duplicate_mailbox_address(self): + mailbox = MailboxSpec("site.example", "support") + payload = AccountBackup(self.site, (), (mailbox,)).manifest() + payload["mailboxes"].append(mailbox.manifest()) + + with self.assertRaisesMessage(ValueError, "lists a mailbox twice"): + AccountBackup.from_manifest(payload) diff --git a/src/coulobre/hosting/test_panel_account_backups.py b/src/coulobre/hosting/test_panel_account_backups.py index 745f0c1..410d324 100644 --- a/src/coulobre/hosting/test_panel_account_backups.py +++ b/src/coulobre/hosting/test_panel_account_backups.py @@ -18,6 +18,7 @@ from coulobre import account_backup_request from coulobre.account_backup import AccountBackup, main from coulobre.account_backup_request import AccountBackupRequest from coulobre.database_node import DEFAULT_SOCKET +from coulobre.mail_node import MailboxSpec from coulobre.web_node import WebSite from .models import AccountBackupJob, HostingAccount, HostingDatabase, Reseller @@ -196,6 +197,20 @@ class AccountBackupRequestTests(SimpleTestCase): self.assertEqual(report["state"], "failed") self.create.assert_not_called() + def test_panel_worker_rejects_requests_that_include_mailboxes(self): + backup = AccountBackup( + self.backup.website, + (), + (MailboxSpec("example.net", "sales"),), + ) + request = AccountBackupRequest(self.request.backup_id, backup) + + code, report = self.send(request.manifest()) + + self.assertEqual(code, 1) + self.assertIn("Use the account backup CLI", report["problem"]) + self.create.assert_not_called() + def test_replay_rejects_an_archive_with_a_different_plan(self): archive = self.directory / f"account-123-{self.request.backup_id}.zip" self.write_zip( diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 7324068..96753dd 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -80,6 +80,7 @@ VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES) +EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES) MANAGE_ACCOUNT_BACKUPS = ( *EXPORT_BACKUP_MANIFEST, "hosting.add_accountbackupjob", @@ -238,6 +239,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["export_backup_manifest"] = not tenant and user.has_perms( EXPORT_BACKUP_MANIFEST ) + context["export_mail_backup_manifest"] = context[ + "export_backup_manifest" + ] and user.has_perm(VIEW_MAILBOXES) if ( settings.LOCAL_ACCOUNT_BACKUPS and not tenant @@ -303,15 +307,27 @@ class DownloadAccountBackupManifest( ): permission_required = EXPORT_BACKUP_MANIFEST + @property + def include_mailboxes(self): + return self.request.GET.get("include_mail") == "1" + + def get_permission_required(self): + if self.include_mailboxes: + return EXPORT_MAIL_BACKUP_MANIFEST + return super().get_permission_required() + def get(self, request, pk): account = get_object_or_404(HostingAccount, pk=pk) + suffix = "backup-with-mail" if self.include_mailboxes else "backup" return JsonResponse( - account_backup_manifest(account), + account_backup_manifest( + account, include_mailboxes=self.include_mailboxes + ), headers={ "Cache-Control": "private, no-store", "Content-Disposition": ( "attachment; " - f'filename="coulobre-account-{account.pk}-backup.json"' + f'filename="coulobre-account-{account.pk}-{suffix}.json"' ), }, )