589 lines
22 KiB
Python
589 lines
22 KiB
Python
import json
|
|
import os
|
|
import stat
|
|
from contextlib import redirect_stdout
|
|
from io import BytesIO, StringIO
|
|
from pathlib import Path
|
|
from subprocess import CompletedProcess
|
|
from tempfile import TemporaryDirectory
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
from uuid import uuid4
|
|
|
|
from django.test import SimpleTestCase
|
|
|
|
from coulobre.mail_node import (
|
|
MailboxQuotaUpdate,
|
|
MailboxRemovalRequest,
|
|
MailboxSpec,
|
|
main,
|
|
)
|
|
from coulobre.mail_node_apply import (
|
|
apply_mailbox,
|
|
check_dovecot_maildir,
|
|
check_dovecot_quota,
|
|
credential_path,
|
|
ensure_mail_home,
|
|
load_credentials,
|
|
mailbox_status,
|
|
run,
|
|
)
|
|
from coulobre.mail_node_quota import set_mailbox_access, set_mailbox_quota
|
|
from coulobre.mail_node_rotation import rotate_mailbox_credentials
|
|
from coulobre.service_credentials import ServiceCredentialRequest
|
|
|
|
|
|
class MailboxApplyRequestTests(SimpleTestCase):
|
|
def setUp(self):
|
|
self.mailbox = MailboxSpec("example.net", "support")
|
|
self.apply = self.enterContext(
|
|
patch(
|
|
"coulobre.mail_node_apply.apply_mailbox",
|
|
return_value=Path("/private/credentials.json"),
|
|
)
|
|
)
|
|
|
|
def request(self, manifest):
|
|
output = StringIO()
|
|
with (
|
|
patch(
|
|
"sys.stdin",
|
|
SimpleNamespace(buffer=BytesIO(json.dumps(manifest).encode())),
|
|
),
|
|
redirect_stdout(output),
|
|
):
|
|
code = main(["apply-request"])
|
|
return code, json.loads(output.getvalue())
|
|
|
|
def test_request_reports_the_mailbox_identity_only(self):
|
|
manifest = self.mailbox.manifest()
|
|
code, reply = self.request(manifest)
|
|
self.apply.assert_called_once_with(self.mailbox)
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(
|
|
reply, manifest | {"state": "configured", "problem": None}
|
|
)
|
|
|
|
def test_request_rejects_extra_credentials_before_acting(self):
|
|
code, reply = self.request(
|
|
self.mailbox.manifest() | {"password": "untrusted"}
|
|
)
|
|
self.assertEqual(code, 1)
|
|
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()
|
|
|
|
def test_removal_request_can_archive_an_active_mailbox(self):
|
|
removal = MailboxRemovalRequest(self.mailbox, str(uuid4()))
|
|
with patch("coulobre.mail_node_retirement.retire_mailbox") as retire:
|
|
code, reply = self.request(removal.manifest())
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(reply["operation_id"], removal.operation_id)
|
|
retire.assert_called_once_with(removal, allow_active=True)
|
|
self.apply.assert_not_called()
|
|
|
|
|
|
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.services = self.enterContext(
|
|
patch(
|
|
"coulobre.mail_node_apply.check_services",
|
|
return_value=(self.account, os.getegid(), False),
|
|
)
|
|
)
|
|
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.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):
|
|
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_reapplying_after_dovecot_upgrade_rewrites_managed_quota_settings(
|
|
self,
|
|
):
|
|
mailbox = MailboxSpec("example.net", "support", quota_mib=128)
|
|
with (
|
|
patch("coulobre.mail_node_apply.check_dovecot_quota"),
|
|
patch(
|
|
"coulobre.mail_node_apply.dovecot_quota_matches",
|
|
return_value=True,
|
|
),
|
|
):
|
|
path = apply_mailbox(mailbox)
|
|
original = path.read_bytes()
|
|
self.assertIn(
|
|
"userdb_quota_rule=*:bytes=128M", self.users.read_text()
|
|
)
|
|
self.services.return_value = (self.account, os.getegid(), True)
|
|
self.assertEqual(apply_mailbox(mailbox), path)
|
|
|
|
self.assertEqual(path.read_bytes(), original)
|
|
self.assertIn("userdb_quota_storage_size=128M", self.users.read_text())
|
|
self.assertNotIn("userdb_quota_rule", self.users.read_text())
|
|
|
|
def test_dovecot_quota_configuration_is_required_before_provisioning(self):
|
|
mailbox = MailboxSpec("example.net", "support", quota_mib=128)
|
|
with (
|
|
patch(
|
|
"coulobre.mail_node_apply.check_dovecot_quota",
|
|
side_effect=ValueError("Enable quota"),
|
|
),
|
|
self.assertRaisesMessage(ValueError, "Enable quota"),
|
|
):
|
|
apply_mailbox(mailbox)
|
|
|
|
self.assertFalse(credential_path(mailbox).exists())
|
|
self.assertFalse(self.mailboxes.exists())
|
|
|
|
def test_reapplying_with_a_different_quota_keeps_the_registered_mailbox(
|
|
self,
|
|
):
|
|
path = apply_mailbox(self.spec)
|
|
original = path.read_bytes()
|
|
with self.assertRaisesMessage(ValueError, "registered storage limit"):
|
|
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_resume_can_recover_an_interrupted_suspension(self):
|
|
path = apply_mailbox(self.spec)
|
|
apply_mailbox(MailboxSpec("other.example", "support"))
|
|
credentials = path.read_bytes()
|
|
table = self.users.read_bytes()
|
|
recipients = self.mailboxes.read_bytes()
|
|
self.postfix_lookup.return_value = "1"
|
|
with (
|
|
patch("coulobre.mail_node_quota.require_root_directory"),
|
|
patch("coulobre.mail_node_apply.wait_for_dovecot_user"),
|
|
patch("coulobre.mail_node_quota.verify_mailbox_access") as verify,
|
|
):
|
|
verify.side_effect = ValueError(
|
|
"Dovecot did not confirm the change."
|
|
)
|
|
with self.assertRaisesMessage(ValueError, "did not confirm"):
|
|
set_mailbox_access(self.spec, True)
|
|
self.assertIn(
|
|
f"{self.spec.address}:{{CRYPT}}*:", self.users.read_text()
|
|
)
|
|
self.assertEqual(path.read_bytes(), credentials)
|
|
self.assertEqual(self.mailboxes.read_bytes(), recipients)
|
|
|
|
verify.side_effect = None
|
|
set_mailbox_access(self.spec, False)
|
|
self.assertEqual(self.users.read_bytes(), table)
|
|
self.assertEqual(path.read_bytes(), credentials)
|
|
|
|
def test_interrupted_rotation_does_not_block_another_mailbox(self):
|
|
path = apply_mailbox(self.spec)
|
|
original = load_credentials(path)
|
|
replacement_hash = "{SHA512-CRYPT}$6$mockSalt$" + ("B" * 86)
|
|
rotation = ServiceCredentialRequest(self.spec, "rotate", str(uuid4()))
|
|
self.postfix_lookup.return_value = "1"
|
|
with (
|
|
patch("coulobre.mail_node_quota.require_root_directory"),
|
|
patch("coulobre.mail_node_apply.wait_for_dovecot_user"),
|
|
patch(
|
|
"coulobre.mail_node_rotation.verify_mailbox_rotation"
|
|
) as verify,
|
|
patch(
|
|
"coulobre.credential_rotation.read_root_file",
|
|
side_effect=lambda path, **kwargs: path.read_text(),
|
|
),
|
|
):
|
|
verify.side_effect = OSError("Verification interrupted.")
|
|
with (
|
|
patch(
|
|
"coulobre.mail_node_apply.hash_mailbox_password",
|
|
return_value=replacement_hash,
|
|
),
|
|
self.assertRaisesMessage(OSError, "Verification interrupted"),
|
|
):
|
|
rotate_mailbox_credentials(rotation)
|
|
self.assertEqual(load_credentials(path), original)
|
|
self.assertIn(replacement_hash, self.users.read_text())
|
|
|
|
sibling = MailboxSpec("other.example", "support")
|
|
apply_mailbox(sibling)
|
|
self.assertIn(replacement_hash, self.users.read_text())
|
|
self.assertIn(sibling.address, self.mailboxes.read_text())
|
|
|
|
verify.side_effect = None
|
|
result = rotate_mailbox_credentials(rotation)
|
|
self.assertNotEqual(result["password"], original.password)
|
|
self.assertEqual(
|
|
load_credentials(path).rotation_id, rotation.rotation_id
|
|
)
|
|
self.assertEqual(rotate_mailbox_credentials(rotation), result)
|
|
|
|
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())
|
|
|
|
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_dovecot_24_checks_the_maildir_driver_and_path(self):
|
|
with patch(
|
|
"coulobre.mail_node_apply.run",
|
|
side_effect=["2.4.2 (build)", "maildir", "~/Maildir"],
|
|
):
|
|
check_dovecot_maildir()
|
|
|
|
def test_dovecot_24_rejects_an_unmanaged_driver_or_path(self):
|
|
for settings in (["mdbox"], ["maildir", "~/other"]):
|
|
with (
|
|
self.subTest(settings=settings),
|
|
patch(
|
|
"coulobre.mail_node_apply.run",
|
|
side_effect=["2.4.2", *settings],
|
|
),
|
|
self.assertRaisesMessage(
|
|
ValueError, "mail_driver and mail_path"
|
|
),
|
|
):
|
|
check_dovecot_maildir()
|
|
|
|
def test_dovecot_24_accepts_a_globally_enabled_quota_plugin(self):
|
|
with patch(
|
|
"coulobre.mail_node_apply.run",
|
|
side_effect=[
|
|
'quota "User quota" {\n}',
|
|
"quota = yes",
|
|
"imap_quota = yes",
|
|
"yes",
|
|
"quota = yes",
|
|
"yes",
|
|
],
|
|
):
|
|
check_dovecot_quota(modern=True)
|
|
|
|
def test_dovecot_24_rejects_explicitly_disabled_quota(self):
|
|
with (
|
|
patch(
|
|
"coulobre.mail_node_apply.run",
|
|
side_effect=[
|
|
'quota "User quota" {\n}',
|
|
"quota = yes",
|
|
"quota = no",
|
|
],
|
|
),
|
|
self.assertRaisesMessage(ValueError, "quota enforcement"),
|
|
):
|
|
check_dovecot_quota(modern=True)
|
|
|
|
def test_dovecot_23_checks_the_legacy_maildir_setting(self):
|
|
with patch(
|
|
"coulobre.mail_node_apply.run",
|
|
side_effect=["2.3.21 (build)", "maildir:~/Maildir"],
|
|
) as command:
|
|
check_dovecot_maildir()
|
|
|
|
command.assert_called_with("doveconf", "-h", "mail_location")
|
|
|
|
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")
|
|
|
|
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="")
|