From 32f56deae4badee8e16c451862b3400706851161 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:43:17 +0100 Subject: [PATCH] Add status checks for managed mailboxes --- docs/development.md | 23 +++ src/coulobre/hosting/test_mail_node_apply.py | 102 ++++++++++++- src/coulobre/mail_node.py | 8 ++ src/coulobre/mail_node_apply.py | 144 ++++++++++++++++--- 4 files changed, 256 insertions(+), 21 deletions(-) diff --git a/docs/development.md b/docs/development.md index b04a3d0..2419857 100644 --- a/docs/development.md +++ b/docs/development.md @@ -272,6 +272,29 @@ address using a password hash. Postfix accepts listed recipients and hands delivery to Dovecot over the local LMTP socket. Reapply the same manifest to resume installation with the same credentials. +### Check a mailbox installation + +Run the status command on the mail node with the same manifest. + +```sh +sudo /opt/coulobre/bin/coulobre-mail-node status coulobre-mailbox-1.json +``` + +The check reads the local registry, mailbox home and lookup files. It +queries the running Postfix service for the domain and recipient and +tests the saved login against Dovecot's local authentication service. +The JSON report includes the address, state and a diagnostic when the +installation needs attention. + +| State | Exit code | Meaning | +| --- | --- | --- | +| `configured` | 0 | The local mailbox and service checks passed. | +| `not_installed` | 2 | The mailbox is absent from the local registry and mail services. | +| `needs_attention` | 2 | An installation, configuration or service check failed. | + +Exit code `1` indicates an invalid manifest or an invocation error such as +running the check without root privileges. + ## Request an Apache configuration preview Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index 88f4b3d..fcc9ea5 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -1,6 +1,8 @@ import json import os import stat +from contextlib import redirect_stdout +from io import StringIO from pathlib import Path from subprocess import CompletedProcess from tempfile import TemporaryDirectory @@ -9,11 +11,12 @@ from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.mail_node import MailboxSpec +from coulobre.mail_node import MailboxSpec, main from coulobre.mail_node_apply import ( apply_mailbox, credential_path, ensure_mail_home, + mailbox_status, run, ) @@ -63,6 +66,9 @@ class MailboxApplyTests(SimpleTestCase): ) self.commands = self.enterContext(patch("coulobre.mail_node_apply.run")) self.commands.return_value = "{SHA512-CRYPT}$6$mockSalt$" + ("A" * 86) + self.postfix_lookup = self.enterContext( + patch("coulobre.mail_node_apply.postfix_lookup", return_value=None) + ) self.spec = MailboxSpec("example.net", "support") def prepare_directory(self, path, *, create_mode=None): @@ -133,6 +139,87 @@ class MailboxApplyTests(SimpleTestCase): self.assertFalse(home.exists()) + def test_status_reports_absence_without_creating_files(self): + result = mailbox_status(self.spec) + + self.assertEqual( + result, + {"address": self.spec.address, "state": "not_installed", "problem": None}, + ) + self.assertFalse(self.state.exists()) + self.assertFalse(self.storage.exists()) + self.assertFalse(self.users.exists()) + self.commands.assert_not_called() + + def test_status_detects_a_live_recipient_without_a_credentials_record(self): + self.postfix_lookup.return_value = "1" + + result = mailbox_status(self.spec) + + self.assertEqual(result["state"], "needs_attention") + self.assertIn("outside Coulobre's registry", result["problem"]) + + def test_status_detects_a_pending_home_preparation(self): + self.prepare_home.side_effect = ValueError("Interrupted before home creation.") + with self.assertRaisesRegex(ValueError, "Interrupted"): + apply_mailbox(self.spec) + + result = mailbox_status(self.spec) + + self.assertEqual(result["state"], "needs_attention") + self.assertIn("installation is incomplete", result["problem"]) + + def test_status_runs_local_authentication_with_saved_password_on_stdin(self): + path = apply_mailbox(self.spec) + saved = json.loads(path.read_text()) + self.postfix_lookup.return_value = "1" + self.commands.reset_mock() + + result = mailbox_status(self.spec) + + self.assertEqual(result["state"], "configured") + self.commands.assert_called_once_with( + "doveadm", + "auth", + "login", + "-x", + "service=imap", + self.spec.address, + standard_input=saved["password"] + "\n", + ) + + def test_status_detects_a_recipient_missing_from_the_active_postfix_map(self): + apply_mailbox(self.spec) + self.postfix_lookup.side_effect = ["1", None] + self.commands.reset_mock() + + result = mailbox_status(self.spec) + + self.assertEqual(result["state"], "needs_attention") + self.assertIn("Postfix did not resolve", result["problem"]) + self.commands.assert_not_called() + + def test_status_command_reports_auth_failure_without_exposing_credentials(self): + path = apply_mailbox(self.spec) + saved = json.loads(path.read_text()) + self.postfix_lookup.return_value = "1" + self.commands.side_effect = ValueError( + saved["password"] + saved["password_hash"] + ) + manifest = self.state.parent / "mailbox.json" + manifest.write_text(json.dumps(self.spec.manifest()), encoding="utf-8") + output = self.enterContext(redirect_stdout(StringIO())) + + self.assertEqual(main(["status", str(manifest)]), 2) + + report = json.loads(output.getvalue()) + self.assertEqual(report["state"], "needs_attention") + self.assertEqual( + report["problem"], "Dovecot could not authenticate the saved mailbox login." + ) + self.assertNotIn(saved["password"], output.getvalue()) + self.assertNotIn(saved["password_hash"], output.getvalue()) + class MailboxCommandTests(SimpleTestCase): def test_password_tool_errors_omit_sensitive_input_and_output(self): @@ -147,3 +234,16 @@ class MailboxCommandTests(SimpleTestCase): self.assertRaisesRegex(ValueError, r"^doveadm pw failed \(75\)\.$"), ): run(*command, standard_input="secret password") + + def test_postfix_query_error_is_distinct_from_a_missing_key(self): + command = ("postmap", "-q", "support@example.net", "proxy:texthash:/mailboxes") + with patch( + "coulobre.mail_node_apply.subprocess.run", + side_effect=[ + CompletedProcess(command, 1, "", ""), + CompletedProcess(command, 1, "", "postmap: fatal: unavailable"), + ], + ): + self.assertIsNone(run(*command, missing_exit=1, missing_output="")) + with self.assertRaisesRegex(ValueError, "postmap: fatal: unavailable"): + run(*command, missing_exit=1, missing_output="") diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index dd04b55..9440986 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -74,6 +74,8 @@ def main(argv=None): "apply", help="Install a virtual mailbox on the mail node." ) apply.add_argument("manifest", type=Path) + status = commands.add_parser("status", help="Check an installed virtual mailbox.") + status.add_argument("manifest", type=Path) args = parser.parse_args(argv) try: @@ -85,6 +87,12 @@ def main(argv=None): credentials = apply_mailbox(mailbox) print(f"Applied virtual mailbox {mailbox.address}.") print(f"Credentials file {credentials}") + 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 else: print(json.dumps({"address": mailbox.address}, indent=2)) except (OSError, ValueError) as error: diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index cab6de2..cf8b0cf 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -9,6 +9,7 @@ import secrets import stat import subprocess import time +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from tempfile import TemporaryDirectory @@ -38,7 +39,7 @@ class Credentials: @property def home(self): - return MAIL_ROOT / self.mailbox.domain / self.mailbox.local_part + return mailbox_home(self.mailbox) @property def path(self): @@ -62,6 +63,10 @@ def credential_path(mailbox): return STATE_DIRECTORY / f"{key}.json" +def mailbox_home(mailbox): + return MAIL_ROOT / mailbox.domain / mailbox.local_part + + def load_credentials(path): try: data = json.loads(read_root_file(path, mode=0o600)) @@ -87,16 +92,98 @@ def apply_mailbox(mailbox): 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) + with locked_state(create=True) as directory: return install_mailbox(mailbox, directory) + + +@contextmanager +def locked_state(*, create): + try: + require_root_directory(STATE_DIRECTORY, create_mode=0o700 if create else None) + directory = os.open( + STATE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + ) + except FileNotFoundError: + if create: + raise + yield None + return + try: + fcntl.flock(directory, fcntl.LOCK_EX if create else fcntl.LOCK_SH) + yield directory finally: os.close(directory) +def mailbox_status(mailbox): + if os.geteuid() != 0: + raise ValueError("Run status as root on the mail node.") + + try: + with locked_state(create=False): + state = check_mailbox(mailbox) + problem = None + except (OSError, ValueError) as error: + state = "needs_attention" + problem = str(error) + return {"address": mailbox.address, "state": state, "problem": problem} + + +def check_mailbox(mailbox): + for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent): + require_root_directory(directory) + account, auth_group = check_services(mailbox) + path = credential_path(mailbox) + home = mailbox_home(mailbox) + if not os.path.lexists(path): + if ( + os.path.lexists(path.with_suffix(".home-ready")) + or os.path.lexists(home) + or dovecot_home(mailbox) is not None + or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) is not None + ): + raise ValueError("The mailbox has resources outside Coulobre's registry.") + return "not_installed" + + record = load_credentials(path) + if not home_is_prepared(record): + raise ValueError("The mailbox installation is incomplete.") + for directory in (MAIL_ROOT, home.parent): + ensure_mail_directory(directory, create=False) + ensure_mail_home(home, account, create=False) + for table, (mode, group, rows) in lookup_tables( + (record,), account, auth_group + ).items(): + contents = read_lookup_table(table, mode, group) + if not contents.startswith(MANAGED_HEADER) or not rows.issubset( + contents.removeprefix(MANAGED_HEADER).splitlines() + ): + raise ValueError(f"The managed mailbox entry is missing from {table}.") + if ( + postfix_lookup(mailbox.domain, POSTFIX_DOMAINS) != "1" + or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) != "1" + ): + raise ValueError("Postfix did not resolve the managed domain and recipient.") + if dovecot_home(mailbox) != str(home): + raise ValueError("Dovecot did not resolve the managed mailbox home.") + try: + run( + "doveadm", + "auth", + "login", + "-x", + "service=imap", + mailbox.address, + standard_input=f"{record.password}\n", + ) + except (OSError, ValueError): + raise ValueError( + "Dovecot could not authenticate the saved mailbox login." + ) from None + return "configured" + + def install_mailbox(mailbox, state_directory): account, auth_group = check_services(mailbox) records = [ @@ -106,7 +193,7 @@ def install_mailbox(mailbox, state_directory): 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 + home = mailbox_home(mailbox) ensure_mail_directory(home.parent) if active is None: if os.path.lexists(home) or dovecot_home(mailbox) is not None: @@ -165,13 +252,18 @@ def lookup_tables(records, account, auth_group): } -def check_lookup_table(path, table): +def read_lookup_table(path, mode, group): 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}.") + return contents + + +def check_lookup_table(path, table): + mode, group, rows = table + contents = read_lookup_table(path, mode, group) if contents and ( not contents.startswith(MANAGED_HEADER) or set(contents.removeprefix(MANAGED_HEADER).splitlines()) - rows @@ -201,14 +293,16 @@ def home_is_prepared(record): return True -def ensure_mail_directory(path): +def ensure_mail_directory(path, *, create=True): require_root_directory(path.parent) - try: - path.mkdir(mode=0o755) - except FileExistsError: - require_root_directory(path) - else: - path.chmod(0o755) + if create: + try: + path.mkdir(mode=0o755) + except FileExistsError: + pass + else: + path.chmod(0o755) + require_root_directory(path) if not path.stat().st_mode & stat.S_IXOTH: raise ValueError(f"Allow the mail service to traverse {path}.") @@ -275,6 +369,17 @@ def dovecot_home(mailbox): return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67) +def postfix_lookup(key, path): + return run( + "postmap", + "-q", + key, + f"proxy:texthash:{path}", + missing_exit=1, + missing_output="", + ) + + def wait_for_dovecot_home(mailbox, home): # Dovecot checks for passwd-file changes at most once per second. for _ in range(10): @@ -287,7 +392,7 @@ def wait_for_dovecot_home(mailbox, home): raise ValueError("Dovecot did not resolve the managed mailbox home.") -def run(*command, standard_input=None, missing_exit=None): +def run(*command, standard_input=None, missing_exit=None, missing_output=None): name = " ".join(command[:2]) try: result = subprocess.run( @@ -301,10 +406,9 @@ def run(*command, standard_input=None, missing_exit=None): except subprocess.TimeoutExpired: raise ValueError(f"{name} timed out.") from None if result.returncode: - if result.returncode == missing_exit: + message = result.stderr.strip() or result.stdout.strip() + if result.returncode == missing_exit and missing_output in (None, message): return None - details = "" - if standard_input is None: - details = result.stderr.strip() or result.stdout.strip() + details = message if standard_input is None else "" raise ValueError(f"{name} failed ({result.returncode}). {details}".rstrip()) return result.stdout.strip()