diff --git a/docs/deployment.md b/docs/deployment.md index 46784e4..a5a8780 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -422,3 +422,7 @@ mailbox requests and the **Can add mailbox provisioning** permission. The initial password stays in the root-only credentials file on the mail node. To locate that file, download the manifest and use the node's `apply` command. Reapplying the manifest preserves the password and prints the file path. + +Back up mail on the node that hosts the mailbox. The archive can be used to +recover messages and folders into a newly provisioned mailbox with the same +address. [Mailbox backup and restore](development.md#back-up-and-restore-a-mailbox) diff --git a/docs/development.md b/docs/development.md index dbe748e..412bfb4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -487,6 +487,39 @@ installation needs attention. Exit code `1` indicates an invalid manifest or an invocation error such as running the check without root privileges. +### Back up and restore a mailbox + +Download the mailbox manifest from the panel and run the backup on the node +that hosts the mailbox. Use a new archive name in a root-controlled directory. + +```sh +sudo install -d -m 0700 /var/backups/coulobre +sudo /opt/coulobre/bin/coulobre-mail-node backup-mailbox \ + coulobre-mailbox-1.json /var/backups/coulobre/mailbox-1.tar.gz +``` + +Coulobre uses Dovecot to copy the managed mailbox into temporary Maildir +storage before creating the archive. Allow space for that copy on the mail +volume. The archive contains messages, folders, IMAP flags, and subscriptions. +Mailbox passwords and node configuration stay on the node. If Dovecot reports +an incomplete sync, retry when the mailbox is idle. +[Dovecot backup command](https://doc.dovecot.org/2.4.4/core/man/doveadm-backup.1.html) + +To recover mail, apply the original mailbox manifest on the destination node. +Use a newly provisioned mailbox that has received no delivery or client +access and has no existing `Maildir`. Keep delivery and client access paused +for that mailbox until recovery completes. Keep Postfix and Dovecot running +for the local configuration checks. Transfer the archive if needed and +ensure it is owned by root with mode `0600`. + +```sh +sudo /opt/coulobre/bin/coulobre-mail-node restore-mailbox \ + coulobre-mailbox-1.json /var/backups/coulobre/mailbox-1.tar.gz +``` + +The node checks the address and validates the archive before publishing the +restored Maildir. Sign in with the destination mailbox's credentials. + ### Enable local mailbox provisioning On a mail node with the same Postfix and Dovecot setup, install Coulobre in a diff --git a/src/coulobre/directadmin.py b/src/coulobre/directadmin.py index c62e55a..03f4459 100644 --- a/src/coulobre/directadmin.py +++ b/src/coulobre/directadmin.py @@ -1,6 +1,7 @@ import argparse import gzip import json +import os import re import subprocess import tarfile @@ -8,6 +9,7 @@ import zlib from contextlib import contextmanager from dataclasses import dataclass, field from pathlib import Path, PurePosixPath +from shutil import copyfileobj from .domain_names import canonical_domain from .mail_node import MailboxSpec @@ -259,6 +261,17 @@ def backup_members(archive): check_tar_padding(archive) +def copy_member(archive, member, target): + if member.size < 0: + raise ValueError("A file in the backup has an invalid size.") + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("xb") as output, archive.extractfile(member) as source: + os.fchmod(output.fileno(), 0o600) + copyfileobj(source, output, length=1024 * 1024) + if output.tell() != member.size: + raise ValueError("A file in the backup is incomplete.") + + def inspect_backup(path): inventory = BackupInventory() with open_backup(path) as archive: diff --git a/src/coulobre/directadmin_website.py b/src/coulobre/directadmin_website.py index 914f248..43f6d98 100644 --- a/src/coulobre/directadmin_website.py +++ b/src/coulobre/directadmin_website.py @@ -1,13 +1,12 @@ -import os from contextlib import suppress from pathlib import Path -from shutil import copyfileobj from tempfile import TemporaryDirectory from .directadmin import ( DOCUMENT_ROOTS, BackupInventory, backup_members, + copy_member, member_path, open_backup, ) @@ -105,14 +104,3 @@ def copy_website(backup, domain, source_root, destination, *, on_copy=None): "bytes": total_bytes, "skipped_non_regular_entries": skipped, } - - -def copy_member(archive, member, target): - if member.size < 0: - raise ValueError("A website file has an invalid size in the archive.") - target.parent.mkdir(parents=True, exist_ok=True) - with target.open("xb") as output, archive.extractfile(member) as source: - os.fchmod(output.fileno(), 0o600) - copyfileobj(source, output, length=1024 * 1024) - if output.tell() != member.size: - raise ValueError("A website file in the archive is incomplete.") diff --git a/src/coulobre/hosting/test_mail_node_backup.py b/src/coulobre/hosting/test_mail_node_backup.py new file mode 100644 index 0000000..be7f183 --- /dev/null +++ b/src/coulobre/hosting/test_mail_node_backup.py @@ -0,0 +1,130 @@ +import json +import os +import stat +import tarfile +from contextlib import nullcontext, redirect_stdout +from io import BytesIO, StringIO +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch + +from django.test import SimpleTestCase + +from coulobre import mail_node_backup +from coulobre.mail_node import MailboxSpec, main + +MESSAGE = b"Subject: Fixture\r\n\r\nTest mail." + + +class MailboxBackupTests(SimpleTestCase): + def setUp(self): + directory = Path(self.enterContext(TemporaryDirectory())) + self.mailbox = MailboxSpec("example.net", "support") + self.home = directory / "home" + self.home.mkdir(mode=0o700) + self.archive = directory / "mailbox.tar.gz" + self.manifest = directory / "mailbox.json" + self.manifest.write_text(json.dumps(self.mailbox.manifest())) + self.account = SimpleNamespace(pw_uid=os.getuid(), pw_gid=os.getgid()) + self.enterContext(patch.object(os, "geteuid", return_value=0)) + self.enterContext( + patch.object(mail_node_backup, "require_root_directory") + ) + self.enterContext(patch.object(mail_node_backup, "check_root_file")) + self.enterContext( + patch.object( + mail_node_backup, + "managed_mailbox", + side_effect=lambda mailbox: nullcontext( + (self.home, self.account) + ), + ) + ) + self.enterContext(patch.object(os, "chown")) + + def make_archive(self, mailbox=None): + metadata = json.dumps( + { + "version": 1, + "kind": "coulobre_mailbox_backup", + "mailbox": (mailbox or self.mailbox).manifest(), + } + ).encode() + with tarfile.open(self.archive, "w:gz") as output: + manifest = tarfile.TarInfo("manifest.json") + manifest.size = len(metadata) + output.addfile(manifest, BytesIO(metadata)) + for name in ("Maildir", "Maildir/new"): + directory = tarfile.TarInfo(name) + directory.type = tarfile.DIRTYPE + output.addfile(directory) + message = tarfile.TarInfo("Maildir/new/first") + message.size = len(MESSAGE) + message.mtime = 1680000000 + output.addfile(message, BytesIO(MESSAGE)) + + def test_restore_publishes_maildir_with_message_timestamp(self): + self.make_archive() + + with redirect_stdout(StringIO()) as output: + self.assertEqual( + main( + ["restore-mailbox", str(self.manifest), str(self.archive)] + ), + 0, + ) + + destination = self.home / "Maildir" + self.assertEqual( + json.loads(output.getvalue())["maildir"], str(destination) + ) + message = destination / "new" / "first" + self.assertEqual(message.read_bytes(), MESSAGE) + self.assertEqual(message.stat().st_mtime, 1680000000) + self.assertEqual(stat.S_IMODE(message.stat().st_mode), 0o600) + for name in ("cur", "new", "tmp"): + self.assertTrue((destination / name).is_dir()) + + def test_restore_refuses_an_existing_maildir(self): + self.make_archive() + in_use = self.home / "Maildir" + in_use.mkdir() + marker = in_use / "existing" + marker.write_bytes(b"mail already present") + + with self.assertRaisesMessage(ValueError, "no existing Maildir"): + mail_node_backup.restore_mailbox(self.mailbox, self.archive) + + self.assertEqual(marker.read_bytes(), b"mail already present") + + def test_restore_refuses_a_backup_for_another_address(self): + self.make_archive(MailboxSpec("example.net", "another")) + + with self.assertRaisesMessage(ValueError, "a different mailbox"): + mail_node_backup.restore_mailbox(self.mailbox, self.archive) + + self.assertFalse((self.home / "Maildir").exists()) + + def test_corrupt_backup_leaves_no_restored_maildir(self): + self.make_archive() + self.archive.write_bytes(self.archive.read_bytes()[:-4]) + + with self.assertRaisesMessage(ValueError, "complete tar archive"): + mail_node_backup.restore_mailbox(self.mailbox, self.archive) + + self.assertFalse((self.home / "Maildir").exists()) + + def test_incomplete_dovecot_sync_leaves_no_archive(self): + with ( + patch.object(mail_node_backup.subprocess, "run") as command, + self.assertRaisesMessage(ValueError, "Retry the backup"), + ): + command.return_value.returncode = 2 + mail_node_backup.backup_mailbox(self.mailbox, self.archive) + + self.assertFalse(self.archive.exists()) + self.assertEqual( + command.call_args.args[0][:4], + ["/usr/bin/doveadm", "backup", "-u", self.mailbox.address], + ) diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index d534e95..964af3a 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -95,6 +95,16 @@ def main(argv=None): "status", help="Check an installed virtual mailbox." ) status.add_argument("manifest", type=Path) + backup = commands.add_parser( + "backup-mailbox", help="Back up the Maildir of a managed mailbox." + ) + backup.add_argument("manifest", type=Path) + backup.add_argument("archive", type=Path) + restore = commands.add_parser( + "restore-mailbox", help="Recover mail into a fresh managed mailbox." + ) + restore.add_argument("manifest", type=Path) + restore.add_argument("archive", type=Path) args = parser.parse_args(argv) if args.command == "apply-request": @@ -119,6 +129,14 @@ def main(argv=None): report = mailbox_status(mailbox) print(json.dumps(report, indent=2)) return 0 if report["state"] == "configured" else 2 + elif args.command == "backup-mailbox": + from .mail_node_backup import backup_mailbox + + print(json.dumps(backup_mailbox(mailbox, args.archive), indent=2)) + elif args.command == "restore-mailbox": + from .mail_node_backup import restore_mailbox + + print(json.dumps(restore_mailbox(mailbox, args.archive), indent=2)) else: print(json.dumps({"address": mailbox.address}, indent=2)) except (OSError, ValueError) as error: diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index 3fd03cb..78b4cd1 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -129,7 +129,8 @@ def mailbox_status(mailbox): try: with locked_state(create=False): - state = check_mailbox(mailbox) + account = configured_mail_account(mailbox) + state = "configured" if account is not None else "not_installed" problem = None except (OSError, ValueError) as error: state = "needs_attention" @@ -137,7 +138,7 @@ def mailbox_status(mailbox): return {"address": mailbox.address, "state": state, "problem": problem} -def check_mailbox(mailbox): +def configured_mail_account(mailbox): for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent): require_root_directory(directory) account, auth_group = check_services(mailbox) @@ -153,7 +154,7 @@ def check_mailbox(mailbox): raise ValueError( "The mailbox has resources outside Coulobre's registry." ) - return "not_installed" + return None record = load_credentials(path) if not home_is_prepared(record): @@ -194,7 +195,7 @@ def check_mailbox(mailbox): raise ValueError( "Dovecot could not authenticate the saved mailbox login." ) from None - return "configured" + return account def install_mailbox(mailbox, state_directory): diff --git a/src/coulobre/mail_node_backup.py b/src/coulobre/mail_node_backup.py new file mode 100644 index 0000000..7bd7061 --- /dev/null +++ b/src/coulobre/mail_node_backup.py @@ -0,0 +1,232 @@ +import json +import os +import stat +import subprocess +from contextlib import contextmanager +from pathlib import Path +from tempfile import NamedTemporaryFile, TemporaryDirectory + +from . import mail_node_apply +from .directadmin import backup_members, copy_member, member_path, open_backup +from .mail_node import MailboxSpec +from .node_files import check_root_file, require_root_directory, write_new_file + +BACKUP_VERSION = 1 +BACKUP_KIND = "coulobre_mailbox_backup" +METADATA_NAME = "manifest.json" +MAILDIR = "Maildir" +MAILDIR_FOLDERS = ("cur", "new", "tmp") +COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} + + +def backup_mailbox(mailbox, archive): + if os.geteuid() != 0: + raise ValueError("Run backup-mailbox as root on the mail node.") + archive = archive.absolute() + require_root_directory(archive.parent) + if os.path.lexists(archive): + raise ValueError("Choose a new mailbox backup filename.") + + with ( + managed_mailbox(mailbox) as (home, account), + TemporaryDirectory(dir=home.parent) as directory, + ): + scratch = Path(directory) + scratch.chmod(0o711) + snapshot = scratch / MAILDIR + mail_node_apply.ensure_mail_home(snapshot, account, create=True) + copy_mailbox(mailbox, snapshot) + check_snapshot(snapshot) + metadata = { + "version": BACKUP_VERSION, + "kind": BACKUP_KIND, + "mailbox": mailbox.manifest(), + } + write_new_file( + scratch / METADATA_NAME, json.dumps(metadata), mode=0o444 + ) + with NamedTemporaryFile(dir=archive.parent) as staged: + archive_snapshot(scratch, account, staged) + staged.flush() + os.fsync(staged.fileno()) + os.link(staged.name, archive) + + return { + "kind": BACKUP_KIND, + "address": mailbox.address, + "archive": str(archive), + } + + +def restore_mailbox(mailbox, archive): + if os.geteuid() != 0: + raise ValueError("Run restore-mailbox as root on the mail node.") + archive = archive.absolute() + require_root_directory(archive.parent) + check_root_file(archive, mode=0o600) + with managed_mailbox(mailbox) as (home, account): + destination = home / MAILDIR + check_fresh_maildir(destination) + with TemporaryDirectory(dir=home.parent) as directory: + scratch = Path(directory) + extract_maildir(mailbox, archive, scratch, account) + check_fresh_maildir(destination) + (scratch / MAILDIR).rename(destination) + + return { + "kind": "coulobre_mailbox_restore", + "address": mailbox.address, + "maildir": str(destination), + } + + +@contextmanager +def managed_mailbox(mailbox): + with mail_node_apply.locked_state(create=False): + account = mail_node_apply.configured_mail_account(mailbox) + if account is None: + raise ValueError( + "Apply the mailbox manifest on the mail node first." + ) + yield mail_node_apply.mailbox_home(mailbox), account + + +def check_fresh_maildir(destination): + if os.path.lexists(destination): + raise ValueError( + "Restore requires a mailbox with no existing Maildir." + ) + + +def copy_mailbox(mailbox, snapshot): + result = subprocess.run( + [ + "/usr/bin/doveadm", + "backup", + "-u", + mailbox.address, + f"maildir:{snapshot}", + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=COMMAND_ENV, + ) + if result.returncode == 2: + raise ValueError( + "Dovecot did not complete the mailbox sync. Retry the backup." + ) + if result.returncode: + raise ValueError( + f"Dovecot mailbox backup failed ({result.returncode})." + ) + + +def check_snapshot(snapshot): + def raise_walk_error(error): + raise error + + for directory, directories, files in snapshot.walk( + on_error=raise_walk_error + ): + for filename in directories + files: + mode = (directory / filename).lstat().st_mode + if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)): + raise ValueError( + "The mailbox backup contains an unsupported entry." + ) + + +def archive_snapshot(directory, account, output): + result = subprocess.run( + [ + "/usr/bin/tar", + "--create", + "--gzip", + "--file=-", + "--format=pax", + "--hard-dereference", + "--directory", + str(directory), + "--", + METADATA_NAME, + MAILDIR, + ], + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.DEVNULL, + user=account.pw_uid, + group=account.pw_gid, + extra_groups=[], + env=COMMAND_ENV, + ) + if result.returncode: + raise ValueError( + f"Could not archive the mailbox snapshot ({result.returncode})." + ) + + +def extract_maildir(mailbox, backup, directory, account): + root = directory / MAILDIR + with open_backup(backup) as archive: + members = backup_members(archive) + validate_metadata(archive, next(members, None), mailbox) + for member in members: + parts = member_path(member) + if not parts or parts[0] != MAILDIR: + raise ValueError( + "The mailbox backup contains an unexpected path." + ) + target = directory.joinpath(*parts) + if target.exists() or not target.parent.is_dir(): + raise ValueError( + "The mailbox backup contains a duplicate entry " + "or missing directory." + ) + if member.isdir(): + target.mkdir(mode=0o700) + elif member.isreg() and target != root: + copy_member(archive, member, target) + os.utime(target, (member.mtime, member.mtime)) + else: + raise ValueError( + "The mailbox backup contains an unsupported entry." + ) + os.chown( + target, account.pw_uid, account.pw_gid, follow_symlinks=False + ) + if not root.is_dir(): + raise ValueError("The mailbox backup is missing its Maildir.") + for name in MAILDIR_FOLDERS: + path = root / name + if not path.exists(): + path.mkdir(mode=0o700) + os.chown( + path, account.pw_uid, account.pw_gid, follow_symlinks=False + ) + elif not path.is_dir(): + raise ValueError( + "The mailbox backup contains an invalid Maildir folder." + ) + + +def validate_metadata(archive, member, mailbox): + if ( + member is None + or member.name != METADATA_NAME + or not member.isreg() + or not 0 < member.size <= 4096 + ): + raise ValueError("Expected a native mailbox backup manifest.") + with archive.extractfile(member) as source: + metadata = json.load(source) + if ( + not isinstance(metadata, dict) + or metadata.keys() != {"version", "kind", "mailbox"} + or type(metadata["version"]) is not int + or metadata["version"] != BACKUP_VERSION + or metadata["kind"] != BACKUP_KIND + ): + raise ValueError("Expected a supported native mailbox backup.") + if MailboxSpec.from_manifest(metadata["mailbox"]) != mailbox: + raise ValueError("The backup is for a different mailbox.") diff --git a/src/coulobre/web_node_backup.py b/src/coulobre/web_node_backup.py index c365e33..e72698e 100644 --- a/src/coulobre/web_node_backup.py +++ b/src/coulobre/web_node_backup.py @@ -8,8 +8,7 @@ from io import BytesIO from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory -from .directadmin import backup_members, member_path, open_backup -from .directadmin_website import copy_member +from .directadmin import backup_members, copy_member, member_path, open_backup from .node_files import check_root_file, require_root_directory from .web_node_apply import ( SitePaths,