diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index 9451176..95beed2 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -11,7 +11,7 @@ from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.mail_node import MailboxSpec, main +from coulobre.mail_node import MailboxQuotaUpdate, MailboxSpec, main from coulobre.mail_node_apply import ( apply_mailbox, check_dovecot_maildir, @@ -21,6 +21,7 @@ from coulobre.mail_node_apply import ( mailbox_status, run, ) +from coulobre.mail_node_quota import set_mailbox_quota class MailboxApplyRequestTests(SimpleTestCase): @@ -62,6 +63,20 @@ class MailboxApplyRequestTests(SimpleTestCase): self.assertEqual(reply["state"], "failed") self.apply.assert_not_called() + def test_quota_update_request_is_distinct_from_provisioning(self): + mailbox = MailboxSpec("example.net", "support", 256) + request = MailboxQuotaUpdate(mailbox) + with patch("coulobre.mail_node_quota.set_mailbox_quota") as change: + code, reply = self.request(request.manifest()) + + self.assertEqual(code, 0) + self.assertEqual( + reply, + request.manifest() | {"state": "configured", "problem": None}, + ) + change.assert_called_once_with(mailbox) + self.apply.assert_not_called() + class MailboxApplyTests(SimpleTestCase): def setUp(self): @@ -218,6 +233,46 @@ class MailboxApplyTests(SimpleTestCase): apply_mailbox(MailboxSpec("example.net", "support", quota_mib=128)) self.assertEqual(path.read_bytes(), original) + def test_quota_update_can_resume_after_the_dovecot_table_was_written(self): + path = apply_mailbox(self.spec) + credentials = json.loads(path.read_text()) + sibling = MailboxSpec("example.net", "other") + apply_mailbox(sibling) + sibling_row = next( + row + for row in self.users.read_text().splitlines() + if row.startswith(sibling.address + ":") + ) + self.postfix_lookup.return_value = "1" + limited = MailboxSpec("example.net", "support", quota_mib=128) + with ( + patch("coulobre.mail_node_quota.require_root_directory"), + patch("coulobre.mail_node_apply.check_dovecot_quota"), + patch("coulobre.mail_node_apply.wait_for_dovecot_user") as wait, + ): + wait.side_effect = ValueError( + "Dovecot has not read the new row yet." + ) + with self.assertRaisesMessage(ValueError, "new row yet"): + set_mailbox_quota(limited) + self.assertIn( + "userdb_quota_rule=*:bytes=128M", self.users.read_text() + ) + self.assertEqual(json.loads(path.read_text()), credentials) + + wait.side_effect = None + with self.assertRaisesMessage( + ValueError, "Retry the original update" + ): + set_mailbox_quota(MailboxSpec("example.net", "support", 256)) + set_mailbox_quota(limited) + + self.assertEqual( + json.loads(path.read_text()), + credentials | {"mailbox": limited.manifest()}, + ) + self.assertIn(sibling_row, self.users.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)] diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index 741bc0b..68b9c93 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -92,6 +92,35 @@ class MailboxSpec: 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): + if ( + isinstance(data, dict) + and data.keys() == {"operation", "mailbox"} + and data["operation"] == "set_quota" + ): + return MailboxQuotaUpdate(MailboxSpec.from_manifest(data["mailbox"])) + return MailboxSpec.from_manifest(data) + + +def apply_mailbox_request(request): + if 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) @@ -103,6 +132,10 @@ def main(argv=None): "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.", @@ -124,10 +157,8 @@ def main(argv=None): args = parser.parse_args(argv) if args.command == "apply-request": - from .mail_node_apply import apply_mailbox - return serve_apply_request( - MANIFEST_VERSION, MailboxSpec.from_manifest, apply_mailbox + MANIFEST_VERSION, parse_mailbox_request, apply_mailbox_request ) try: @@ -139,6 +170,19 @@ def main(argv=None): 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 diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index 539201b..336c826 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -50,15 +50,20 @@ class Credentials: def home_marker(self): return self.path.with_suffix(".home-ready") - def save(self): + def save(self, *, replace=False): 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 - ) + text = json.dumps(document, indent=2) + "\n" + if replace: + with TemporaryDirectory(dir=self.path.parent) as scratch: + staged = Path(scratch) / "credentials" + write_new_file(staged, text, mode=0o600) + os.replace(staged, self.path) + else: + write_new_file(self.path, text, mode=0o600) def credential_path(mailbox): @@ -103,7 +108,7 @@ def apply_mailbox(mailbox): @contextmanager -def locked_state(*, create): +def locked_state(*, create, exclusive=False): try: require_root_directory( STATE_DIRECTORY, create_mode=0o700 if create else None @@ -117,7 +122,9 @@ def locked_state(*, create): yield None return try: - fcntl.flock(directory, fcntl.LOCK_EX if create else fcntl.LOCK_SH) + fcntl.flock( + directory, fcntl.LOCK_EX if create or exclusive else fcntl.LOCK_SH + ) yield directory finally: os.close(directory) @@ -305,20 +312,26 @@ def lookup_tables(records, account, auth_group, *, modern): def dovecot_lookup_rows(records, account, *, modern): - rows = set() - for record in records: - row = ( - f"{record.mailbox.address}:{record.password_hash}:" - f"{account.pw_uid}:{account.pw_gid}::{record.home}::" - ) - if record.mailbox.quota_mib is not None: - key, value = quota_userdb_setting(record.mailbox, modern) - row += f"userdb_{key}={value}" - rows.add(row) - return rows + return { + dovecot_lookup_row(record, account, modern=modern) + for record in records + } + + +def dovecot_lookup_row(record, account, *, modern): + row = ( + f"{record.mailbox.address}:{record.password_hash}:" + f"{account.pw_uid}:{account.pw_gid}::{record.home}::" + ) + if record.mailbox.quota_mib is not None: + key, value = quota_userdb_setting(record.mailbox, modern) + row += f"userdb_{key}={value}" + return row def quota_userdb_setting(mailbox, modern): + if mailbox.quota_mib is None: + return ("quota_storage_size" if modern else "quota_rule"), "" size = f"{mailbox.quota_mib}M" if modern: return "quota_storage_size", size @@ -532,19 +545,21 @@ def postfix_lookup(key, path): ) -def dovecot_quota_matches(mailbox, modern): - if mailbox.quota_mib is None: +def dovecot_quota_matches(mailbox, modern, *, verify_unlimited=False): + if mailbox.quota_mib is None and not verify_unlimited: return True key, value = quota_userdb_setting(mailbox, modern) return run("doveadm", "user", "-f", key, mailbox.address) == value -def wait_for_dovecot_user(mailbox, home, modern): +def wait_for_dovecot_user(mailbox, home, modern, *, verify_unlimited=False): # Dovecot checks for passwd-file changes at most once per second. for _ in range(10): resolved = dovecot_home(mailbox) if resolved == str(home): - if dovecot_quota_matches(mailbox, modern): + if dovecot_quota_matches( + mailbox, modern, verify_unlimited=verify_unlimited + ): return elif resolved is not None: break diff --git a/src/coulobre/mail_node_quota.py b/src/coulobre/mail_node_quota.py new file mode 100644 index 0000000..aa37c17 --- /dev/null +++ b/src/coulobre/mail_node_quota.py @@ -0,0 +1,78 @@ +import os +from dataclasses import replace + +from . import mail_node_apply as mail +from .node_files import require_root_directory + + +def set_mailbox_quota(mailbox): + if os.geteuid() != 0: + raise ValueError("Run set-quota as root on the mail node.") + with mail.locked_state(create=False, exclusive=True) as state_directory: + path = mail.credential_path(mailbox) + if state_directory is None or not os.path.lexists(path): + raise ValueError( + "Apply the mailbox manifest before changing its quota." + ) + original = mail.load_credentials(path) + updated = replace(original, mailbox=mailbox) + publish_mailbox_quota(original, updated) + if original != updated: + updated.save(replace=True) + os.fsync(state_directory) + + +def publish_mailbox_quota(original, updated): + mailbox = updated.mailbox + for directory in ( + mail.DOVECOT_USERS.parent, + mail.POSTFIX_MAILBOXES.parent, + ): + require_root_directory(directory) + account, auth_group, modern = mail.check_services(mailbox) + if not mail.home_is_prepared(original): + raise ValueError( + "Complete mailbox provisioning before changing its quota." + ) + mail.ensure_mail_directory(mail.MAIL_ROOT, create=False) + mail.ensure_mail_directory(original.home.parent, create=False) + mail.ensure_mail_home(original.home, account, create=False) + if ( + mail.postfix_lookup(mailbox.domain, mail.POSTFIX_DOMAINS) != "1" + or mail.postfix_lookup(mailbox.address, mail.POSTFIX_MAILBOXES) != "1" + ): + raise ValueError( + "Postfix did not resolve the managed domain and recipient." + ) + if mailbox.quota_mib is not None: + mail.check_dovecot_quota(modern) + + contents = mail.read_lookup_table(mail.DOVECOT_USERS, 0o640, auth_group) + if not contents.startswith(mail.MANAGED_HEADER): + raise ValueError("Expected a managed Dovecot lookup table.") + rows = contents.removeprefix(mail.MANAGED_HEADER).splitlines() + old_row = mail.dovecot_lookup_row(original, account, modern=modern) + new_row = mail.dovecot_lookup_row(updated, account, modern=modern) + matched = [ + index + for index, row in enumerate(rows) + if row.startswith(mailbox.address + ":") + ] + if len(matched) != 1 or rows[matched[0]] not in (old_row, new_row): + raise ValueError( + "The Dovecot entry conflicts with this quota update. " + "Retry the original update if it was interrupted." + ) + rows[matched[0]] = new_row + mail.publish_table(mail.DOVECOT_USERS, (0o640, auth_group, rows), contents) + # Persist the live table before updating the registry. + directory = os.open( + mail.DOVECOT_USERS.parent, os.O_RDONLY | os.O_DIRECTORY + ) + try: + os.fsync(directory) + finally: + os.close(directory) + mail.wait_for_dovecot_user( + mailbox, original.home, modern, verify_unlimited=True + )