Files
coulobre/src/coulobre/mail_node.py
T

224 lines
7.6 KiB
Python

import argparse
import json
import re
from dataclasses import dataclass
from pathlib import Path
from .domain_names import canonical_domain
from .node_requests import serve_apply_request
from .node_retirement import RetirementRequest, parse_retirement
from .service_access import ServiceAccessRequest, parse_service_request
MANIFEST_VERSION = 1
QUOTA_MANIFEST_VERSION = 2
MANIFEST_KIND = "virtual_mailbox"
LOCAL_PART_MAX_LENGTH = 64
MAX_MAILBOX_QUOTA_MIB = 2**31 - 1
INVALID_LOCAL_PART = (
"Use 1 to 64 letters, digits, dots, underscores, or hyphens. "
"Start and end with a letter or digit and avoid consecutive dots."
)
@dataclass(frozen=True)
class MailboxSpec:
domain: str
local_part: str
quota_mib: int | None = None
def __post_init__(self):
if not isinstance(self.domain, str):
raise ValueError("Enter a valid mail domain.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
if (
not isinstance(self.local_part, str)
or not self.local_part.isascii()
):
raise ValueError(INVALID_LOCAL_PART)
local_part = self.local_part.lower()
if (
len(local_part) > LOCAL_PART_MAX_LENGTH
or not re.fullmatch(
r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?", local_part
)
or ".." in local_part
):
raise ValueError(INVALID_LOCAL_PART)
object.__setattr__(self, "local_part", local_part)
if len(self.address) > 254:
raise ValueError(
"The full mailbox address must be at most 254 characters."
)
if self.quota_mib is not None and (
type(self.quota_mib) is not int
or not 1 <= self.quota_mib <= MAX_MAILBOX_QUOTA_MIB
):
raise ValueError(
f"The mailbox storage limit must be between 1 and "
f"{MAX_MAILBOX_QUOTA_MIB} MiB."
)
@property
def address(self):
return f"{self.local_part}@{self.domain}"
def manifest(self):
result = {
"version": MANIFEST_VERSION,
"kind": MANIFEST_KIND,
"domain": self.domain,
"local_part": self.local_part,
}
if self.quota_mib is not None:
result["version"] = QUOTA_MANIFEST_VERSION
result["quota_mib"] = self.quota_mib
return result
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND:
raise ValueError("Expected a virtual mailbox manifest.")
version = data.get("version")
if type(version) is not int or version not in (
MANIFEST_VERSION,
QUOTA_MANIFEST_VERSION,
):
raise ValueError("Unsupported mailbox manifest version.")
fields = {"version", "kind", "domain", "local_part"}
if version == QUOTA_MANIFEST_VERSION:
fields.add("quota_mib")
if data.keys() != fields or (
version == QUOTA_MANIFEST_VERSION and data["quota_mib"] is None
):
raise ValueError("Expected a virtual mailbox manifest.")
return cls(data["domain"], data["local_part"], data.get("quota_mib"))
@dataclass(frozen=True)
class MailboxQuotaUpdate:
mailbox: MailboxSpec
def manifest(self):
return {"operation": "set_quota", "mailbox": self.mailbox.manifest()}
def parse_mailbox_request(data):
return parse_retirement(
data, MailboxSpec.from_manifest, parse_mailbox_apply
)
def parse_mailbox_apply(data):
if (
isinstance(data, dict)
and data.keys() == {"operation", "mailbox"}
and data["operation"] == "set_quota"
):
return MailboxQuotaUpdate(MailboxSpec.from_manifest(data["mailbox"]))
return parse_service_request(data, MailboxSpec.from_manifest)
def apply_mailbox_request(request):
if isinstance(request, RetirementRequest):
from .mail_node_retirement import retire_mailbox
retire_mailbox(request)
elif isinstance(request, ServiceAccessRequest):
from .mail_node_quota import set_mailbox_access
set_mailbox_access(request.resource, request.suspended)
elif isinstance(request, MailboxQuotaUpdate):
from .mail_node_quota import set_mailbox_quota
set_mailbox_quota(request.mailbox)
else:
from .mail_node_apply import apply_mailbox
apply_mailbox(request)
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-mail-node")
commands = parser.add_subparsers(dest="command", required=True)
inspect = commands.add_parser(
"inspect", help="Inspect a virtual mailbox manifest."
)
inspect.add_argument("manifest", type=Path)
apply = commands.add_parser(
"apply", help="Install a virtual mailbox on the mail node."
)
apply.add_argument("manifest", type=Path)
quota = commands.add_parser(
"set-quota", help="Change the storage limit of an installed mailbox."
)
quota.add_argument("manifest", type=Path)
commands.add_parser(
"apply-request",
help="Apply one mailbox manifest from standard input and report JSON.",
)
status = commands.add_parser(
"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":
return serve_apply_request(
MANIFEST_VERSION, parse_mailbox_request, apply_mailbox_request
)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
mailbox = MailboxSpec.from_manifest(payload)
if args.command == "apply":
from .mail_node_apply import apply_mailbox
credentials = apply_mailbox(mailbox)
print(f"Applied virtual mailbox {mailbox.address}.")
print(f"Credentials file {credentials}")
elif args.command == "set-quota":
from .mail_node_quota import set_mailbox_quota
set_mailbox_quota(mailbox)
print(
json.dumps(
{
"address": mailbox.address,
"quota_mib": mailbox.quota_mib,
},
indent=2,
)
)
elif args.command == "status":
from .mail_node_apply import mailbox_status
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:
report = {"address": mailbox.address}
if mailbox.quota_mib is not None:
report["quota_mib"] = mailbox.quota_mib
print(json.dumps(report, indent=2))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0