From 386525d314bbfb357df63e004a8b81f5b0d53998 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 22:18:59 +0100 Subject: [PATCH] Back up and recover remote mailboxes from the panel --- deploy/panel.env.example | 2 + docs/deployment.md | 120 ++++++++++- src/coulobre/hosting/account_backups.py | 10 + src/coulobre/hosting/backup_restores.py | 37 +++- .../migrations/0040_remote_mail_archives.py | 22 ++ src/coulobre/hosting/models.py | 13 ++ src/coulobre/hosting/node_client.py | 12 +- src/coulobre/hosting/tasks.py | 57 ++++- .../hosting/backup_restore_history.html | 6 + .../hosting/test_remote_mail_archives.py | 204 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 33 ++- src/coulobre/settings.py | 13 ++ 13 files changed, 510 insertions(+), 24 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0040_remote_mail_archives.py create mode 100644 src/coulobre/hosting/test_remote_mail_archives.py diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 0316aa3..5a455c4 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -34,7 +34,9 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_ROUNDCUBE_BRIDGE_KEY= # COULOBRE_LOCAL_ACCOUNT_BACKUPS=1 # COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1 +# COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1 # COULOBRE_LOCAL_BACKUP_RETENTION=1 # COULOBRE_LOCAL_WEBSITE_RESTORE=1 # COULOBRE_LOCAL_DATABASE_RESTORE=1 # COULOBRE_LOCAL_MAILBOX_RESTORE=1 +# COULOBRE_REMOTE_MAILBOX_RESTORE=1 diff --git a/docs/deployment.md b/docs/deployment.md index 594a425..834e4db 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -586,8 +586,9 @@ worker delivery from recreating an expired archive. #### Restore from local account backups in the panel Enable local account backups first. Install the restore socket and give the -backup worker access to it. The archive and the resources being restored -must be on the same server. +backup worker access to it. Website and MariaDB restores use the backup +host. To restore to a separate mail server, use the +[remote mailbox setup](#include-mailboxes-on-a-separate-server). ```sh sudo groupadd --system coulobre-restore-requests @@ -644,7 +645,7 @@ action on a completed backup. - **Restore mailbox** offers mailboxes listed in the backup that still belong to the account. Use a newly provisioned mailbox with no Maildir. Keep delivery and client access paused for that mailbox during recovery, - with Postfix and Dovecot running for local checks. The restored mailbox + with Postfix and Dovecot running on the destination. The restored mailbox uses the destination credentials and current quota configuration. The **Backup restores** section shows each target, source backup, operator, @@ -652,7 +653,8 @@ and result. Keep the request records under `/var/lib/coulobre/account-restores/` while corresponding jobs could still be delivered. If the panel cannot confirm a restore, check the destination before submitting another. For resources on separate servers, use the -[account bundle commands](development.md#recover-backups-from-the-bundle). +[account bundle commands](development.md#recover-backups-from-the-bundle) +or the remote mailbox action below. ##### Run a backup and restore drill @@ -690,9 +692,113 @@ starting or scheduling an account backup. They can also edit an existing schedule that includes mail. If you disable mailbox backups while such a schedule is enabled, the subsequent jobs report a failure until you adjust the schedule or re-enable local mailbox backups. Provision all listed -mailboxes before requesting a backup with mail. For mailboxes on a separate -server, use the -[bundle workflow for separate nodes](development.md#bundle-backups-from-separate-nodes). +mailboxes before requesting a backup with mail. + +#### Include mailboxes on a separate server + +Enable local account backups on the panel host and provision the +mailboxes on the [separate mail node](#provision-mail-and-dns-on-separate-servers). +Upgrade Coulobre on both hosts. The website, database dumps, and completed +ZIP stay on the backup host. The mail node streams the native snapshots +over SSH and uses temporary disk space while collecting or restoring a +mailbox. + +Choose which operations to enable. The examples enable both; use just +`backup` in the loops if you only want to collect mail. + +On the backup host, create a dedicated identity and SSH key for each +operation, and install its relay socket and service. + +```sh +sudo apt install openssh-client +sudo install -d -m 0755 /etc/coulobre-remote +sudo install -m 0644 deploy/openssh/mail-archive-client.conf.example \ + /etc/coulobre-remote/mail-archive.conf +sudoedit /etc/coulobre-remote/mail-archive.conf +for action in backup restore; do + unit="coulobre-mail-archive-$action" + path="/etc/coulobre-remote/mail-archive-$action" + sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin "$unit" + sudo install -d -o root -g "$unit" -m 0750 "$path" + sudo ssh-keygen -t ed25519 -N '' -f "$path/id_ed25519" + sudo chown "$unit:$unit" "$path/id_ed25519" + sudo install -m 0644 "deploy/systemd/$unit.socket" \ + "deploy/systemd/$unit@.service" /etc/systemd/system/ + sudo install -D -m 0644 "deploy/systemd/$unit@.service.d/relay.conf" \ + "/etc/systemd/system/$unit@.service.d/relay.conf" + sudo cat "$path/id_ed25519.pub" +done +``` + +Point the SSH aliases at the mail node that serves these mailboxes. Add +its verified host key to each operation's `known_hosts` file. Keep both +aliases pointed at the same node while jobs are queued or may be retried. + +On the mail node, save the sender's separate public keys as +`backup.pub` and `restore.pub`. Install the receiver accounts, sockets, +and forced commands. + +```sh +sudo apt install openssh-server socat +sudo install -d -m 0755 /etc/ssh/coulobre-node-keys +for action in backup restore; do + unit="coulobre-mail-archive-$action" + sudo useradd --system --user-group --no-create-home --home-dir / \ + --shell /bin/sh "$unit" + sudo install -m 0644 "$action.pub" "/etc/ssh/coulobre-node-keys/$unit" + sudo install -m 0644 "deploy/systemd/$unit.socket" \ + "deploy/systemd/$unit@.service" /etc/systemd/system/ + sudo systemctl enable --now "$unit.socket" +done +sudo install -m 0644 deploy/openssh/coulobre-mail-archive.conf.example \ + /etc/ssh/sshd_config.d/00-coulobre-mail-archive.conf +sudo install -m 0644 deploy/tmpfiles.d/coulobre-mail-archive.conf \ + /etc/tmpfiles.d/coulobre-mail-archive.conf +sudo sshd -t +sudo systemctl reload-or-restart ssh.service +sudo systemctl start systemd-tmpfiles-clean.timer +``` + +Return to the backup host. Enable the corresponding relay sockets and +authorize the operations for the account services. + +```sh +sudo install -D -m 0644 deploy/systemd/coulobre-account-backup@.service.d/remote-mail.conf \ + /etc/systemd/system/coulobre-account-backup@.service.d/remote-mail.conf +sudo systemctl enable --now coulobre-mail-archive-backup.socket + +# For restores, install the account restore socket and worker access first. +sudo install -D -m 0644 deploy/systemd/coulobre-account-restore@.service.d/remote-mail.conf \ + /etc/systemd/system/coulobre-account-restore@.service.d/remote-mail.conf +sudo systemctl enable --now coulobre-mail-archive-restore.socket +``` + +Use `COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1` and, if enabled, +`COULOBRE_REMOTE_MAILBOX_RESTORE=1` in `/etc/coulobre/panel.env`. +Each operation takes one transport. Clear its local setting when +switching that operation to SSH. Apply migrations, reload systemd, and +restart the panel, scheduler and backup worker. + +Select **Include mailboxes** in manual or scheduled backups. A failed or +interrupted transfer reports where mail collection stopped and keeps the +incomplete backup out of the ready archives and retention count. + +For recovery, pause delivery and client access for the selected mailbox. +Use **Restore mailbox** with the matching, provisioned destination and +an absent Maildir. If the connection drops before the result is confirmed, +use **Retry remote restore** while the source archive is available. The +mail node records results by restore ID and checks the archive checksum +and destination before writing. If it reports an interrupted restore, +inspect the destination before opening a new request. Keep the mail +node's restore journal under `/var/lib/coulobre/mail-archive-restores/` +while corresponding jobs can still be retried. The cleanup rule removes +abandoned transfer staging files after one day. + +For a recovery drill, follow the [backup and restore drill](#run-a-backup-and-restore-drill) +with the mailbox stored on the other node. Verify that the backup on the +panel host includes the website, SQL dump, and test message, and that the +selected message is recovered on the mail node. ## Show local database and mailbox connection details diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index efe302d..c618a2b 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -1,5 +1,6 @@ from datetime import UTC, datetime, timedelta +from django.conf import settings from django.core.exceptions import PermissionDenied from django.db import transaction from django.utils import timezone @@ -15,6 +16,13 @@ from .models import ( from .resource_requests import lock_hosting_account, require_open_account +def mail_backups_enabled(): + return ( + settings.LOCAL_ACCOUNT_BACKUP_MAIL + or settings.REMOTE_ACCOUNT_BACKUP_MAIL + ) + + def account_backup_manifest(account, *, include_mailboxes=False): mailboxes = None if include_mailboxes: @@ -42,6 +50,8 @@ def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None): manifest=account_backup_manifest( account, include_mailboxes=include_mailboxes ), + remote_mail=include_mailboxes + and settings.REMOTE_ACCOUNT_BACKUP_MAIL, scheduled_for=scheduled_for, ) diff --git a/src/coulobre/hosting/backup_restores.py b/src/coulobre/hosting/backup_restores.py index b73cd73..84f1418 100644 --- a/src/coulobre/hosting/backup_restores.py +++ b/src/coulobre/hosting/backup_restores.py @@ -16,7 +16,11 @@ def enabled_component_restores(): kind for kind, enabled in ( (RestoreKind.DATABASE, settings.LOCAL_DATABASE_RESTORE), - (RestoreKind.MAILBOX, settings.LOCAL_MAILBOX_RESTORE), + ( + RestoreKind.MAILBOX, + settings.LOCAL_MAILBOX_RESTORE + or settings.REMOTE_MAILBOX_RESTORE, + ), ) if enabled } @@ -91,7 +95,12 @@ def queue_component_restore( backup, restore_id, operator_username, - {"kind": kind, "resource": resource}, + { + "kind": kind, + "resource": resource, + "remote_mail": kind == RestoreKind.MAILBOX + and settings.REMOTE_MAILBOX_RESTORE, + }, ComponentRestoreJob.objects.filter( backup__account=account, kind=kind, @@ -102,6 +111,30 @@ def queue_component_restore( ) +@transaction.atomic +def retry_remote_mail_restore(job, operator_username): + account = lock_hosting_account(job.backup.account_id, customer_id=None) + require_active_services(account) + job.refresh_from_db() + targets = available_restore_resources( + job.backup, + RestoreKind.MAILBOX, + current_restore_resources(account, RestoreKind.MAILBOX), + ) + if not job.can_retry_remote or job.resource not in targets: + raise ValidationError("This mailbox restore can no longer be retried.") + jobs = ComponentRestoreJob.objects.filter( + backup__account=account, + kind=RestoreKind.MAILBOX, + resource=job.resource, + ) + if jobs.filter(finished_at__isnull=True).exists(): + raise ValidationError("Wait for the current restore of this target.") + ComponentRestoreJob.objects.requeue( + jobs.filter(pk=job.pk), operator_username=operator_username + ) + + def _queue_restore( jobs, backup, restore_id, operator_username, target, pending, busy ): diff --git a/src/coulobre/hosting/migrations/0040_remote_mail_archives.py b/src/coulobre/hosting/migrations/0040_remote_mail_archives.py new file mode 100644 index 0000000..5498f70 --- /dev/null +++ b/src/coulobre/hosting/migrations/0040_remote_mail_archives.py @@ -0,0 +1,22 @@ +# Generated by Django 5.2.19 on 2026-11-21 21:12 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0039_mail_dns_setup"), + ] + + operations = [ + migrations.AddField( + model_name="accountbackupjob", + name="remote_mail", + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name="componentrestorejob", + name="remote_mail", + field=models.BooleanField(default=False), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index fea42d7..6d98a63 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -26,6 +26,7 @@ from coulobre.dns_node import ( MxRecord, TxtRecord, ) +from coulobre.mail_archive_transport import UNCONFIRMED_REMOTE_RESTORE from coulobre.mail_node import ( LOCAL_PART_MAX_LENGTH, MAX_MAILBOX_QUOTA_MIB, @@ -829,6 +830,7 @@ class AccountBackupJob(ProvisioningJob): default=uuid.uuid4, unique=True, editable=False ) manifest = models.JSONField() + remote_mail = models.BooleanField(default=False) scheduled_for = models.DateTimeField(null=True, blank=True) archive_bytes = models.PositiveBigIntegerField(null=True, blank=True) retention_protected = models.BooleanField(default=False) @@ -900,6 +902,7 @@ class ComponentRestoreJob(ProvisioningJob): restore_id = models.UUIDField(unique=True, editable=False) kind = models.CharField(max_length=8, choices=Kind) resource = models.CharField(max_length=254) + remote_mail = models.BooleanField(default=False) operator_username = models.CharField(max_length=150) class Meta: @@ -915,6 +918,16 @@ class ComponentRestoreJob(ProvisioningJob): return DatabaseSpec(self.backup.account_id, self.resource).name return self.resource + @property + def can_retry_remote(self): + return ( + self.kind == self.Kind.MAILBOX + and self.remote_mail + and self.state == "failed" + and self.problem == UNCONFIRMED_REMOTE_RESTORE + and self.backup.archive_is_restorable + ) + class AccountBackupSchedule(models.Model): class Frequency(models.TextChoices): diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index eb30307..1a1caa7 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -25,6 +25,10 @@ from coulobre.web_node import ( RESPONSE_LIMIT = 32768 +class NodeReplyError(ValueError): + pass + + def activate_local_site(site): apply_on_local_node( site, "/run/coulobre-web-apply.sock", "web node", "site" @@ -230,9 +234,9 @@ def apply_on_local_node( body = response.read(RESPONSE_LIMIT + 1) if len(body) > RESPONSE_LIMIT: - raise ValueError(f"The {node} returned an oversized response.") + raise NodeReplyError(f"The {node} returned an oversized response.") if not body: - raise ValueError( + raise NodeReplyError( f"The {node} closed the connection without a response." ) invalid_response = ( @@ -246,10 +250,10 @@ def apply_on_local_node( for key, value in expected.items() ) except (KeyError, TypeError, ValueError, RecursionError): - raise ValueError(invalid_response) from None + raise NodeReplyError(invalid_response) from None if matches: if state == "configured" and problem is None: return reply if state == "failed" and isinstance(problem, str) and problem.strip(): raise ValueError(problem.strip()[:2000]) - raise ValueError(invalid_response) + raise NodeReplyError(invalid_response) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 443b737..d730910 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -19,6 +19,7 @@ from coulobre.account_restore_request import ( WebsiteRestoreRequest, ) from coulobre.dns_node import DnsZone +from coulobre.mail_archive_transport import UNCONFIRMED_REMOTE_RESTORE from coulobre.php_pool_settings import PhpPoolSettings from coulobre.sftp_keys import SFTPKeys from coulobre.web_node import WebAlias, WebSite @@ -26,6 +27,7 @@ from coulobre.web_node import WebAlias, WebSite from .account_backups import queue_due_account_backups from .account_retirement import apply_retirement_job, finalize_retirement from .backup_restores import ( + RestoreKind, available_restore_resources, current_restore_resources, enabled_component_restores, @@ -54,6 +56,7 @@ from .models import ( WebsiteRestoreJob, ) from .node_client import ( + NodeReplyError, activate_local_site, activate_local_site_with_php, create_local_account_backup, @@ -631,7 +634,7 @@ def apply_mailbox_provisioning(provisioning): def create_account_backup(job_id): if settings.LOCAL_ACCOUNT_BACKUPS: run_provisioning_job( - AccountBackupJob.objects.all(), + AccountBackupJob.objects.select_related("account"), job_id, apply_account_backup, "Could not complete the request to the local backup node. " @@ -644,10 +647,29 @@ def apply_account_backup(job): backup = AccountBackup.from_manifest(job.manifest) if backup.website.account_id != job.account_id: raise ValueError("The backup manifest belongs to a different account.") - if backup.mailboxes is not None and not settings.LOCAL_ACCOUNT_BACKUP_MAIL: - raise ValueError("Enable local mailbox backups before trying again.") + if backup.mailboxes is not None: + if job.remote_mail: + if not settings.REMOTE_ACCOUNT_BACKUP_MAIL: + raise ValueError( + "Enable remote mailbox backups before trying again." + ) + current = current_restore_resources( + job.account, RestoreKind.MAILBOX + ) + if any( + mailbox.address not in current for mailbox in backup.mailboxes + ): + raise ValueError( + "A mailbox no longer belongs to this account." + ) + elif not settings.LOCAL_ACCOUNT_BACKUP_MAIL: + raise ValueError( + "Enable local mailbox backups before trying again." + ) size = create_local_account_backup( - AccountBackupRequest(job.backup_id, backup) + AccountBackupRequest( + job.backup_id, backup, remote_mail=job.remote_mail + ) ) return {"archive_bytes": size} @@ -748,11 +770,30 @@ def apply_component_restore(job): raise ValueError( "The backup or its restore target is no longer available." ) - restore_local_component( - ComponentRestoreRequest( - job.restore_id, backup.backup_id, backup.account_id, target + if job.kind == RestoreKind.MAILBOX: + enabled = ( + settings.REMOTE_MAILBOX_RESTORE + if job.remote_mail + else settings.LOCAL_MAILBOX_RESTORE ) - ) + if not enabled: + raise ValueError( + "Re-enable the requested mailbox restore transport." + ) + try: + restore_local_component( + ComponentRestoreRequest( + job.restore_id, + backup.backup_id, + backup.account_id, + target, + remote_mail=job.remote_mail, + ) + ) + except (OSError, NodeReplyError): + if job.remote_mail: + raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None + raise def run_provisioning_job( diff --git a/src/coulobre/hosting/templates/hosting/backup_restore_history.html b/src/coulobre/hosting/templates/hosting/backup_restore_history.html index 72bed2a..11c7cde 100644 --- a/src/coulobre/hosting/templates/hosting/backup_restore_history.html +++ b/src/coulobre/hosting/templates/hosting/backup_restore_history.html @@ -30,6 +30,12 @@ {{ restore.state|capfirst }} {% endif %} {% if restore.problem %}
{{ restore.problem }}
{% endif %} + {% if allow_remote_restore_retry and restore.can_retry_remote %} +
+ {% csrf_token %} + +
+ {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/test_remote_mail_archives.py b/src/coulobre/hosting/test_remote_mail_archives.py new file mode 100644 index 0000000..1f8e5cd --- /dev/null +++ b/src/coulobre/hosting/test_remote_mail_archives.py @@ -0,0 +1,204 @@ +import hashlib +from datetime import timedelta +from io import BytesIO +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch +from uuid import uuid4 + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.account_backup_request import AccountBackupRequest +from coulobre.account_restore_request import ComponentRestoreRequest +from coulobre.mail_archive_transport import ( + UNCONFIRMED_REMOTE_RESTORE, + MailArchiveConnectionError, + MailArchiveRequest, + encode_header, + node_reply, + receive_archive, +) +from coulobre.mail_node import MailboxSpec + +from .account_backups import account_backup_manifest, queue_due_account_backups +from .models import ( + AccountBackupJob, + AccountBackupSchedule, + ComponentRestoreJob, + HostingAccount, + HostingMailbox, + HostingMailDomain, +) +from .tasks import create_account_backup, restore_backup_component + + +class MailArchiveProtocolTests(SimpleTestCase): + def test_role_and_response_must_match_the_requested_mailbox(self): + mailbox = MailboxSpec("account.example", "help", 50) + payload = b"fixture" + request = MailArchiveRequest( + mailbox, uuid4(), len(payload), hashlib.sha256(payload).hexdigest() + ) + manifest = request.manifest() + self.assertEqual( + MailArchiveRequest.parse(manifest, "restore"), request + ) + with self.assertRaises(ValueError): + MailArchiveRequest.parse(manifest, "backup") + wrong = manifest | { + "mailbox": MailboxSpec("elsewhere.example", "help", 50).manifest(), + "state": "configured", + "problem": None, + } + with self.assertRaises(MailArchiveConnectionError): + node_reply(BytesIO(encode_header(wrong)), request) + + def test_truncated_corrupt_or_extra_data_is_discarded(self): + payload = b"mail archive fixture" + digest = hashlib.sha256(payload).hexdigest() + with TemporaryDirectory() as directory: + archive = Path(directory) / "mailbox.tar.gz" + for received in ( + payload[:-1], + payload + b"! failure", + b"!" * len(payload), + ): + with self.subTest(received=received): + with self.assertRaises(MailArchiveConnectionError): + receive_archive( + BytesIO(received), + archive, + len(payload), + digest=digest, + ) + self.assertFalse(archive.exists()) + receive_archive( + BytesIO(payload), archive, len(payload), digest=digest + ) + with self.assertRaises(FileExistsError): + receive_archive(BytesIO(b"overwrite"), archive, 9) + self.assertEqual(archive.read_bytes(), payload) + + +@override_settings( + LOCAL_ACCOUNT_BACKUPS=True, + LOCAL_ACCOUNT_BACKUP_MAIL=False, + LOCAL_MAILBOX_RESTORE=False, + REMOTE_ACCOUNT_BACKUP_MAIL=True, + REMOTE_MAILBOX_RESTORE=True, +) +class RemoteMailboxArchiveTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.account = HostingAccount.objects.create( + name="Fixture", primary_domain="account.example" + ) + cls.domain = HostingMailDomain.objects.create( + account=cls.account, domain="account.example" + ) + cls.mailbox = HostingMailbox.objects.create( + mail_domain=cls.domain, local_part="help" + ) + + def test_scheduler_queues_and_dispatches_remote_mail_in_the_same_backup( + self, + ): + AccountBackupSchedule.objects.create( + account=self.account, + include_mailboxes=True, + enabled=True, + next_run_at=timezone.now() - timedelta(hours=1), + time=timezone.now().time(), + ) + queue_due_account_backups(timezone.now()) + job = AccountBackupJob.objects.get(account=self.account) + self.assertTrue(job.remote_mail) + self.assertIsNotNone(job.scheduled_for) + with patch( + "coulobre.hosting.tasks.create_local_account_backup", + return_value=300, + ) as run: + create_account_backup(job.pk) + request = run.call_args.args[0] + self.assertEqual( + AccountBackupRequest.from_manifest(request.manifest()), request + ) + self.assertTrue(request.remote_mail) + self.assertEqual(request.backup.mailboxes, (self.mailbox.spec,)) + job.refresh_from_db() + self.assertEqual(job.archive_bytes, 300) + + def test_backup_fails_if_queued_address_is_no_longer_owned(self): + job = AccountBackupJob.objects.create( + account=self.account, + remote_mail=True, + manifest=account_backup_manifest( + self.account, include_mailboxes=True + ), + ) + new_account = HostingAccount.objects.create( + name="Other", primary_domain="other.example" + ) + self.domain.account = new_account + self.domain.save(update_fields=["account"]) + with patch( + "coulobre.hosting.tasks.create_local_account_backup" + ) as run: + create_account_backup(job.pk) + run.assert_not_called() + job.refresh_from_db() + self.assertIn("no longer belongs", job.problem) + + def test_uncertain_restore_retries_the_same_request(self): + backup = AccountBackupJob.objects.create( + account=self.account, + manifest=account_backup_manifest( + self.account, include_mailboxes=True + ), + finished_at=timezone.now(), + ) + self.client.force_login(self.operator) + action = reverse( + "panel:mailbox_restore", args=[self.account.pk, backup.pk] + ) + identifier = uuid4() + self.assertRedirects( + self.client.post( + action, + {"restore_id": str(identifier), "resource": str(self.mailbox)}, + ), + self.account.get_absolute_url(), + ) + job = ComponentRestoreJob.objects.get(restore_id=identifier) + self.assertTrue(job.remote_mail) + with patch( + "coulobre.hosting.tasks.restore_local_component", + side_effect=(OSError("lost reply"), None), + ) as restore: + restore_backup_component(job.pk) + job.refresh_from_db() + self.assertEqual(job.problem, UNCONFIRMED_REMOTE_RESTORE) + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "Retry remote restore", + ) + retry = reverse( + "panel:mailbox_restore_retry", args=[self.account.pk, job.pk] + ) + self.assertRedirects( + self.client.post(retry), self.account.get_absolute_url() + ) + restore_backup_component(job.pk) + job.refresh_from_db() + self.assertEqual(job.state, "configured") + self.assertEqual(restore.call_args_list[0], restore.call_args_list[1]) + request = restore.call_args.args[0] + self.assertEqual( + ComponentRestoreRequest.from_manifest(request.manifest()), request + ) + self.assertEqual(request.restore_id, identifier) + self.assertEqual(ComponentRestoreJob.objects.count(), 1) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index cba9a94..9577432 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -117,6 +117,11 @@ urlpatterns = [ views.RequestComponentRestore.as_view(kind=RestoreKind.MAILBOX), name="mailbox_restore", ), + path( + "accounts//restores//retry-mailbox/", + views.RetryRemoteMailRestore.as_view(), + name="mailbox_restore_retry", + ), path( "accounts//sftp/", views.SiteSFTPKeys.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 5b34639..a6303ef 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -51,6 +51,7 @@ from .account_backup_forms import ( ) from .account_backups import ( account_backup_manifest, + mail_backups_enabled, queue_account_backup, save_backup_schedule, ) @@ -61,6 +62,7 @@ from .backup_restores import ( enabled_component_restores, queue_component_restore, queue_website_restore, + retry_remote_mail_restore, ) from .backup_retention import change_backup_retention, protect_backup from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record @@ -458,7 +460,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): and not can_view_mailboxes ) context["account_backup_allow_mail"] = ( - settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes + mail_backups_enabled() and can_view_mailboxes ) schedule = getattr(self.object, "backup_schedule", None) if ( @@ -800,7 +802,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): raise Http404 include_mailboxes = request.POST.get("include_mail") == "1" if include_mailboxes: - if not settings.LOCAL_ACCOUNT_BACKUP_MAIL: + if not mail_backups_enabled(): raise Http404 if not request.user.has_perm(VIEW_MAILBOXES): return self.handle_no_permission() @@ -991,6 +993,9 @@ def backup_restore_context(account, user, backups, can_view_mailboxes): context["backup_restore_jobs"] = sorted( history, key=attrgetter("requested_at"), reverse=True )[:10] + context["allow_remote_restore_retry"] = ( + settings.REMOTE_MAILBOX_RESTORE and RestoreKind.MAILBOX in kinds + ) return context @@ -1102,6 +1107,28 @@ class RequestComponentRestore(BackupRestoreView): ) +class RetryRemoteMailRestore(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = COMPONENT_RESTORE_PERMISSIONS[RestoreKind.MAILBOX] + + def post(self, request, pk, restore_pk): + if not ( + settings.LOCAL_ACCOUNT_BACKUPS and settings.REMOTE_MAILBOX_RESTORE + ): + raise Http404 + job = get_object_or_404( + ComponentRestoreJob.objects.select_related("backup"), + pk=restore_pk, + backup__account_id=pk, + kind=RestoreKind.MAILBOX, + remote_mail=True, + ) + try: + retry_remote_mail_restore(job, request.user.get_username()) + except ValidationError as error: + return provisioning_conflict(error) + return redirect("panel:account", pk=pk) + + class EditAccountBackupSchedule( OperatorOnlyMixin, PermissionRequiredMixin, FormView ): @@ -1134,7 +1161,7 @@ class EditAccountBackupSchedule( def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["allow_mail"] = ( - settings.LOCAL_ACCOUNT_BACKUP_MAIL + mail_backups_enabled() and self.request.user.has_perm(VIEW_MAILBOXES) ) return kwargs diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index fc4a2e8..77539c8 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -250,6 +250,9 @@ LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1" LOCAL_ACCOUNT_BACKUP_MAIL = ( os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1" ) +REMOTE_ACCOUNT_BACKUP_MAIL = ( + os.environ.get("COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL") == "1" +) LOCAL_BACKUP_RETENTION = ( LOCAL_ACCOUNT_BACKUPS and os.environ.get("COULOBRE_LOCAL_BACKUP_RETENTION") == "1" @@ -266,6 +269,16 @@ LOCAL_MAILBOX_RESTORE = ( LOCAL_ACCOUNT_BACKUPS and os.environ.get("COULOBRE_LOCAL_MAILBOX_RESTORE") == "1" ) +REMOTE_MAILBOX_RESTORE = ( + LOCAL_ACCOUNT_BACKUPS + and os.environ.get("COULOBRE_REMOTE_MAILBOX_RESTORE") == "1" +) +if (LOCAL_ACCOUNT_BACKUP_MAIL and REMOTE_ACCOUNT_BACKUP_MAIL) or ( + LOCAL_MAILBOX_RESTORE and REMOTE_MAILBOX_RESTORE +): + raise ImproperlyConfigured( + "Choose one mailbox transport for backup and one for restore." + ) CELERY_BEAT_SCHEDULE = { "dispatch-account-retirements": { "task": "coulobre.hosting.tasks.dispatch_account_retirements",