Add native Dovecot mailbox backups and restore

This commit is contained in:
parkel committed 2026-11-21 12:21:15 +01:00
1 parent 41369b9ffd
commit 55d209f9e5
4 files changed
+385 -4

No files matched your search

@@ -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],
)
+18
View File
@@ -95,6 +95,16 @@ def main(argv=None):
"status", help="Check an installed virtual mailbox." "status", help="Check an installed virtual mailbox."
) )
status.add_argument("manifest", type=Path) 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) args = parser.parse_args(argv)
if args.command == "apply-request": if args.command == "apply-request":
@@ -119,6 +129,14 @@ def main(argv=None):
report = mailbox_status(mailbox) report = mailbox_status(mailbox)
print(json.dumps(report, indent=2)) print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 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: else:
print(json.dumps({"address": mailbox.address}, indent=2)) print(json.dumps({"address": mailbox.address}, indent=2))
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
+5 -4
View File
@@ -129,7 +129,8 @@ def mailbox_status(mailbox):
try: try:
with locked_state(create=False): 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 problem = None
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
state = "needs_attention" state = "needs_attention"
@@ -137,7 +138,7 @@ def mailbox_status(mailbox):
return {"address": mailbox.address, "state": state, "problem": problem} 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): for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory) require_root_directory(directory)
account, auth_group = check_services(mailbox) account, auth_group = check_services(mailbox)
@@ -153,7 +154,7 @@ def check_mailbox(mailbox):
raise ValueError( raise ValueError(
"The mailbox has resources outside Coulobre's registry." "The mailbox has resources outside Coulobre's registry."
) )
return "not_installed" return None
record = load_credentials(path) record = load_credentials(path)
if not home_is_prepared(record): if not home_is_prepared(record):
@@ -194,7 +195,7 @@ def check_mailbox(mailbox):
raise ValueError( raise ValueError(
"Dovecot could not authenticate the saved mailbox login." "Dovecot could not authenticate the saved mailbox login."
) from None ) from None
return "configured" return account
def install_mailbox(mailbox, state_directory): def install_mailbox(mailbox, state_directory):
+232
View File
@@ -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.")