From 4bd7a905806b7bdc2ea6bf28c727b943ddccd78a Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:24:40 +0100 Subject: [PATCH 1/3] Add mailbox requests and deployment manifests for hosting accounts --- docs/development.md | 19 ++ pyproject.toml | 1 + .../hosting/migrations/0008_hostingmailbox.py | 75 ++++++++ src/coulobre/hosting/models.py | 34 ++++ .../templates/hosting/account_detail.html | 34 ++++ .../templates/hosting/mailbox_form.html | 21 +++ src/coulobre/hosting/test_mailboxes.py | 175 ++++++++++++++++++ src/coulobre/hosting/urls.py | 10 + src/coulobre/hosting/views.py | 69 +++++++ src/coulobre/mail_node.py | 81 ++++++++ 10 files changed, 519 insertions(+) create mode 100644 src/coulobre/hosting/migrations/0008_hostingmailbox.py create mode 100644 src/coulobre/hosting/templates/hosting/mailbox_form.html create mode 100644 src/coulobre/hosting/test_mailboxes.py create mode 100644 src/coulobre/mail_node.py diff --git a/docs/development.md b/docs/development.md index 4b75329..651c9cb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -176,6 +176,25 @@ it again. Coulobre checks the SOA serial, reloads the individual zone, and waits for BIND9 to report the requested serial. Reapply the same manifest to resume after an interrupted reload. See the [BIND9 command reference](https://bind9.readthedocs.io/en/v9.18.39/manpages.html#rndc) and [RFC 1982](https://www.rfc-editor.org/rfc/rfc1982.html). +## Request a virtual mailbox + +Open a hosting account and select **Request mailbox**. Enter the part before +the `@`, such as `support`. The panel uses the account's primary domain, +lowercases the local part, and converts the domain to its ASCII DNS form. +Existing mailbox requests keep their addresses when the primary domain changes. + +The **Mailbox requests** table shows the email addresses. Operators can +download a versioned manifest that contains the domain and local part. +Resellers can see mailbox requests on their assigned accounts. + +Run the installed node command to validate the manifest and display its +address. The manifest describes a virtual user for the Postfix and Dovecot +mail stack. See the [Dovecot guide to Postfix and LMTP](https://doc.dovecot.org/2.3/configuration_manual/howto/postfix_dovecot_lmtp/). + +```sh +coulobre-mail-node inspect coulobre-mailbox-1.json +``` + ## Request an Apache configuration preview Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development diff --git a/pyproject.toml b/pyproject.toml index 0aedbb6..db256e9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,6 +18,7 @@ dependencies = [ [project.scripts] coulobre-database-node = "coulobre.database_node:main" coulobre-dns-node = "coulobre.dns_node:main" +coulobre-mail-node = "coulobre.mail_node:main" coulobre-web-node = "coulobre.web_node:main" [project.optional-dependencies] diff --git a/src/coulobre/hosting/migrations/0008_hostingmailbox.py b/src/coulobre/hosting/migrations/0008_hostingmailbox.py new file mode 100644 index 0000000..9946987 --- /dev/null +++ b/src/coulobre/hosting/migrations/0008_hostingmailbox.py @@ -0,0 +1,75 @@ +# Generated by Django 5.2.19 on 2026-11-19 22:22 + +import django.db.models.deletion +from django.db import migrations, models + +import coulobre.hosting.fields + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0007_hostingdnszone"), + ] + + operations = [ + migrations.CreateModel( + name="HostingMailDomain", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "domain", + coulobre.hosting.fields.DomainNameField( + max_length=253, unique=True + ), + ), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="mail_domains", + to="hosting.hostingaccount", + ), + ), + ], + ), + migrations.CreateModel( + name="HostingMailbox", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("local_part", models.CharField(max_length=64)), + ( + "mail_domain", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="mailboxes", + to="hosting.hostingmaildomain", + ), + ), + ], + options={ + "ordering": ("mail_domain__domain", "local_part"), + "constraints": [ + models.UniqueConstraint( + fields=("mail_domain", "local_part"), + name="hosting_mailbox_domain_local_part_unique", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index dcacf8d..cb9fd5a 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -5,6 +5,7 @@ from django.urls import reverse from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone +from coulobre.mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec from .fields import DomainNameField @@ -118,6 +119,39 @@ class HostingDnsZone(models.Model): return str(self.domain) +class HostingMailDomain(models.Model): + account = models.ForeignKey( + HostingAccount, on_delete=models.PROTECT, related_name="mail_domains" + ) + domain = DomainNameField(max_length=253, unique=True) + + def __str__(self): + return str(self.domain) + + +class HostingMailbox(models.Model): + mail_domain = models.ForeignKey( + HostingMailDomain, on_delete=models.PROTECT, related_name="mailboxes" + ) + local_part = models.CharField(max_length=LOCAL_PART_MAX_LENGTH) + + class Meta: + ordering = ("mail_domain__domain", "local_part") + constraints = [ + models.UniqueConstraint( + fields=("mail_domain", "local_part"), + name="hosting_mailbox_domain_local_part_unique", + ) + ] + + @property + def spec(self): + return MailboxSpec(self.mail_domain.domain, self.local_part) + + def __str__(self): + return self.spec.address + + class WebProvisioningPlan(models.Model): account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE) primary_domain = DomainNameField(max_length=253) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 2e24624..3ee9cf2 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -106,4 +106,38 @@ {% endif %} {% endif %} + {% if is_reseller or perms.hosting.view_hostingmailbox %} +
+
+

Mailbox requests

+ {% if not is_reseller and perms.hosting.add_hostingmailbox %} + Request mailbox + {% endif %} +
+ {% if mailboxes %} +
+ + + + + {% if not is_reseller %}{% endif %} + + + + {% for mailbox in mailboxes %} + + + {% if not is_reseller %} + + {% endif %} + + {% endfor %} + +
Email addressDeployment
{{ mailbox }}Download manifest
+
+ {% else %} +

No mailboxes requested yet.

+ {% endif %} +
+ {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_form.html b/src/coulobre/hosting/templates/hosting/mailbox_form.html new file mode 100644 index 0000000..6fba097 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mailbox_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}Request mailbox · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Request mailbox

+

{{ account.primary_domain }}

+
+
+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/test_mailboxes.py b/src/coulobre/hosting/test_mailboxes.py new file mode 100644 index 0000000..7ac8fa1 --- /dev/null +++ b/src/coulobre/hosting/test_mailboxes.py @@ -0,0 +1,175 @@ +import json +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +from tempfile import TemporaryDirectory + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase +from django.urls import reverse + +from coulobre.mail_node import MailboxSpec, main + +from .models import HostingAccount, HostingMailbox, HostingMailDomain, Reseller + + +class MailboxRequestTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.reseller_user = users.create_user("reseller") + reseller = Reseller.objects.create(user=cls.reseller_user) + cls.account = HostingAccount.objects.create( + name="Account A", primary_domain="Bücher.Example", reseller=reseller + ) + cls.other = HostingAccount.objects.create( + name="Account B", primary_domain="other.example" + ) + + def setUp(self): + self.client.force_login(self.operator) + self.request_url = reverse("panel:mailbox_create", args=[self.account.pk]) + + def request_mailbox(self, local_part="Support.Team"): + self.assertRedirects( + self.client.post(self.request_url, {"local_part": local_part}), + self.account.get_absolute_url(), + ) + return HostingMailbox.objects.get() + + def test_operator_can_request_a_mailbox_and_download_its_manifest(self): + self.assertContains(self.client.get(self.request_url), "Request mailbox") + mailbox = self.request_mailbox() + self.assertEqual(mailbox.mail_domain.account, self.account) + address = "support.team@xn--bcher-kva.example" + self.assertContains(self.client.get(self.account.get_absolute_url()), address) + + manifest = self.client.get(reverse("panel:mailbox_manifest", args=[mailbox.pk])) + self.assertEqual(manifest["Cache-Control"], "private, no-store") + self.assertIn("attachment", manifest["Content-Disposition"]) + self.assertEqual( + manifest.json(), + { + "version": 1, + "kind": "virtual_mailbox", + "domain": "xn--bcher-kva.example", + "local_part": "support.team", + }, + ) + self.assertEqual(MailboxSpec.from_manifest(manifest.json()).address, address) + + def test_duplicate_local_parts_are_case_insensitive_and_scoped_by_domain(self): + self.request_mailbox("Support") + duplicate = self.client.post(self.request_url, {"local_part": "support"}) + self.assertContains(duplicate, "This mailbox has already been requested.") + + self.assertRedirects( + self.client.post( + reverse("panel:mailbox_create", args=[self.other.pk]), + {"local_part": "Support"}, + ), + self.other.get_absolute_url(), + ) + self.assertEqual(HostingMailbox.objects.count(), 2) + + def test_invalid_request_leaves_the_domain_available(self): + response = self.client.post(self.request_url, {"local_part": "support+tag"}) + + self.assertIn("local_part", response.context["form"].errors) + self.assertFalse(HostingMailDomain.objects.exists()) + + def test_renamed_account_keeps_existing_mail_and_prevents_domain_reassignment(self): + original = self.request_mailbox("support") + mail_domain = original.mail_domain.domain + self.assertRedirects( + self.client.post( + reverse("panel:account_edit", args=[self.account.pk]), + {"name": self.account.name, "primary_domain": "new.example"}, + ), + self.account.get_absolute_url(), + ) + self.assertContains( + self.client.get(self.account.get_absolute_url()), f"support@{mail_domain}" + ) + self.assertRedirects( + self.client.post(self.request_url, {"local_part": "billing"}), + self.account.get_absolute_url(), + ) + self.assertEqual( + HostingMailbox.objects.get(local_part="billing").spec.domain, "new.example" + ) + + HostingAccount.objects.filter(pk=self.other.pk).update( + primary_domain=mail_domain + ) + conflict = self.client.post( + reverse("panel:mailbox_create", args=[self.other.pk]), + {"local_part": "billing"}, + ) + self.assertContains( + conflict, "This mail domain belongs to another hosting account." + ) + self.assertEqual(HostingMailbox.objects.count(), 2) + + def test_reseller_can_see_owned_requests_but_cannot_create_or_export(self): + owned = self.request_mailbox() + other_domain = HostingMailDomain.objects.create( + account=self.other, domain="other.example" + ) + HostingMailbox.objects.create(mail_domain=other_domain, local_part="other") + self.client.force_login(self.reseller_user) + + account = self.client.get(self.account.get_absolute_url()) + self.assertContains(account, owned.spec.address) + self.assertNotContains(account, "other@other.example") + self.assertNotContains(account, "Download mailbox manifest") + self.assertNotContains(account, "Request mailbox") + self.assertEqual( + self.client.get(self.other.get_absolute_url()).status_code, 404 + ) + self.assertEqual( + self.client.post(self.request_url, {"local_part": "another"}).status_code, + 403, + ) + self.assertEqual( + self.client.get( + reverse("panel:mailbox_manifest", args=[owned.pk]) + ).status_code, + 403, + ) + + +class MailboxManifestTests(SimpleTestCase): + def test_inspect_prints_the_canonical_address(self): + directory = Path(self.enterContext(TemporaryDirectory())) + path = directory / "mailbox.json" + path.write_text( + json.dumps(MailboxSpec("Bücher.Example.", "Support").manifest()), + encoding="utf-8", + ) + output = self.enterContext(redirect_stdout(StringIO())) + + self.assertEqual(main(["inspect", str(path)]), 0) + self.assertEqual( + json.loads(output.getvalue()), {"address": "support@xn--bcher-kva.example"} + ) + + def test_manifest_rejects_invalid_recipient_keys_and_unexpected_fields(self): + manifest = MailboxSpec("example.net", "support").manifest() + for change in ( + {"version": True}, + {"version": 2}, + {"kind": "unknown"}, + {"domain": None}, + {"domain": "example.net\nother.example"}, + {"local_part": "../support"}, + {"local_part": "support+tag"}, + {"local_part": "support..team"}, + {"local_part": "support@else.example"}, + {"local_part": "équipe"}, + {"local_part": "a" * 65}, + {"password": "unexpected"}, + ): + with self.subTest(change=change), self.assertRaises(ValueError): + MailboxSpec.from_manifest(manifest | change) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 7224238..0a39867 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -40,6 +40,16 @@ urlpatterns = [ views.DownloadDnsZoneManifest.as_view(), name="dns_zone_manifest", ), + path( + "accounts//mailboxes/new/", + views.MailboxCreate.as_view(), + name="mailbox_create", + ), + path( + "mailboxes//manifest/", + views.DownloadMailboxManifest.as_view(), + name="mailbox_manifest", + ), path( "accounts//plans/", views.RequestWebPlan.as_view(), name="request_plan" ), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 383f10d..3fac36c 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -11,6 +11,7 @@ from django.views.generic import CreateView, DetailView, FormView, ListView, Upd from django.views.generic.detail import SingleObjectMixin from coulobre.dns_node import MAX_SOA_SERIAL +from coulobre.mail_node import INVALID_LOCAL_PART, MailboxSpec from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user from .dns_forms import DnsZoneEditForm, DnsZoneForm @@ -18,6 +19,8 @@ from .models import ( HostingAccount, HostingDatabase, HostingDnsZone, + HostingMailbox, + HostingMailDomain, HostingPlan, WebProvisioningPlan, ) @@ -31,6 +34,7 @@ VIEW_HOSTING_PLANS = "hosting.view_hostingplan" VIEW_RESELLERS = "hosting.view_reseller" VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" +VIEW_MAILBOXES = "hosting.view_hostingmailbox" class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView): @@ -166,6 +170,10 @@ class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView): context["has_primary_zone"] = any( zone.domain == self.object.primary_domain for zone in zones ) + if reseller is not None or user.has_perm(VIEW_MAILBOXES): + context["mailboxes"] = HostingMailbox.objects.filter( + mail_domain__account=self.object + ).select_related("mail_domain") return context @@ -324,6 +332,67 @@ class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): ) +class MailboxCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView): + model = HostingMailbox + fields = ("local_part",) + template_name = "hosting/mailbox_form.html" + permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox") + + @cached_property + def account(self): + return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + form.fields["local_part"].help_text = INVALID_LOCAL_PART + return form + + def get_context_data(self, **kwargs): + return super().get_context_data(account=self.account, **kwargs) + + def form_valid(self, form): + try: + spec = MailboxSpec( + self.account.primary_domain, form.cleaned_data["local_part"] + ) + except ValueError as error: + form.add_error("local_part", str(error)) + return self.form_invalid(form) + + with transaction.atomic(): + mail_domain, _ = HostingMailDomain.objects.get_or_create( + domain=spec.domain, defaults={"account": self.account} + ) + if mail_domain.account_id != self.account.pk: + form.add_error( + None, "This mail domain belongs to another hosting account." + ) + return self.form_invalid(form) + self.object, created = HostingMailbox.objects.get_or_create( + mail_domain=mail_domain, local_part=spec.local_part + ) + if not created: + form.add_error("local_part", "This mailbox has already been requested.") + return self.form_invalid(form) + return redirect(self.account) + + +class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES) + + def get(self, request, pk): + mailbox = get_object_or_404( + HostingMailbox.objects.select_related("mail_domain"), pk=pk + ) + return JsonResponse( + mailbox.spec.manifest(), + headers={ + "Cache-Control": "private, no-store", + "Content-Disposition": f'attachment; filename="coulobre-mailbox-{mailbox.pk}.json"', + }, + ) + + class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): model = HostingPlan permission_required = VIEW_HOSTING_PLANS diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py new file mode 100644 index 0000000..2a1f669 --- /dev/null +++ b/src/coulobre/mail_node.py @@ -0,0 +1,81 @@ +import argparse +import json +import re +from dataclasses import dataclass +from pathlib import Path + +from .domain_names import canonical_domain + +MANIFEST_VERSION = 1 +MANIFEST_KIND = "virtual_mailbox" +LOCAL_PART_MAX_LENGTH = 64 +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 + + 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.") + + @property + def address(self): + return f"{self.local_part}@{self.domain}" + + def manifest(self): + return { + "version": MANIFEST_VERSION, + "kind": MANIFEST_KIND, + "domain": self.domain, + "local_part": self.local_part, + } + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "version", + "kind", + "domain", + "local_part", + }: + raise ValueError("Expected a virtual mailbox manifest.") + if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION: + raise ValueError("Unsupported mailbox manifest version.") + if data["kind"] != MANIFEST_KIND: + raise ValueError("Expected a virtual mailbox manifest.") + return cls(data["domain"], data["local_part"]) + + +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) + 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)) + except (OSError, ValueError) as error: + parser.exit(1, f"coulobre-mail-node: {error}\n") + return 0 -- 2.43.0 From 0804182f17ff4edb7585d3d215ee8506d75341e9 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:37:11 +0100 Subject: [PATCH 2/3] Provision virtual mailboxes with Postfix and Dovecot --- docs/development.md | 77 +++++ src/coulobre/hosting/test_mail_node_apply.py | 149 +++++++++ src/coulobre/mail_node.py | 13 +- src/coulobre/mail_node_apply.py | 310 +++++++++++++++++++ src/coulobre/node_files.py | 4 +- 5 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 src/coulobre/hosting/test_mail_node_apply.py create mode 100644 src/coulobre/mail_node_apply.py diff --git a/docs/development.md b/docs/development.md index 651c9cb..b04a3d0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -195,6 +195,83 @@ mail stack. See the [Dovecot guide to Postfix and LMTP](https://doc.dovecot.org/ coulobre-mail-node inspect coulobre-mailbox-1.json ``` +### Apply a mailbox manifest + +Use an Ubuntu 24.04 mail node with Postfix, Dovecot 2.3 and the `dovecot-imapd` +and `dovecot-lmtpd` packages. Install Coulobre in a root-owned virtual +environment on the node. Use a Postfix hostname outside the set of hosted +mail domains and keep those domains in Postfix's virtual mailbox address +class. See the [Postfix virtual domain guide](https://www.postfix.org/VIRTUAL_README.html). + +On a fresh mail node, create the virtual mail user and empty lookup files. + +```sh +sudo adduser --system --group --no-create-home --home /srv/coulobre-mail \ + --shell /usr/sbin/nologin coulobre-vmail +sudo install -m 0644 /dev/null /etc/postfix/coulobre-domains +sudo install -m 0644 /dev/null /etc/postfix/coulobre-mailboxes +sudo install -o root -g dovecot -m 0640 /dev/null /etc/dovecot/coulobre-users +``` + +Use these values in Postfix's `main.cf`. + +```ini +virtual_mailbox_domains = proxy:texthash:/etc/postfix/coulobre-domains +virtual_mailbox_maps = proxy:texthash:/etc/postfix/coulobre-mailboxes +virtual_transport = lmtp:unix:private/dovecot-lmtp +smtpd_reject_unlisted_recipient = yes +``` + +Replace the stock `auth-system.conf.ext` include in Dovecot's `10-auth.conf` +with the following virtual user configuration. Configure Dovecot's TLS +certificate and keep encrypted client authentication enabled on a public +mail node. See the [Dovecot passwd-file guide](https://doc.dovecot.org/2.3/configuration_manual/authentication/passwd_file/). + +```text +auth_username_format = %Lu +auth_cache_size = 0 +passdb { + driver = passwd-file + args = /etc/dovecot/coulobre-users +} +userdb { + driver = passwd-file + args = /etc/dovecot/coulobre-users +} +``` + +Set the mailbox format and enable the LMTP socket for Postfix in Dovecot. +Use the output of `id -u coulobre-vmail` for both UID settings in place of +the example value `103`. This limits Dovecot mailbox access to the virtual +mail user on this node. See the [Dovecot UID range settings](https://doc.dovecot.org/2.3/settings/core/#first-valid-uid). + +```text +protocols = imap lmtp +mail_location = maildir:~/Maildir +first_valid_uid = 103 +last_valid_uid = 103 +service lmtp { + unix_listener /var/spool/postfix/private/dovecot-lmtp { + user = postfix + group = postfix + mode = 0600 + } +} +``` + +Start Postfix and Dovecot with these settings and apply the manifest. + +```sh +sudo /opt/coulobre/bin/coulobre-mail-node apply coulobre-mailbox-1.json +``` + +The command creates a private mailbox home under `/srv/coulobre-mail/`, +generates the initial password, and prints the path to the root-only +credentials file on the mail node. Dovecot authenticates the full mailbox +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. + ## 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 new file mode 100644 index 0000000..88f4b3d --- /dev/null +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -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") diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index 2a1f669..dd04b55 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -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 diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py new file mode 100644 index 0000000..cab6de2 --- /dev/null +++ b/src/coulobre/mail_node_apply.py @@ -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() diff --git a/src/coulobre/node_files.py b/src/coulobre/node_files.py index bc8894b..5d39bd5 100644 --- a/src/coulobre/node_files.py +++ b/src/coulobre/node_files.py @@ -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) -- 2.43.0 From 32f56deae4badee8e16c451862b3400706851161 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:43:17 +0100 Subject: [PATCH 3/3] 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() -- 2.43.0