Stream native mailbox archives over a constrained SSH transport
This commit is contained in:
1 parent
d076f111b6
commit
13cb45dfe4
16 files changed
+482
-18
No files matched your search
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
Environment=COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
Environment=COULOBRE_REMOTE_MAILBOX_RESTORE=1
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Remove abandoned transfer staging files. Keep the restore journal.
|
||||||
|
e /var/lib/coulobre/mail-archive-work - - - 1d
|
||||||
@@ -41,7 +41,7 @@ class AccountBackup:
|
|||||||
raise ValueError("The account backup lists a database twice.")
|
raise ValueError("The account backup lists a database twice.")
|
||||||
names.add(database.name)
|
names.add(database.name)
|
||||||
if self.mailboxes is not None and len(self.mailboxes) != len(
|
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.")
|
raise ValueError("The account backup lists a mailbox twice.")
|
||||||
|
|
||||||
@@ -180,14 +180,16 @@ def private_path(path, *, new=False):
|
|||||||
return path
|
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 .database_node_backup import backup_database
|
||||||
|
from .mail_archive_transport import download_mailbox_backup
|
||||||
from .mail_node_backup import backup_mailbox
|
from .mail_node_backup import backup_mailbox
|
||||||
from .web_node_backup import backup_website
|
from .web_node_backup import backup_website
|
||||||
|
|
||||||
archive = private_path(archive, new=True)
|
archive = private_path(archive, new=True)
|
||||||
with TemporaryDirectory(dir=archive.parent) as directory:
|
with TemporaryDirectory(dir=archive.parent) as directory:
|
||||||
directory = Path(directory)
|
directory = Path(directory)
|
||||||
|
captured = 0
|
||||||
for resource, _, filename in backup.components():
|
for resource, _, filename in backup.components():
|
||||||
path = directory / filename
|
path = directory / filename
|
||||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
@@ -195,8 +197,19 @@ def create_backup(backup, archive, socket):
|
|||||||
backup_website(resource, path)
|
backup_website(resource, path)
|
||||||
elif isinstance(resource, DatabaseSpec):
|
elif isinstance(resource, DatabaseSpec):
|
||||||
backup_database(resource, socket, path)
|
backup_database(resource, socket, path)
|
||||||
else:
|
elif not remote_mail:
|
||||||
backup_mailbox(resource, path)
|
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)
|
pack_backup(backup, directory, archive)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from .node_files import check_root_file, locked_root_directory
|
|||||||
from .node_requests import serve_apply_request
|
from .node_requests import serve_apply_request
|
||||||
|
|
||||||
REQUEST_VERSION = 1
|
REQUEST_VERSION = 1
|
||||||
|
REMOTE_MAIL_VERSION = 2
|
||||||
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
|
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
|
||||||
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
|
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
|
||||||
BACKUP_TIMEOUT_SECONDS = 30 * 60
|
BACKUP_TIMEOUT_SECONDS = 30 * 60
|
||||||
@@ -25,6 +26,7 @@ BACKUP_TIMEOUT_SECONDS = 30 * 60
|
|||||||
class AccountBackupRequest:
|
class AccountBackupRequest:
|
||||||
backup_id: UUID
|
backup_id: UUID
|
||||||
backup: AccountBackup
|
backup: AccountBackup
|
||||||
|
remote_mail: bool = False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_manifest(cls, data):
|
def from_manifest(cls, data):
|
||||||
@@ -32,29 +34,39 @@ class AccountBackupRequest:
|
|||||||
not isinstance(data, dict)
|
not isinstance(data, dict)
|
||||||
or data.keys() != {"version", "backup_id", "backup"}
|
or data.keys() != {"version", "backup_id", "backup"}
|
||||||
or type(data["version"]) is not int
|
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)
|
or not isinstance(data["backup_id"], str)
|
||||||
):
|
):
|
||||||
raise ValueError("Expected a local account backup request.")
|
raise ValueError("Expected a local account backup request.")
|
||||||
backup_id = UUID(data["backup_id"])
|
backup_id = UUID(data["backup_id"])
|
||||||
if str(backup_id) != data["backup_id"]:
|
if str(backup_id) != data["backup_id"]:
|
||||||
raise ValueError("Expected a canonical 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):
|
def manifest(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": self.version,
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"backup": self.backup.manifest(),
|
"backup": self.backup.manifest(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def identity(self):
|
def identity(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": self.version,
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"account_id": self.backup.website.account_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):
|
def backup_archive(account_id, backup_id):
|
||||||
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
|
||||||
@@ -95,11 +107,17 @@ def serve_backup_request():
|
|||||||
def create_requested_backup(request):
|
def create_requested_backup(request):
|
||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
raise ValueError("Run create-request as root on the backup node.")
|
raise ValueError("Run create-request as root on the backup node.")
|
||||||
if (
|
if request.backup.mailboxes is not None:
|
||||||
request.backup.mailboxes is not None
|
setting = (
|
||||||
and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1"
|
"COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL"
|
||||||
):
|
if request.remote_mail
|
||||||
raise ValueError("Enable mailbox backups on the local backup node.")
|
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):
|
with locked_root_directory(BACKUP_DIRECTORY):
|
||||||
archive = ensure_requested_archive(request)
|
archive = ensure_requested_archive(request)
|
||||||
return {"archive_bytes": archive.stat().st_size}
|
return {"archive_bytes": archive.stat().st_size}
|
||||||
@@ -112,6 +130,11 @@ def ensure_requested_archive(request):
|
|||||||
if os.path.lexists(expiration_marker(archive)):
|
if os.path.lexists(expiration_marker(archive)):
|
||||||
raise ValueError("This account backup has expired.")
|
raise ValueError("This account backup has expired.")
|
||||||
if not os.path.lexists(archive):
|
if not os.path.lexists(archive):
|
||||||
|
if request.remote_mail:
|
||||||
|
create_backup(
|
||||||
|
request.backup, archive, DEFAULT_SOCKET, remote_mail=True
|
||||||
|
)
|
||||||
|
else:
|
||||||
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
create_backup(request.backup, archive, DEFAULT_SOCKET)
|
||||||
return archive
|
return archive
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from .node_requests import serve_apply_request
|
|||||||
from .web_node import WebSite
|
from .web_node import WebSite
|
||||||
|
|
||||||
REQUEST_VERSION = 1
|
REQUEST_VERSION = 1
|
||||||
|
REMOTE_MAIL_VERSION = 2
|
||||||
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
|
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
|
||||||
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
|
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
|
||||||
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
|
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
|
||||||
@@ -94,6 +95,7 @@ class ComponentRestoreRequest:
|
|||||||
backup_id: UUID
|
backup_id: UUID
|
||||||
account_id: int
|
account_id: int
|
||||||
resource: DatabaseSpec | MailboxSpec
|
resource: DatabaseSpec | MailboxSpec
|
||||||
|
remote_mail: bool = False
|
||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
if (
|
if (
|
||||||
@@ -106,6 +108,8 @@ class ComponentRestoreRequest:
|
|||||||
and self.resource.account_id != self.account_id
|
and self.resource.account_id != self.account_id
|
||||||
):
|
):
|
||||||
raise ValueError("The database must belong to the backup account.")
|
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
|
@classmethod
|
||||||
def from_manifest(cls, data):
|
def from_manifest(cls, data):
|
||||||
@@ -114,7 +118,7 @@ class ComponentRestoreRequest:
|
|||||||
or data.keys()
|
or data.keys()
|
||||||
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
|
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
|
||||||
or type(data["version"]) is not int
|
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)
|
or not isinstance(data["resource"], dict)
|
||||||
):
|
):
|
||||||
raise ValueError("Expected a local component restore request.")
|
raise ValueError("Expected a local component restore request.")
|
||||||
@@ -129,11 +133,14 @@ class ComponentRestoreRequest:
|
|||||||
parse_uuid(data["backup_id"]),
|
parse_uuid(data["backup_id"]),
|
||||||
data["account_id"],
|
data["account_id"],
|
||||||
spec,
|
spec,
|
||||||
|
data["version"] == REMOTE_MAIL_VERSION,
|
||||||
)
|
)
|
||||||
|
|
||||||
def manifest(self):
|
def manifest(self):
|
||||||
return {
|
return {
|
||||||
"version": REQUEST_VERSION,
|
"version": REMOTE_MAIL_VERSION
|
||||||
|
if self.remote_mail
|
||||||
|
else REQUEST_VERSION,
|
||||||
"restore_id": str(self.restore_id),
|
"restore_id": str(self.restore_id),
|
||||||
"backup_id": str(self.backup_id),
|
"backup_id": str(self.backup_id),
|
||||||
"account_id": self.account_id,
|
"account_id": self.account_id,
|
||||||
@@ -193,7 +200,10 @@ def restore_requested_website(request):
|
|||||||
|
|
||||||
|
|
||||||
def restore_requested_component(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"
|
setting = "COULOBRE_LOCAL_DATABASE_RESTORE"
|
||||||
feature = "database"
|
feature = "database"
|
||||||
else:
|
else:
|
||||||
@@ -203,14 +213,19 @@ def restore_requested_component(request):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Enable local {feature} restores on the backup node."
|
f"Enable local {feature} restores on the backup node."
|
||||||
)
|
)
|
||||||
|
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)
|
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:
|
if os.geteuid() != 0:
|
||||||
raise ValueError("Run the account restore as root on the backup node.")
|
raise ValueError("Run the account restore as root on the backup node.")
|
||||||
with locked_root_directory(RESTORE_DIRECTORY) as directory:
|
journal = RESTORE_DIRECTORY if journal is None else journal
|
||||||
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
|
with locked_root_directory(journal) as directory:
|
||||||
|
claim = journal / f"{request.restore_id}.json"
|
||||||
result = claim.with_suffix(".result")
|
result = claim.with_suffix(".result")
|
||||||
manifest = json.dumps(request.manifest())
|
manifest = json.dumps(request.manifest())
|
||||||
try:
|
try:
|
||||||
@@ -259,6 +274,10 @@ def restore_website_from_bundle(request):
|
|||||||
|
|
||||||
def restore_component_from_bundle(request):
|
def restore_component_from_bundle(request):
|
||||||
from .database_node_backup import restore_database
|
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
|
from .mail_node_backup import restore_mailbox
|
||||||
|
|
||||||
resource = request.resource
|
resource = request.resource
|
||||||
@@ -270,6 +289,11 @@ def restore_component_from_bundle(request):
|
|||||||
) as staged:
|
) as staged:
|
||||||
if isinstance(resource, DatabaseSpec):
|
if isinstance(resource, DatabaseSpec):
|
||||||
restore_database(resource, DEFAULT_SOCKET, staged)
|
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:
|
else:
|
||||||
restore_mailbox(resource, staged)
|
restore_mailbox(resource, staged)
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -185,6 +185,12 @@ def main(argv=None):
|
|||||||
"apply-request",
|
"apply-request",
|
||||||
help="Apply one mailbox manifest from standard input and report JSON.",
|
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 = commands.add_parser(
|
||||||
"status", help="Check an installed virtual mailbox."
|
"status", help="Check an installed virtual mailbox."
|
||||||
)
|
)
|
||||||
@@ -201,6 +207,11 @@ def main(argv=None):
|
|||||||
restore.add_argument("archive", type=Path)
|
restore.add_argument("archive", type=Path)
|
||||||
args = parser.parse_args(argv)
|
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":
|
if args.command == "apply-request":
|
||||||
return serve_apply_request(
|
return serve_apply_request(
|
||||||
MANIFEST_VERSION,
|
MANIFEST_VERSION,
|
||||||
|
|||||||
Reference in new issue
Block a user