diff --git a/deploy/openssh/coulobre-mail-archive.conf.example b/deploy/openssh/coulobre-mail-archive.conf.example new file mode 100644 index 0000000..e3447cc --- /dev/null +++ b/deploy/openssh/coulobre-mail-archive.conf.example @@ -0,0 +1,20 @@ +Match User coulobre-mail-archive-backup,coulobre-mail-archive-restore + AuthenticationMethods publickey + PubkeyAuthentication yes + PasswordAuthentication no + KbdInteractiveAuthentication no + AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u + AuthorizedKeysCommand none + TrustedUserCAKeys none + DisableForwarding yes + PermitTunnel no + PermitTTY no + PermitUserRC no + +Match User coulobre-mail-archive-backup + ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-backup.sock + +Match User coulobre-mail-archive-restore + ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-restore.sock + +Match all diff --git a/deploy/openssh/mail-archive-client.conf.example b/deploy/openssh/mail-archive-client.conf.example new file mode 100644 index 0000000..4261a55 --- /dev/null +++ b/deploy/openssh/mail-archive-client.conf.example @@ -0,0 +1,22 @@ +Host coulobre-mail-archive-backup + User coulobre-mail-archive-backup + IdentityFile /etc/coulobre-remote/mail-archive-backup/id_ed25519 + UserKnownHostsFile /etc/coulobre-remote/mail-archive-backup/known_hosts + +Host coulobre-mail-archive-restore + User coulobre-mail-archive-restore + IdentityFile /etc/coulobre-remote/mail-archive-restore/id_ed25519 + UserKnownHostsFile /etc/coulobre-remote/mail-archive-restore/known_hosts + +Host coulobre-mail-archive-* + HostName mail.example.org + Port 22 + IdentityAgent none + IdentitiesOnly yes + PreferredAuthentications publickey + GlobalKnownHostsFile none + StrictHostKeyChecking yes + BatchMode yes + ConnectTimeout 5 + ServerAliveInterval 30 + ServerAliveCountMax 3 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/deploy/systemd/coulobre-account-backup@.service.d/remote-mail.conf b/deploy/systemd/coulobre-account-backup@.service.d/remote-mail.conf new file mode 100644 index 0000000..37388e1 --- /dev/null +++ b/deploy/systemd/coulobre-account-backup@.service.d/remote-mail.conf @@ -0,0 +1,2 @@ +[Service] +Environment=COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1 diff --git a/deploy/systemd/coulobre-account-restore@.service.d/remote-mail.conf b/deploy/systemd/coulobre-account-restore@.service.d/remote-mail.conf new file mode 100644 index 0000000..4b311fa --- /dev/null +++ b/deploy/systemd/coulobre-account-restore@.service.d/remote-mail.conf @@ -0,0 +1,2 @@ +[Service] +Environment=COULOBRE_REMOTE_MAILBOX_RESTORE=1 diff --git a/deploy/systemd/coulobre-mail-archive-backup.socket b/deploy/systemd/coulobre-mail-archive-backup.socket new file mode 100644 index 0000000..92f573b --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-backup.socket @@ -0,0 +1,12 @@ +[Unit] +Description=Coulobre mailbox archive backup socket + +[Socket] +ListenStream=/run/coulobre-mail-archive-backup.sock +SocketUser=root +SocketGroup=coulobre-mail-archive-backup +SocketMode=0660 +Accept=yes + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-mail-archive-backup@.service b/deploy/systemd/coulobre-mail-archive-backup@.service new file mode 100644 index 0000000..d5f5adc --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-backup@.service @@ -0,0 +1,22 @@ +[Unit] +Description=Coulobre mailbox archive backup request +After=postfix.service dovecot.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +StateDirectory=coulobre/mail-archive-work +StateDirectoryMode=0700 +UMask=0077 +ExecStart=/opt/coulobre/bin/coulobre-mail-node backup-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=30min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=-/srv/coulobre-mail diff --git a/deploy/systemd/coulobre-mail-archive-backup@.service.d/relay.conf b/deploy/systemd/coulobre-mail-archive-backup@.service.d/relay.conf new file mode 100644 index 0000000..c671ba9 --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-backup@.service.d/relay.conf @@ -0,0 +1,7 @@ +[Service] +User=coulobre-mail-archive-backup +Group=coulobre-mail-archive-backup +StateDirectory= +ReadWritePaths= +ExecStart= +ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-backup diff --git a/deploy/systemd/coulobre-mail-archive-restore.socket b/deploy/systemd/coulobre-mail-archive-restore.socket new file mode 100644 index 0000000..c1ba4e5 --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-restore.socket @@ -0,0 +1,12 @@ +[Unit] +Description=Coulobre mailbox archive restore socket + +[Socket] +ListenStream=/run/coulobre-mail-archive-restore.sock +SocketUser=root +SocketGroup=coulobre-mail-archive-restore +SocketMode=0660 +Accept=yes + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-mail-archive-restore@.service b/deploy/systemd/coulobre-mail-archive-restore@.service new file mode 100644 index 0000000..e7bd6f5 --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-restore@.service @@ -0,0 +1,23 @@ +[Unit] +Description=Coulobre mailbox archive restore request +After=postfix.service dovecot.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +StateDirectory=coulobre/mail-archive-work coulobre/mail-archive-restores +StateDirectoryMode=0700 +UMask=0077 +ExecStart=/opt/coulobre/bin/coulobre-mail-node restore-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=30min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=-/srv/coulobre-mail +CapabilityBoundingSet=~CAP_SYS_RESOURCE diff --git a/deploy/systemd/coulobre-mail-archive-restore@.service.d/relay.conf b/deploy/systemd/coulobre-mail-archive-restore@.service.d/relay.conf new file mode 100644 index 0000000..8bc4d6b --- /dev/null +++ b/deploy/systemd/coulobre-mail-archive-restore@.service.d/relay.conf @@ -0,0 +1,7 @@ +[Service] +User=coulobre-mail-archive-restore +Group=coulobre-mail-archive-restore +StateDirectory= +ReadWritePaths= +ExecStart= +ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-restore diff --git a/deploy/tmpfiles.d/coulobre-mail-archive.conf b/deploy/tmpfiles.d/coulobre-mail-archive.conf new file mode 100644 index 0000000..0b6e286 --- /dev/null +++ b/deploy/tmpfiles.d/coulobre-mail-archive.conf @@ -0,0 +1,2 @@ +# Remove abandoned transfer staging files. Keep the restore journal. +e /var/lib/coulobre/mail-archive-work - - - 1d 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/account_backup.py b/src/coulobre/account_backup.py index c74e755..26a144c 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -41,7 +41,7 @@ class AccountBackup: 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) + {mailbox.address for mailbox in self.mailboxes} ): raise ValueError("The account backup lists a mailbox twice.") @@ -180,14 +180,16 @@ def private_path(path, *, new=False): return path -def create_backup(backup, archive, socket): +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) @@ -195,8 +197,19 @@ def create_backup(backup, archive, socket): backup_website(resource, path) elif isinstance(resource, DatabaseSpec): backup_database(resource, socket, path) - else: + 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) diff --git a/src/coulobre/account_backup_request.py b/src/coulobre/account_backup_request.py index 9a374c7..c7eb16b 100644 --- a/src/coulobre/account_backup_request.py +++ b/src/coulobre/account_backup_request.py @@ -16,6 +16,7 @@ from .node_files import check_root_file, locked_root_directory from .node_requests import serve_apply_request REQUEST_VERSION = 1 +REMOTE_MAIL_VERSION = 2 BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups") BACKUP_SOCKET = "/run/coulobre-account-backup.sock" BACKUP_TIMEOUT_SECONDS = 30 * 60 @@ -25,6 +26,7 @@ BACKUP_TIMEOUT_SECONDS = 30 * 60 class AccountBackupRequest: backup_id: UUID backup: AccountBackup + remote_mail: bool = False @classmethod def from_manifest(cls, data): @@ -32,29 +34,39 @@ class AccountBackupRequest: not isinstance(data, dict) or data.keys() != {"version", "backup_id", "backup"} or type(data["version"]) is not int - or data["version"] != REQUEST_VERSION + or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION) or not isinstance(data["backup_id"], str) ): raise ValueError("Expected a local account backup request.") backup_id = UUID(data["backup_id"]) if str(backup_id) != data["backup_id"]: raise ValueError("Expected a canonical backup ID.") - return cls(backup_id, AccountBackup.from_manifest(data["backup"])) + backup = AccountBackup.from_manifest(data["backup"]) + remote_mail = data["version"] == REMOTE_MAIL_VERSION + if remote_mail and backup.mailboxes is None: + raise ValueError( + "Expected mailboxes in the remote backup request." + ) + return cls(backup_id, backup, remote_mail) def manifest(self): return { - "version": REQUEST_VERSION, + "version": self.version, "backup_id": str(self.backup_id), "backup": self.backup.manifest(), } def identity(self): return { - "version": REQUEST_VERSION, + "version": self.version, "backup_id": str(self.backup_id), "account_id": self.backup.website.account_id, } + @property + def version(self): + return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION + def backup_archive(account_id, backup_id): return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip" @@ -95,11 +107,17 @@ def serve_backup_request(): def create_requested_backup(request): if os.geteuid() != 0: raise ValueError("Run create-request as root on the backup node.") - if ( - request.backup.mailboxes is not None - and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1" - ): - raise ValueError("Enable mailbox backups on the local backup node.") + if request.backup.mailboxes is not None: + setting = ( + "COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL" + if request.remote_mail + else "COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL" + ) + if os.environ.get(setting) != "1": + location = "remote" if request.remote_mail else "local" + raise ValueError( + f"Enable mailbox backups on the {location} backup node." + ) with locked_root_directory(BACKUP_DIRECTORY): archive = ensure_requested_archive(request) return {"archive_bytes": archive.stat().st_size} @@ -112,7 +130,12 @@ def ensure_requested_archive(request): if os.path.lexists(expiration_marker(archive)): raise ValueError("This account backup has expired.") if not os.path.lexists(archive): - create_backup(request.backup, archive, DEFAULT_SOCKET) + if request.remote_mail: + create_backup( + request.backup, archive, DEFAULT_SOCKET, remote_mail=True + ) + else: + create_backup(request.backup, archive, DEFAULT_SOCKET) return archive check_root_file(archive, mode=0o600) diff --git a/src/coulobre/account_restore_request.py b/src/coulobre/account_restore_request.py index 369302d..f9ca2a0 100644 --- a/src/coulobre/account_restore_request.py +++ b/src/coulobre/account_restore_request.py @@ -18,6 +18,7 @@ from .node_requests import serve_apply_request from .web_node import WebSite REQUEST_VERSION = 1 +REMOTE_MAIL_VERSION = 2 RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores") RESTORE_SOCKET = "/run/coulobre-account-restore.sock" RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS @@ -94,6 +95,7 @@ class ComponentRestoreRequest: backup_id: UUID account_id: int resource: DatabaseSpec | MailboxSpec + remote_mail: bool = False def __post_init__(self): if ( @@ -106,6 +108,8 @@ class ComponentRestoreRequest: and self.resource.account_id != self.account_id ): raise ValueError("The database must belong to the backup account.") + if self.remote_mail and not isinstance(self.resource, MailboxSpec): + raise ValueError("Remote mail restore requires a mailbox.") @classmethod def from_manifest(cls, data): @@ -114,7 +118,7 @@ class ComponentRestoreRequest: or data.keys() != {"version", "restore_id", "backup_id", "account_id", "resource"} or type(data["version"]) is not int - or data["version"] != REQUEST_VERSION + or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION) or not isinstance(data["resource"], dict) ): raise ValueError("Expected a local component restore request.") @@ -129,11 +133,14 @@ class ComponentRestoreRequest: parse_uuid(data["backup_id"]), data["account_id"], spec, + data["version"] == REMOTE_MAIL_VERSION, ) def manifest(self): return { - "version": REQUEST_VERSION, + "version": REMOTE_MAIL_VERSION + if self.remote_mail + else REQUEST_VERSION, "restore_id": str(self.restore_id), "backup_id": str(self.backup_id), "account_id": self.account_id, @@ -193,7 +200,10 @@ def restore_requested_website(request): def restore_requested_component(request): - if isinstance(request.resource, DatabaseSpec): + if request.remote_mail: + setting = "COULOBRE_REMOTE_MAILBOX_RESTORE" + feature = "remote mailbox" + elif isinstance(request.resource, DatabaseSpec): setting = "COULOBRE_LOCAL_DATABASE_RESTORE" feature = "database" else: @@ -203,14 +213,19 @@ def restore_requested_component(request): raise ValueError( f"Enable local {feature} restores on the backup node." ) - apply_restore_once(request, restore_component_from_bundle) + if request.remote_mail: + # The destination owns the restore claim across SSH disconnects. + restore_component_from_bundle(request) + else: + apply_restore_once(request, restore_component_from_bundle) -def apply_restore_once(request, restore): +def apply_restore_once(request, restore, *, journal=None): if os.geteuid() != 0: raise ValueError("Run the account restore as root on the backup node.") - with locked_root_directory(RESTORE_DIRECTORY) as directory: - claim = RESTORE_DIRECTORY / f"{request.restore_id}.json" + journal = RESTORE_DIRECTORY if journal is None else journal + with locked_root_directory(journal) as directory: + claim = journal / f"{request.restore_id}.json" result = claim.with_suffix(".result") manifest = json.dumps(request.manifest()) try: @@ -259,6 +274,10 @@ def restore_website_from_bundle(request): def restore_component_from_bundle(request): from .database_node_backup import restore_database + from .mail_archive_transport import ( + UNCONFIRMED_REMOTE_RESTORE, + upload_mailbox_restore, + ) from .mail_node_backup import restore_mailbox resource = request.resource @@ -270,6 +289,11 @@ def restore_component_from_bundle(request): ) as staged: if isinstance(resource, DatabaseSpec): restore_database(resource, DEFAULT_SOCKET, staged) + elif request.remote_mail: + try: + upload_mailbox_restore(resource, staged, request.restore_id) + except OSError: + raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None else: restore_mailbox(resource, staged) 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 %}