From 4bd7a905806b7bdc2ea6bf28c727b943ddccd78a Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:24:40 +0100 Subject: [PATCH] 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