Stream native mailbox archives over a constrained SSH transport

This commit is contained in:
parkel committed 2026-11-21 22:18:59 +01:00
1 parent d076f111b6
commit 13cb45dfe4
16 files changed
+484 -20

No files matched your search

+16 -3
View File
@@ -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)
+33 -10
View File
@@ -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)
+31 -7
View File
@@ -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)
+262
View File
@@ -0,0 +1,262 @@
import hashlib
import json
import os
import re
import socket
import sys
from dataclasses import dataclass
from pathlib import Path
from shutil import copyfileobj
from tempfile import TemporaryDirectory
from uuid import UUID
from .mail_node import MailboxSpec
BACKUP_RELAY = "/run/coulobre-mail-archive-backup.sock"
RESTORE_RELAY = "/run/coulobre-mail-archive-restore.sock"
WORK_DIRECTORY = Path("/var/lib/coulobre/mail-archive-work")
RESTORE_JOURNAL = Path("/var/lib/coulobre/mail-archive-restores")
TIMEOUT_SECONDS = 30 * 60
HEADER_LIMIT = 8192
CHUNK_SIZE = 1024 * 1024
DIGEST = re.compile(r"[0-9a-f]{64}")
UNCONFIRMED_REMOTE_RESTORE = (
"Could not confirm the remote mailbox restore. Retry the same request."
)
class MailArchiveConnectionError(OSError):
pass
@dataclass(frozen=True)
class MailArchiveRequest:
mailbox: MailboxSpec
restore_id: UUID | None = None
size: int | None = None
digest: str | None = None
def manifest(self):
fields = {
"version": 1,
"operation": "restore" if self.restore_id else "backup",
"mailbox": self.mailbox.manifest(),
}
if self.restore_id:
fields.update(
restore_id=str(self.restore_id),
archive_bytes=self.size,
sha256=self.digest,
)
return fields
@classmethod
def parse(cls, data, operation):
fields = {"version", "operation", "mailbox"}
if operation == "restore":
fields |= {"restore_id", "archive_bytes", "sha256"}
if (
not isinstance(data, dict)
or data.keys() != fields
or type(data["version"]) is not int
or data["version"] != 1
or data["operation"] != operation
):
raise ValueError("Expected a mailbox archive request.")
mailbox = MailboxSpec.from_manifest(data["mailbox"])
if operation == "backup":
return cls(mailbox)
identifier, size, digest = (
data["restore_id"],
data["archive_bytes"],
data["sha256"],
)
if (
not isinstance(identifier, str)
or not valid_size(size)
or not isinstance(digest, str)
or not DIGEST.fullmatch(digest)
):
raise ValueError("Expected a valid mailbox restore identity.")
restore_id = UUID(identifier)
if str(restore_id) != identifier:
raise ValueError("Expected a canonical restore ID.")
return cls(mailbox, restore_id, size, digest)
def valid_size(size):
return type(size) is int and 0 < size < 2**63
def read_header(source):
body = source.readline(HEADER_LIMIT + 1)
if not body.endswith(b"\n") or len(body) > HEADER_LIMIT:
raise MailArchiveConnectionError("Incomplete mailbox archive header.")
try:
return json.loads(body.decode("utf-8"))
except (ValueError, RecursionError):
raise MailArchiveConnectionError(
"Invalid mailbox archive header."
) from None
def encode_header(fields):
return json.dumps(fields, separators=(",", ":")).encode("utf-8") + b"\n"
def receive_archive(source, archive, size, *, digest=None):
calculated = hashlib.sha256() if digest else None
target = archive.open("xb")
try:
with target:
os.fchmod(target.fileno(), 0o600)
remaining = size
while remaining:
data = source.read(min(CHUNK_SIZE, remaining))
if not data:
raise MailArchiveConnectionError(
"The mailbox archive transfer ended early."
)
target.write(data)
if calculated is not None:
calculated.update(data)
remaining -= len(data)
if source.read(1):
raise MailArchiveConnectionError(
"The mailbox archive contains unexpected trailing data."
)
if calculated is not None and calculated.hexdigest() != digest:
raise MailArchiveConnectionError(
"The transferred mailbox archive failed its checksum."
)
except BaseException:
archive.unlink(missing_ok=True)
raise
def connected_to_mail_node(path):
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
client.settimeout(TIMEOUT_SECONDS + 5)
client.connect(path)
except OSError:
client.close()
raise
return client
def node_reply(source, request):
reply = read_header(source)
identity = request.manifest()
if not isinstance(reply, dict) or any(
key not in reply
or type(reply[key]) is not type(value)
or reply[key] != value
for key, value in identity.items()
):
raise MailArchiveConnectionError(
"The mail node returned a different mailbox archive identity."
)
if reply.get("state") == "configured" and reply.get("problem") is None:
return reply
problem = reply.get("problem")
if reply.get("state") == "failed" and isinstance(problem, str) and problem:
raise ValueError(problem[:2000])
raise MailArchiveConnectionError(
"The mail node returned an invalid result."
)
def download_mailbox_backup(mailbox, archive):
request = MailArchiveRequest(mailbox)
with connected_to_mail_node(BACKUP_RELAY) as client:
client.sendall(encode_header(request.manifest()))
client.shutdown(socket.SHUT_WR)
with client.makefile("rb") as source:
reply = node_reply(source, request)
size = reply.get("archive_bytes")
if not valid_size(size):
raise MailArchiveConnectionError(
"The mail node returned an invalid archive size."
)
receive_archive(source, archive, size)
def upload_mailbox_restore(mailbox, archive, restore_id):
with archive.open("rb") as data:
digest = hashlib.file_digest(data, "sha256").hexdigest()
size = os.fstat(data.fileno()).st_size
data.seek(0)
request = MailArchiveRequest(mailbox, restore_id, size, digest)
with connected_to_mail_node(RESTORE_RELAY) as client:
client.sendall(encode_header(request.manifest()))
client.sendfile(data)
client.shutdown(socket.SHUT_WR)
with client.makefile("rb") as source:
node_reply(source, request)
if source.read(1):
raise MailArchiveConnectionError(
"The mail node returned unexpected restore data."
)
def serve_mail_archive(operation):
from .account_restore_request import apply_restore_once
from .mail_node_backup import backup_mailbox, restore_mailbox
from .node_files import require_root_directory
source, output = sys.stdin.buffer, sys.stdout.buffer
identity = {"version": 1, "operation": operation}
try:
if os.geteuid() != 0:
raise ValueError("Run the mail archive service as root.")
request = MailArchiveRequest.parse(read_header(source), operation)
identity = request.manifest()
require_root_directory(WORK_DIRECTORY)
with TemporaryDirectory(dir=WORK_DIRECTORY) as directory:
archive = Path(directory) / "mailbox.tar.gz"
if operation == "backup":
if source.read(1):
raise ValueError("Unexpected mailbox backup request data.")
backup_mailbox(request.mailbox, archive)
with archive.open("rb") as data:
size = os.fstat(data.fileno()).st_size
output.write(
encode_header(
identity
| {
"state": "configured",
"problem": None,
"archive_bytes": size,
}
)
)
copyfileobj(data, output, length=CHUNK_SIZE)
output.flush()
else:
receive_archive(
source, archive, request.size, digest=request.digest
)
apply_restore_once(
request,
lambda job: restore_mailbox(job.mailbox, archive),
journal=RESTORE_JOURNAL,
)
output.write(
encode_header(
identity | {"state": "configured", "problem": None}
)
)
output.flush()
except (BrokenPipeError, MailArchiveConnectionError):
# The caller has no authoritative result after a transfer error.
return 1
except (OSError, ValueError) as error:
output.write(
encode_header(
identity | {"state": "failed", "problem": str(error)[:2000]}
)
)
output.flush()
return 1
return 0
+11
View File
@@ -185,6 +185,12 @@ def main(argv=None):
"apply-request",
help="Apply one mailbox manifest from standard input and report JSON.",
)
commands.add_parser(
"backup-request", help="Stream one native mailbox archive."
)
commands.add_parser(
"restore-request", help="Recover one mailbox from a streamed archive."
)
status = commands.add_parser(
"status", help="Check an installed virtual mailbox."
)
@@ -201,6 +207,11 @@ def main(argv=None):
restore.add_argument("archive", type=Path)
args = parser.parse_args(argv)
if args.command in {"backup-request", "restore-request"}:
from .mail_archive_transport import serve_mail_archive
return serve_mail_archive(args.command.removesuffix("-request"))
if args.command == "apply-request":
return serve_apply_request(
MANIFEST_VERSION,