Merge pull request 'Include mailboxes in account backup bundles' (#28) from feature/account-backup-mailboxes into main
Reviewed-on: #28
This commit was merged in pull request #28.
This commit is contained in:
commit
30e5c520c0
9 files changed
+276
-43
No files matched your search
+3
-2
@@ -356,8 +356,9 @@ managed database and restore it to an empty database with the same identity.
|
|||||||
|
|
||||||
## Back up an account's website and databases
|
## Back up an account's website and databases
|
||||||
|
|
||||||
Download the account backup manifest from the panel. Use it to create one
|
Download an account backup manifest from the panel. Use it to create one ZIP
|
||||||
ZIP on a single server or bundle native archives from separate nodes.
|
on a single server or bundle native archives from separate nodes. The CLI can
|
||||||
|
also include mailbox archives when the downloaded manifest lists mailboxes.
|
||||||
[Account backup and recovery](development.md#back-up-a-hosting-account)
|
[Account backup and recovery](development.md#back-up-a-hosting-account)
|
||||||
|
|
||||||
### Start local account backups from the panel
|
### Start local account backups from the panel
|
||||||
|
|||||||
+28
-16
@@ -894,16 +894,20 @@ backup. The website can be recovered while its web services are stopped.
|
|||||||
|
|
||||||
Open the account as an operator and select **Download backup manifest**. The
|
Open the account as an operator and select **Download backup manifest**. The
|
||||||
manifest lists the primary website and all database requests for the account.
|
manifest lists the primary website and all database requests for the account.
|
||||||
Provision those resources before running the backup. The ZIP archive contains
|
Select **Download backup manifest with mail** to also include mailbox requests
|
||||||
the native website archive and a compressed SQL dump for each listed database.
|
from every mail domain assigned to the account. This option requires permission
|
||||||
Back up mail, DNS, and panel settings separately.
|
to view mailbox requests. Provision all listed resources before running the
|
||||||
|
backup. The ZIP contains the native website archive, a compressed SQL dump for
|
||||||
|
each listed database, and the requested mailbox archives. Back up DNS and panel
|
||||||
|
settings separately.
|
||||||
|
|
||||||
On a single-server installation, operators can also start a backup and view
|
On a single-server installation, operators can start a backup of the website
|
||||||
its status directly on the account page.
|
and databases directly from the account page and view its status there.
|
||||||
[Enable account backups in the panel](deployment.md#start-local-account-backups-from-the-panel)
|
[Enable account backups in the panel](deployment.md#start-local-account-backups-from-the-panel)
|
||||||
|
|
||||||
On a server hosting both the website and its databases, run the account backup
|
If all resources in the manifest are on one server, run the account backup
|
||||||
command as root. Add `--socket PATH` when MariaDB uses a custom socket.
|
command there as root. To include mail, pass the manifest downloaded with
|
||||||
|
mail. Add `--socket PATH` when MariaDB uses a custom socket.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo install -d -m 0700 /var/backups/coulobre
|
sudo install -d -m 0700 /var/backups/coulobre
|
||||||
@@ -912,9 +916,10 @@ sudo /opt/coulobre/bin/coulobre-account-backup create \
|
|||||||
```
|
```
|
||||||
|
|
||||||
Use a new archive filename. Allow space for the component archives and the
|
Use a new archive filename. Allow space for the component archives and the
|
||||||
finished ZIP while it is assembled. The website and databases are captured
|
finished ZIP while it is assembled. Maildir snapshots also need space on the
|
||||||
in sequence. Pause application writes, SFTP uploads, and schema changes across
|
mail volume. The components are captured in sequence. Pause changes to the
|
||||||
the components if they need to represent a single point in time.
|
listed resources during backup if they need to represent a single point in
|
||||||
|
time.
|
||||||
|
|
||||||
### Bundle backups from separate nodes
|
### Bundle backups from separate nodes
|
||||||
|
|
||||||
@@ -923,7 +928,10 @@ on the web node and the [database backup command](#back-up-and-restore-a-managed
|
|||||||
on each database node. Transfer the resulting files to a root-controlled
|
on each database node. Transfer the resulting files to a root-controlled
|
||||||
directory with mode `0600` on every archive. Name the website archive
|
directory with mode `0600` on every archive. Name the website archive
|
||||||
`website.tar.gz` and each SQL dump `database-<suffix>.sql.gz`, for example
|
`website.tar.gz` and each SQL dump `database-<suffix>.sql.gz`, for example
|
||||||
`database-cms.sql.gz`. Assemble the ZIP with the same account manifest.
|
`database-cms.sql.gz`. When the manifest includes mail, use the
|
||||||
|
[mailbox backup command](#back-up-and-restore-a-mailbox) on the mail node and
|
||||||
|
place each archive under `mailboxes/<domain>/<local-part>.tar.gz` within the
|
||||||
|
component directory. Assemble the ZIP with the same account manifest.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo /opt/coulobre/bin/coulobre-account-backup pack \
|
sudo /opt/coulobre/bin/coulobre-account-backup pack \
|
||||||
@@ -944,11 +952,15 @@ sudo /opt/coulobre/bin/coulobre-account-backup unpack \
|
|||||||
|
|
||||||
Use the recovered `website.json` and `website.tar.gz` with `restore-site`.
|
Use the recovered `website.json` and `website.tar.gz` with `restore-site`.
|
||||||
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
|
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
|
||||||
`restore-database`. Transfer the relevant pairs when the destination uses
|
`restore-database`. For mail, use the original manifest and archive recovered
|
||||||
separate nodes. For a full recovery, prepare an empty document root and empty
|
as `mailboxes/<domain>/<local-part>.json` and
|
||||||
managed databases with the original manifests and restore all components before
|
`mailboxes/<domain>/<local-part>.tar.gz` with `restore-mailbox`.
|
||||||
resuming application traffic. To recover one website file, use the website pair
|
Transfer the relevant pairs when the destination uses separate nodes. Prepare
|
||||||
with the existing `restore-site --file` option.
|
an empty document root, empty managed databases, and any newly provisioned
|
||||||
|
destination mailboxes before restoration. Resume traffic after the components
|
||||||
|
have been restored. To recover one website file, use the website pair with the
|
||||||
|
existing `restore-site --file` option. Existing website and database bundles
|
||||||
|
continue to unpack with the same filenames.
|
||||||
|
|
||||||
## Run an isolated PHP test site
|
## Run an isolated PHP test site
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,12 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory
|
|||||||
from zipfile import ZIP_STORED, BadZipFile, ZipFile
|
from zipfile import ZIP_STORED, BadZipFile, ZipFile
|
||||||
|
|
||||||
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
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 .node_files import check_root_file, require_root_directory, write_new_file
|
||||||
from .web_node import WebSite
|
from .web_node import WebSite
|
||||||
|
|
||||||
MANIFEST_VERSION = 1
|
BASE_MANIFEST_VERSION = 1
|
||||||
|
MAIL_MANIFEST_VERSION = 2
|
||||||
MANIFEST_KIND = "coulobre_account_backup"
|
MANIFEST_KIND = "coulobre_account_backup"
|
||||||
MANIFEST_NAME = "manifest.json"
|
MANIFEST_NAME = "manifest.json"
|
||||||
MAX_MANIFEST_BYTES = 1024 * 1024
|
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||||
@@ -25,6 +27,7 @@ CHUNK_BYTES = 1024 * 1024
|
|||||||
class AccountBackup:
|
class AccountBackup:
|
||||||
website: WebSite
|
website: WebSite
|
||||||
databases: tuple[DatabaseSpec, ...]
|
databases: tuple[DatabaseSpec, ...]
|
||||||
|
mailboxes: tuple[MailboxSpec, ...] | None = None
|
||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
names = set()
|
names = set()
|
||||||
@@ -36,34 +39,53 @@ class AccountBackup:
|
|||||||
if database.name in names:
|
if database.name in names:
|
||||||
raise ValueError("The account backup lists a database twice.")
|
raise ValueError("The account backup lists a database twice.")
|
||||||
names.add(database.name)
|
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):
|
def manifest(self):
|
||||||
return {
|
manifest = {
|
||||||
"version": MANIFEST_VERSION,
|
"version": BASE_MANIFEST_VERSION,
|
||||||
"kind": MANIFEST_KIND,
|
"kind": MANIFEST_KIND,
|
||||||
"website": self.website.manifest(),
|
"website": self.website.manifest(),
|
||||||
"databases": [database.manifest() for database in self.databases],
|
"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
|
@classmethod
|
||||||
def from_manifest(cls, data):
|
def from_manifest(cls, data):
|
||||||
if (
|
if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND:
|
||||||
not isinstance(data, dict)
|
|
||||||
or data.keys() != {"version", "kind", "website", "databases"}
|
|
||||||
or data["kind"] != MANIFEST_KIND
|
|
||||||
or not isinstance(data["databases"], list)
|
|
||||||
):
|
|
||||||
raise ValueError("Expected a Coulobre account backup manifest.")
|
raise ValueError("Expected a Coulobre account backup manifest.")
|
||||||
if (
|
version = data.get("version")
|
||||||
type(data["version"]) is not int
|
if type(version) is not int or version not in (
|
||||||
or data["version"] != MANIFEST_VERSION
|
BASE_MANIFEST_VERSION,
|
||||||
|
MAIL_MANIFEST_VERSION,
|
||||||
):
|
):
|
||||||
raise ValueError("Unsupported account backup 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(
|
return cls(
|
||||||
WebSite.from_manifest(data["website"]),
|
WebSite.from_manifest(data["website"]),
|
||||||
tuple(
|
tuple(
|
||||||
DatabaseSpec.from_manifest(item) for item in data["databases"]
|
DatabaseSpec.from_manifest(item) for item in data["databases"]
|
||||||
),
|
),
|
||||||
|
mailboxes,
|
||||||
)
|
)
|
||||||
|
|
||||||
def components(self):
|
def components(self):
|
||||||
@@ -71,13 +93,16 @@ class AccountBackup:
|
|||||||
for database in self.databases:
|
for database in self.databases:
|
||||||
name = f"database-{database.suffix}"
|
name = f"database-{database.suffix}"
|
||||||
yield database, f"{name}.json", f"{name}.sql.gz"
|
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):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(prog="coulobre-account-backup")
|
parser = argparse.ArgumentParser(prog="coulobre-account-backup")
|
||||||
commands = parser.add_subparsers(dest="command", required=True)
|
commands = parser.add_subparsers(dest="command", required=True)
|
||||||
create = commands.add_parser(
|
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("manifest", type=Path)
|
||||||
create.add_argument("archive", type=Path)
|
create.add_argument("archive", type=Path)
|
||||||
@@ -139,6 +164,7 @@ def private_path(path, *, new=False):
|
|||||||
|
|
||||||
def create_backup(backup, archive, socket):
|
def create_backup(backup, archive, socket):
|
||||||
from .database_node_backup import backup_database
|
from .database_node_backup import backup_database
|
||||||
|
from .mail_node_backup import backup_mailbox
|
||||||
from .web_node_backup import backup_website
|
from .web_node_backup import backup_website
|
||||||
|
|
||||||
archive = private_path(archive, new=True)
|
archive = private_path(archive, new=True)
|
||||||
@@ -146,10 +172,13 @@ def create_backup(backup, archive, socket):
|
|||||||
directory = Path(directory)
|
directory = Path(directory)
|
||||||
for resource, _, filename in backup.components():
|
for resource, _, filename in backup.components():
|
||||||
path = directory / filename
|
path = directory / filename
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
if isinstance(resource, WebSite):
|
if isinstance(resource, WebSite):
|
||||||
backup_website(resource, path)
|
backup_website(resource, path)
|
||||||
else:
|
elif isinstance(resource, DatabaseSpec):
|
||||||
backup_database(resource, socket, path)
|
backup_database(resource, socket, path)
|
||||||
|
else:
|
||||||
|
backup_mailbox(resource, path)
|
||||||
pack_backup(backup, directory, archive)
|
pack_backup(backup, directory, archive)
|
||||||
|
|
||||||
|
|
||||||
@@ -163,6 +192,7 @@ def pack_backup(backup, directory, archive):
|
|||||||
bundle.writestr(MANIFEST_NAME, manifest)
|
bundle.writestr(MANIFEST_NAME, manifest)
|
||||||
for resource, _, filename in backup.components():
|
for resource, _, filename in backup.components():
|
||||||
path = directory / filename
|
path = directory / filename
|
||||||
|
require_root_directory(path.parent)
|
||||||
check_root_file(path, mode=0o600)
|
check_root_file(path, mode=0o600)
|
||||||
validate_component(resource, path)
|
validate_component(resource, path)
|
||||||
bundle.write(path, filename)
|
bundle.write(path, filename)
|
||||||
@@ -201,6 +231,7 @@ def unpack_backup(archive, directory):
|
|||||||
)
|
)
|
||||||
for resource, manifest, filename in backup.components():
|
for resource, manifest, filename in backup.components():
|
||||||
path = staged / filename
|
path = staged / filename
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
with bundle.open(filename) as source, path.open("xb") as target:
|
with bundle.open(filename) as source, path.open("xb") as target:
|
||||||
os.fchmod(target.fileno(), 0o600)
|
os.fchmod(target.fileno(), 0o600)
|
||||||
copyfileobj(source, target, length=CHUNK_BYTES)
|
copyfileobj(source, target, length=CHUNK_BYTES)
|
||||||
@@ -238,19 +269,27 @@ def validate_bundle_entries(entries, backup):
|
|||||||
|
|
||||||
def validate_component(resource, path):
|
def validate_component(resource, path):
|
||||||
from .database_node_backup import validate_dump_header
|
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:
|
try:
|
||||||
with gzip.open(path, "rb") as data:
|
with gzip.open(path, "rb") as data:
|
||||||
if isinstance(resource, WebSite):
|
if isinstance(resource, DatabaseSpec):
|
||||||
with tarfile.open(fileobj=data, mode="r|") as archive:
|
|
||||||
validate_metadata(archive, archive.next(), resource)
|
|
||||||
else:
|
|
||||||
validate_dump_header(resource, data)
|
validate_dump_header(resource, data)
|
||||||
if not data.read(1):
|
if not data.read(1):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The MariaDB backup is missing its SQL dump."
|
"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):
|
while data.read(CHUNK_BYTES):
|
||||||
pass
|
pass
|
||||||
except (EOFError, gzip.BadGzipFile, tarfile.TarError, zlib.error):
|
except (EOFError, gzip.BadGzipFile, tarfile.TarError, zlib.error):
|
||||||
|
|||||||
@@ -39,7 +39,12 @@ class AccountBackupRequest:
|
|||||||
backup_id = UUID(data["backup_id"])
|
backup_id = UUID(data["backup_id"])
|
||||||
if str(backup_id) != data["backup_id"]:
|
if str(backup_id) != data["backup_id"]:
|
||||||
raise ValueError("Expected a canonical 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):
|
def manifest(self):
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -3,13 +3,21 @@ from django.db import transaction
|
|||||||
from coulobre.account_backup import AccountBackup
|
from coulobre.account_backup import AccountBackup
|
||||||
from coulobre.web_node import WebSite
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
|
from .models import HostingMailbox
|
||||||
from .resource_requests import lock_hosting_account
|
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(
|
return AccountBackup(
|
||||||
WebSite(account.pk, account.primary_domain),
|
WebSite(account.pk, account.primary_domain),
|
||||||
tuple(database.spec for database in account.databases.all()),
|
tuple(database.spec for database in account.databases.all()),
|
||||||
|
mailboxes,
|
||||||
).manifest()
|
).manifest()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,9 @@
|
|||||||
{% if export_backup_manifest %}
|
{% if export_backup_manifest %}
|
||||||
<a class="button secondary" href="{% url 'panel:account_backup_manifest' account.pk %}">Download backup manifest</a>
|
<a class="button secondary" href="{% url 'panel:account_backup_manifest' account.pk %}">Download backup manifest</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
{% if export_mail_backup_manifest %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_backup_manifest' account.pk %}?include_mail=1">Download backup manifest with mail</a>
|
||||||
|
{% endif %}
|
||||||
{% if is_operator and perms.hosting.change_hostingaccount %}
|
{% if is_operator and perms.hosting.change_hostingaccount %}
|
||||||
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
|
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import os
|
|||||||
import stat
|
import stat
|
||||||
import tarfile
|
import tarfile
|
||||||
from contextlib import redirect_stdout
|
from contextlib import redirect_stdout
|
||||||
from io import StringIO
|
from io import BytesIO, StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
@@ -19,10 +19,17 @@ from coulobre import account_backup
|
|||||||
from coulobre.account_backup import AccountBackup
|
from coulobre.account_backup import AccountBackup
|
||||||
from coulobre.database_node import DatabaseSpec
|
from coulobre.database_node import DatabaseSpec
|
||||||
from coulobre.database_node_backup import backup_header
|
from coulobre.database_node_backup import backup_header
|
||||||
|
from coulobre.mail_node import MailboxSpec
|
||||||
from coulobre.web_node import WebSite
|
from coulobre.web_node import WebSite
|
||||||
from coulobre.web_node_backup import write_metadata
|
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):
|
class AccountBackupManifestTests(TestCase):
|
||||||
@@ -97,6 +104,59 @@ class AccountBackupManifestTests(TestCase):
|
|||||||
|
|
||||||
self.assertEqual(self.client.get(self.url).status_code, 403)
|
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):
|
class AccountBackupCommandTests(SimpleTestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
@@ -132,6 +192,23 @@ class AccountBackupCommandTests(SimpleTestCase):
|
|||||||
gzip.compress(backup_header(database) + b"SELECT 1;\n")
|
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):
|
def test_create_and_unpack_recover_the_native_archives_and_manifests(self):
|
||||||
with (
|
with (
|
||||||
patch(
|
patch(
|
||||||
@@ -217,3 +294,60 @@ class AccountBackupCommandTests(SimpleTestCase):
|
|||||||
account_backup.unpack_backup(self.archive, self.restored)
|
account_backup.unpack_backup(self.archive, self.restored)
|
||||||
|
|
||||||
self.assertFalse(self.restored.exists())
|
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)
|
||||||
@@ -18,6 +18,7 @@ from coulobre import account_backup_request
|
|||||||
from coulobre.account_backup import AccountBackup, main
|
from coulobre.account_backup import AccountBackup, main
|
||||||
from coulobre.account_backup_request import AccountBackupRequest
|
from coulobre.account_backup_request import AccountBackupRequest
|
||||||
from coulobre.database_node import DEFAULT_SOCKET
|
from coulobre.database_node import DEFAULT_SOCKET
|
||||||
|
from coulobre.mail_node import MailboxSpec
|
||||||
from coulobre.web_node import WebSite
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
from .models import AccountBackupJob, HostingAccount, HostingDatabase, Reseller
|
from .models import AccountBackupJob, HostingAccount, HostingDatabase, Reseller
|
||||||
@@ -196,6 +197,20 @@ class AccountBackupRequestTests(SimpleTestCase):
|
|||||||
self.assertEqual(report["state"], "failed")
|
self.assertEqual(report["state"], "failed")
|
||||||
self.create.assert_not_called()
|
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):
|
def test_replay_rejects_an_archive_with_a_different_plan(self):
|
||||||
archive = self.directory / f"account-123-{self.request.backup_id}.zip"
|
archive = self.directory / f"account-123-{self.request.backup_id}.zip"
|
||||||
self.write_zip(
|
self.write_zip(
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ VIEW_DATABASES = "hosting.view_hostingdatabase"
|
|||||||
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
||||||
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
|
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
|
||||||
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
|
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
|
||||||
|
EXPORT_MAIL_BACKUP_MANIFEST = (*EXPORT_BACKUP_MANIFEST, VIEW_MAILBOXES)
|
||||||
MANAGE_ACCOUNT_BACKUPS = (
|
MANAGE_ACCOUNT_BACKUPS = (
|
||||||
*EXPORT_BACKUP_MANIFEST,
|
*EXPORT_BACKUP_MANIFEST,
|
||||||
"hosting.add_accountbackupjob",
|
"hosting.add_accountbackupjob",
|
||||||
@@ -238,6 +239,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["export_backup_manifest"] = not tenant and user.has_perms(
|
context["export_backup_manifest"] = not tenant and user.has_perms(
|
||||||
EXPORT_BACKUP_MANIFEST
|
EXPORT_BACKUP_MANIFEST
|
||||||
)
|
)
|
||||||
|
context["export_mail_backup_manifest"] = context[
|
||||||
|
"export_backup_manifest"
|
||||||
|
] and user.has_perm(VIEW_MAILBOXES)
|
||||||
if (
|
if (
|
||||||
settings.LOCAL_ACCOUNT_BACKUPS
|
settings.LOCAL_ACCOUNT_BACKUPS
|
||||||
and not tenant
|
and not tenant
|
||||||
@@ -303,15 +307,27 @@ class DownloadAccountBackupManifest(
|
|||||||
):
|
):
|
||||||
permission_required = EXPORT_BACKUP_MANIFEST
|
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):
|
def get(self, request, pk):
|
||||||
account = get_object_or_404(HostingAccount, pk=pk)
|
account = get_object_or_404(HostingAccount, pk=pk)
|
||||||
|
suffix = "backup-with-mail" if self.include_mailboxes else "backup"
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
account_backup_manifest(account),
|
account_backup_manifest(
|
||||||
|
account, include_mailboxes=self.include_mailboxes
|
||||||
|
),
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "private, no-store",
|
"Cache-Control": "private, no-store",
|
||||||
"Content-Disposition": (
|
"Content-Disposition": (
|
||||||
"attachment; "
|
"attachment; "
|
||||||
f'filename="coulobre-account-{account.pk}-backup.json"'
|
f'filename="coulobre-account-{account.pk}-{suffix}.json"'
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in new issue
Block a user