Provision virtual mailboxes with Postfix and Dovecot

This commit is contained in:
parkel committed 2026-11-19 23:37:11 +01:00
1 parent 4bd7a90580
commit 0804182f17
5 files changed
+551 -2

No files matched your search

@@ -0,0 +1,149 @@
import json
import os
import stat
from pathlib import Path
from subprocess import CompletedProcess
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from django.test import SimpleTestCase
from coulobre.mail_node import MailboxSpec
from coulobre.mail_node_apply import (
apply_mailbox,
credential_path,
ensure_mail_home,
run,
)
class MailboxApplyTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.state = directory / "state"
self.storage = directory / "homes"
self.domains = directory / "domains"
self.mailboxes = directory / "mailboxes"
self.users = directory / "users"
settings = {
"STATE_DIRECTORY": self.state,
"MAIL_ROOT": self.storage,
"POSTFIX_DOMAINS": self.domains,
"POSTFIX_MAILBOXES": self.mailboxes,
"DOVECOT_USERS": self.users,
}
for name, value in settings.items():
self.enterContext(patch(f"coulobre.mail_node_apply.{name}", value))
self.enterContext(patch("coulobre.mail_node_apply.os.geteuid", return_value=0))
self.enterContext(
patch(
"coulobre.mail_node_apply.require_root_directory",
side_effect=self.prepare_directory,
)
)
self.enterContext(
patch(
"coulobre.mail_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
)
)
self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001)
self.enterContext(
patch(
"coulobre.mail_node_apply.check_services",
return_value=(self.account, os.getegid()),
)
)
self.resolve_home = self.enterContext(
patch("coulobre.mail_node_apply.dovecot_home", side_effect=self.lookup_home)
)
self.prepare_home = self.enterContext(
patch("coulobre.mail_node_apply.ensure_mail_home")
)
self.commands = self.enterContext(patch("coulobre.mail_node_apply.run"))
self.commands.return_value = "{SHA512-CRYPT}$6$mockSalt$" + ("A" * 86)
self.spec = MailboxSpec("example.net", "support")
def prepare_directory(self, path, *, create_mode=None):
if create_mode is not None:
path.mkdir(mode=create_mode, exist_ok=True)
def lookup_home(self, mailbox):
if self.users.exists() and f"{mailbox.address}:" in self.users.read_text():
return str(self.storage / mailbox.domain / mailbox.local_part)
return None
def test_reapplying_preserves_password_and_privately_publishes_the_hash(self):
credential_file = apply_mailbox(self.spec)
original = credential_file.read_bytes()
self.assertEqual(apply_mailbox(self.spec), credential_file)
self.assertEqual(credential_file.read_bytes(), original)
self.assertEqual(stat.S_IMODE(credential_file.stat().st_mode), 0o600)
record = json.loads(original)
self.assertIn(record["password_hash"], self.users.read_text())
self.assertNotIn(record["password"], self.users.read_text())
self.assertEqual(stat.S_IMODE(self.users.stat().st_mode), 0o640)
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
self.assertIn("example.net\t1", self.domains.read_text())
def test_pending_mailbox_is_published_only_after_its_home_is_prepared(self):
self.prepare_home.side_effect = ValueError("Interrupted before home creation.")
with self.assertRaisesRegex(ValueError, "Interrupted"):
apply_mailbox(self.spec)
credential_file = credential_path(self.spec)
original = credential_file.read_bytes()
self.assertFalse(self.mailboxes.exists())
self.prepare_home.side_effect = None
apply_mailbox(MailboxSpec("example.net", "sales"))
self.assertIn("sales@example.net\t1", self.mailboxes.read_text())
self.assertNotIn("support@example.net", self.mailboxes.read_text())
self.assertEqual(apply_mailbox(self.spec), credential_file)
self.assertEqual(credential_file.read_bytes(), original)
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
def test_waits_for_dovecot_to_read_the_updated_authentication_file(self):
home = self.storage / self.spec.domain / self.spec.local_part
self.resolve_home.side_effect = [None, None, str(home)]
with patch("coulobre.mail_node_apply.time.sleep") as pause:
apply_mailbox(self.spec)
pause.assert_called_once()
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
def test_unmanaged_lookup_is_preserved_without_reserving_credentials(self):
self.mailboxes.write_text("existing@example.net\t1\n", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "differ from Coulobre's registry"):
apply_mailbox(self.spec)
self.assertEqual(self.mailboxes.read_text(), "existing@example.net\t1\n")
self.assertFalse(credential_path(self.spec).exists())
def test_missing_prepared_home_is_not_recreated(self):
home = self.storage / self.spec.domain / self.spec.local_part
with self.assertRaises(FileNotFoundError):
ensure_mail_home(home, self.account, create=False)
self.assertFalse(home.exists())
class MailboxCommandTests(SimpleTestCase):
def test_password_tool_errors_omit_sensitive_input_and_output(self):
command = ("doveadm", "pw", "-s", "SHA512-CRYPT")
with (
patch(
"coulobre.mail_node_apply.subprocess.run",
return_value=CompletedProcess(
command, 75, "secret hash", "secret password"
),
),
self.assertRaisesRegex(ValueError, r"^doveadm pw failed \(75\)\.$"),
):
run(*command, standard_input="secret password")
+12 -1
View File
@@ -70,12 +70,23 @@ def main(argv=None):
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)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
mailbox = MailboxSpec.from_manifest(payload)
print(json.dumps({"address": mailbox.address}, indent=2))
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}")
else:
print(json.dumps({"address": mailbox.address}, indent=2))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0
+310
View File
@@ -0,0 +1,310 @@
import fcntl
import grp
import hashlib
import json
import os
import pwd
import re
import secrets
import stat
import subprocess
import time
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
from .mail_node import MailboxSpec
from .node_files import read_root_file, require_root_directory, write_new_file
STATE_DIRECTORY = Path("/var/lib/coulobre/mail-node")
MAIL_ROOT = Path("/srv/coulobre-mail")
MAIL_USER = "coulobre-vmail"
POSTFIX_DOMAINS = Path("/etc/postfix/coulobre-domains")
POSTFIX_MAILBOXES = Path("/etc/postfix/coulobre-mailboxes")
DOVECOT_USERS = Path("/etc/dovecot/coulobre-users")
LMTP_SOCKET = Path("/var/spool/postfix/private/dovecot-lmtp")
MANAGED_HEADER = "# Managed by Coulobre Panel\n"
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
PASSWORD_HASH = re.compile(
r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}"
)
@dataclass(frozen=True)
class Credentials:
mailbox: MailboxSpec
password: str
password_hash: str
@property
def home(self):
return MAIL_ROOT / self.mailbox.domain / self.mailbox.local_part
@property
def path(self):
return credential_path(self.mailbox)
@property
def home_marker(self):
return self.path.with_suffix(".home-ready")
def save(self):
document = {
"mailbox": self.mailbox.manifest(),
"password": self.password,
"password_hash": self.password_hash,
}
write_new_file(self.path, json.dumps(document, indent=2) + "\n", mode=0o600)
def credential_path(mailbox):
key = hashlib.sha256(mailbox.address.encode("ascii")).hexdigest()
return STATE_DIRECTORY / f"{key}.json"
def load_credentials(path):
try:
data = json.loads(read_root_file(path, mode=0o600))
record = Credentials(
MailboxSpec.from_manifest(data["mailbox"]),
data["password"],
data["password_hash"],
)
if (
record.path != path
or not PASSWORD.fullmatch(record.password)
or not PASSWORD_HASH.fullmatch(record.password_hash)
):
raise ValueError
except (KeyError, TypeError, ValueError):
raise ValueError(f"Invalid mailbox credentials record at {path}.") from None
return record
def apply_mailbox(mailbox):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the mail node.")
for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory)
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
ensure_mail_directory(MAIL_ROOT)
directory = os.open(STATE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
return install_mailbox(mailbox, directory)
finally:
os.close(directory)
def install_mailbox(mailbox, state_directory):
account, auth_group = check_services(mailbox)
records = [
load_credentials(path) for path in sorted(STATE_DIRECTORY.glob("*.json"))
]
active = next((record for record in records if record.mailbox == mailbox), None)
prepared = [record for record in records if home_is_prepared(record)]
previous = lookup_tables(prepared, account, auth_group)
ready = {path: check_lookup_table(path, table) for path, table in previous.items()}
home = MAIL_ROOT / mailbox.domain / mailbox.local_part
ensure_mail_directory(home.parent)
if active is None:
if os.path.lexists(home) or dovecot_home(mailbox) is not None:
raise ValueError("The mailbox already exists outside Coulobre's registry.")
password = secrets.token_urlsafe(32)
password_hash = run(
"doveadm",
"pw",
"-s",
"SHA512-CRYPT",
standard_input=f"{password}\n{password}\n",
)
if not PASSWORD_HASH.fullmatch(password_hash):
raise ValueError("Dovecot did not return the expected password hash.")
active = Credentials(mailbox, password, password_hash)
active.save()
os.fsync(state_directory)
if active not in prepared:
ensure_mail_home(home, account, create=True)
write_new_file(active.home_marker, f"{mailbox.address}\n", mode=0o600)
os.fsync(state_directory)
prepared.append(active)
else:
ensure_mail_home(home, account, create=False)
tables = lookup_tables(prepared, account, auth_group)
publish_table(DOVECOT_USERS, tables[DOVECOT_USERS], ready[DOVECOT_USERS])
wait_for_dovecot_home(mailbox, home)
for path in (POSTFIX_MAILBOXES, POSTFIX_DOMAINS):
publish_table(path, tables[path], ready[path])
run("postfix", "reload")
return active.path
def lookup_tables(records, account, auth_group):
return {
DOVECOT_USERS: (
0o640,
auth_group,
{
f"{record.mailbox.address}:{record.password_hash}:"
f"{account.pw_uid}:{account.pw_gid}::{record.home}::"
for record in records
},
),
POSTFIX_MAILBOXES: (
0o644,
None,
{f"{record.mailbox.address}\t1" for record in records},
),
POSTFIX_DOMAINS: (
0o644,
None,
{f"{record.mailbox.domain}\t1" for record in records},
),
}
def check_lookup_table(path, table):
if not os.path.lexists(path):
return ""
mode, group, rows = table
contents = read_root_file(path, mode=mode)
if group is not None and path.lstat().st_gid != group:
raise ValueError(f"Expected ownership by the Dovecot auth group for {path}.")
if contents and (
not contents.startswith(MANAGED_HEADER)
or set(contents.removeprefix(MANAGED_HEADER).splitlines()) - rows
):
raise ValueError(f"Existing entries in {path} differ from Coulobre's registry.")
return contents
def publish_table(path, table, previous):
mode, group, rows = table
contents = MANAGED_HEADER + "".join(f"{row}\n" for row in sorted(rows))
if contents == previous:
return
with TemporaryDirectory(dir=path.parent) as scratch:
staged = Path(scratch) / "lookup"
write_new_file(staged, contents, mode=mode, group=group)
os.replace(staged, path)
def home_is_prepared(record):
if not os.path.lexists(record.home_marker):
return False
if read_root_file(record.home_marker, mode=0o600) != f"{record.mailbox.address}\n":
raise ValueError(
"The mailbox home marker conflicts with its credentials record."
)
return True
def ensure_mail_directory(path):
require_root_directory(path.parent)
try:
path.mkdir(mode=0o755)
except FileExistsError:
require_root_directory(path)
else:
path.chmod(0o755)
if not path.stat().st_mode & stat.S_IXOTH:
raise ValueError(f"Allow the mail service to traverse {path}.")
def ensure_mail_home(home, account, *, create):
if create and not os.path.lexists(home):
home.mkdir(mode=0o700)
info = home.lstat()
if not stat.S_ISDIR(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o700:
raise ValueError(f"Expected a private mailbox directory at {home}.")
if create and info.st_uid == 0 and not any(home.iterdir()):
os.chown(home, account.pw_uid, account.pw_gid, follow_symlinks=False)
elif (info.st_uid, info.st_gid) != (account.pw_uid, account.pw_gid):
raise ValueError(f"Unexpected ownership for the mailbox directory at {home}.")
def check_services(mailbox):
try:
account = pwd.getpwnam(MAIL_USER)
except KeyError:
raise ValueError(
f"Create the {MAIL_USER} system account on the mail node."
) from None
if (
not account.pw_uid
or not account.pw_gid
or account.pw_dir != str(MAIL_ROOT)
or account.pw_shell != "/usr/sbin/nologin"
):
raise ValueError(
f"Unexpected configuration for the {MAIL_USER} system account."
)
settings = {
"virtual_mailbox_domains": f"proxy:texthash:{POSTFIX_DOMAINS}",
"virtual_mailbox_maps": f"proxy:texthash:{POSTFIX_MAILBOXES}",
"virtual_transport": "lmtp:unix:private/dovecot-lmtp",
"smtpd_reject_unlisted_recipient": "yes",
}
for name, expected in settings.items():
if run("postconf", "-hx", name) != expected:
raise ValueError(f"Configure Postfix {name} for Coulobre mailboxes.")
local_domains = run("postconf", "-hx", "mydestination")
if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()):
raise ValueError("The requested mail domain is a local Postfix destination.")
if run("doveconf", "-h", "mail_location") != "maildir:~/Maildir":
raise ValueError("Configure Dovecot mail_location for the managed Maildir.")
first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_valid_uid"))
if account.pw_uid < first_uid or (last_uid and account.pw_uid > last_uid):
raise ValueError(f"Allow the {MAIL_USER} UID in Dovecot's valid UID range.")
if not LMTP_SOCKET.is_socket():
raise ValueError(f"Dovecot is missing its LMTP socket at {LMTP_SOCKET}.")
run("postfix", "status")
try:
auth_group = grp.getgrnam("dovecot").gr_gid
except KeyError:
raise ValueError("The Dovecot auth group is missing.") from None
if not auth_group:
raise ValueError("The Dovecot auth group must be unprivileged.")
return account, auth_group
def dovecot_home(mailbox):
return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67)
def wait_for_dovecot_home(mailbox, home):
# Dovecot checks for passwd-file changes at most once per second.
for _ in range(10):
resolved = dovecot_home(mailbox)
if resolved == str(home):
return
if resolved is not None:
break
time.sleep(0.2)
raise ValueError("Dovecot did not resolve the managed mailbox home.")
def run(*command, standard_input=None, missing_exit=None):
name = " ".join(command[:2])
try:
result = subprocess.run(
command,
input=standard_input,
capture_output=True,
text=True,
timeout=20,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"},
)
except subprocess.TimeoutExpired:
raise ValueError(f"{name} timed out.") from None
if result.returncode:
if result.returncode == missing_exit:
return None
details = ""
if standard_input is None:
details = result.stderr.strip() or result.stdout.strip()
raise ValueError(f"{name} failed ({result.returncode}). {details}".rstrip())
return result.stdout.strip()
+3 -1
View File
@@ -26,10 +26,12 @@ def read_root_file(path, *, mode=None):
return path.read_text(encoding="utf-8")
def write_new_file(path, content, *, mode):
def write_new_file(path, content, *, mode, group=None):
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged:
staged.write(content)
staged.flush()
if group is not None:
os.fchown(staged.fileno(), -1, group)
os.fchmod(staged.fileno(), mode)
os.fsync(staged.fileno())
os.link(staged.name, path)