From b53f6ba8d622e9380e027059d8d941cbc1e2012b Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 01:51:42 +0100 Subject: [PATCH] Provision local mailboxes from Coulobre Panel --- deploy/panel.env.example | 1 + .../coulobre-mailbox-provisioner.service | 26 ++++ docs/deployment.md | 32 +++++ .../migrations/0016_mailbox_provisioning.py | 47 +++++++ src/coulobre/hosting/models.py | 6 + src/coulobre/hosting/node_client.py | 6 + src/coulobre/hosting/tasks.py | 26 ++++ .../templates/hosting/account_detail.html | 16 ++- ...ioning.html => resource_provisioning.html} | 8 +- .../hosting/test_mailbox_provisioning.py | 118 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 22 +++- src/coulobre/settings.py | 9 ++ 13 files changed, 315 insertions(+), 7 deletions(-) create mode 100644 deploy/systemd/coulobre-mailbox-provisioner.service create mode 100644 src/coulobre/hosting/migrations/0016_mailbox_provisioning.py rename src/coulobre/hosting/templates/hosting/{database_provisioning.html => resource_provisioning.html} (74%) create mode 100644 src/coulobre/hosting/test_mailbox_provisioning.py diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 4a7b1ef..25f85f6 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -11,3 +11,4 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_LOCAL_WEB_ACTIVATION=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1 +# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 diff --git a/deploy/systemd/coulobre-mailbox-provisioner.service b/deploy/systemd/coulobre-mailbox-provisioner.service new file mode 100644 index 0000000..e99a84f --- /dev/null +++ b/deploy/systemd/coulobre-mailbox-provisioner.service @@ -0,0 +1,26 @@ +[Unit] +Description=Coulobre Panel local mailbox provisioning worker +Requires=coulobre-mail-apply.socket +Wants=network-online.target +After=network-online.target coulobre-mail-apply.socket mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-mail-provisioner +Group=coulobre-mail-provisioner +SupplementaryGroups=coulobre-mail-provisioning +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-mailbox-provisioning --hostname=mailbox-provisioner@%H --concurrency=1 +KillMode=mixed +TimeoutStopSec=4min +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/docs/deployment.md b/docs/deployment.md index 6132a21..68474fa 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -273,3 +273,35 @@ Operators need permission to view hosting accounts and DNS zones and the Each request captures the reviewed SOA serial and records. You can edit the zone while it publishes. Publish the newer revision after the current request finishes. Use **Retry publishing** if the current revision failed. + +## Provision local mailboxes from the panel + +Set up [Postfix and Dovecot 2.3](development.md#apply-a-mailbox-manifest) on the +Ubuntu 24.04 panel host and enable the +[mailbox provisioning socket](development.md#enable-local-mailbox-provisioning). +Install the dedicated worker that connects to that socket. + +```sh +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin coulobre-mail-provisioner +sudo install -m 0644 deploy/systemd/coulobre-mailbox-provisioner.service /etc/systemd/system/ +sudo systemctl daemon-reload +``` + +Set `COULOBRE_LOCAL_MAILBOX_PROVISIONING=1` in `/etc/coulobre/panel.env`, then +apply pending migrations and restart the panel services. + +```sh +panel_manage migrate --noinput +sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat +sudo systemctl enable --now coulobre-mailbox-provisioner.service +``` + +Open a hosting account and select **Provision mailbox** for a mailbox request. +Reload the account page to see the status. Use **Retry provisioning** after a +reported failure. Operators need permission to view hosting accounts and +mailbox requests and the **Can add mailbox provisioning** permission. + +The initial password stays in the root-only credentials file on the mail node. +To locate that file, download the manifest and use the node's `apply` command. +Reapplying the manifest preserves the password and prints the file path. diff --git a/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py b/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py new file mode 100644 index 0000000..820ee73 --- /dev/null +++ b/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py @@ -0,0 +1,47 @@ +# Generated by Django 5.2.19 on 2026-11-21 00:48 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0015_dns_publication"), + ] + + operations = [ + migrations.CreateModel( + name="MailboxProvisioning", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ("last_dispatched_at", models.DateTimeField(blank=True, null=True)), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("problem", models.TextField(blank=True)), + ( + "mailbox", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="provisioning", + to="hosting.hostingmailbox", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 5af1288..30bdd75 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -279,3 +279,9 @@ class DnsPublication(ProvisioningJob): manifest = models.JSONField() serial = models.PositiveBigIntegerField() published_serial = models.PositiveBigIntegerField(null=True, blank=True) + + +class MailboxProvisioning(ProvisioningJob): + mailbox = models.OneToOneField( + HostingMailbox, on_delete=models.CASCADE, related_name="provisioning" + ) diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index a12b601..096ce86 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -24,6 +24,12 @@ def publish_local_zone(zone): ) +def provision_local_mailbox(mailbox): + apply_on_local_node( + mailbox, "/run/coulobre-mail-apply.sock", "mail node", "mailbox" + ) + + def encode_manifest(manifest): return json.dumps(manifest).encode("utf-8") diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 792b3ff..040599d 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -11,12 +11,14 @@ from coulobre.web_node import WebSite from .models import ( DatabaseProvisioning, DnsPublication, + MailboxProvisioning, WebActivation, WebProvisioningPlan, ) from .node_client import ( activate_local_site, provision_local_database, + provision_local_mailbox, publish_local_zone, ) @@ -24,6 +26,7 @@ REDISPATCH_AFTER = timedelta(minutes=5) WEB_ACTIVATION_QUEUE = "coulobre-web-activation" DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning" DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing" +MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning" @shared_task @@ -80,6 +83,14 @@ def dispatch_dns_publications(): ) +@shared_task +def dispatch_mailbox_provisioning(): + if settings.LOCAL_MAILBOX_PROVISIONING: + dispatch_provisioning_jobs( + MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE + ) + + def dispatch_provisioning_jobs(model, task, queue): stale_before = timezone.now() - REDISPATCH_AFTER waiting = model.objects.filter(finished_at__isnull=True) @@ -150,6 +161,21 @@ def apply_dns_publication(publication): return {"published_serial": zone.serial} +@shared_task(acks_late=True, reject_on_worker_lost=True) +def provision_mailbox(provisioning_id): + if settings.LOCAL_MAILBOX_PROVISIONING: + run_provisioning_job( + MailboxProvisioning.objects.select_related("mailbox__mail_domain"), + provisioning_id, + apply_mailbox_provisioning, + "Could not complete the request to the local mail node. Check its socket and try again.", + ) + + +def apply_mailbox_provisioning(provisioning): + provision_local_mailbox(provisioning.mailbox.spec) + + def run_provisioning_job(jobs, job_id, apply, connection_problem): started_at = timezone.now() pending = jobs.filter(pk=job_id, finished_at__isnull=True) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 480b385..b30893a 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -66,7 +66,8 @@
Download manifest {% if manage_database_provisioning %} - {% include "hosting/database_provisioning.html" with provisioning=database.provisioning %} + {% url 'panel:database_provision' database.pk as provision_url %} + {% include "hosting/resource_provisioning.html" with provisioning=database.provisioning enabled=local_database_enabled action=provision_url resource=database provision_label="Provision database" %} {% endif %}
{% if manage_database_provisioning and database.provisioning.problem %} @@ -165,7 +166,18 @@ {{ mailbox }} {% if is_operator %} - Download manifest + +
+ Download manifest + {% if manage_mailbox_provisioning %} + {% url 'panel:mailbox_provision' mailbox.pk as provision_url %} + {% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %} + {% endif %} +
+ {% if manage_mailbox_provisioning and mailbox.provisioning.problem %} +

{{ mailbox.provisioning.problem }}

+ {% endif %} + {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/database_provisioning.html b/src/coulobre/hosting/templates/hosting/resource_provisioning.html similarity index 74% rename from src/coulobre/hosting/templates/hosting/database_provisioning.html rename to src/coulobre/hosting/templates/hosting/resource_provisioning.html index f827f9c..bec634d 100644 --- a/src/coulobre/hosting/templates/hosting/database_provisioning.html +++ b/src/coulobre/hosting/templates/hosting/resource_provisioning.html @@ -7,14 +7,14 @@ {% elif provisioning %} Queued {% endif %} -{% if local_database_enabled %} +{% if enabled %} {% if not provisioning or provisioning.state == "failed" %} -
+ {% csrf_token %} {% if provisioning %} - + {% else %} - + {% endif %}
{% endif %} diff --git a/src/coulobre/hosting/test_mailbox_provisioning.py b/src/coulobre/hosting/test_mailbox_provisioning.py new file mode 100644 index 0000000..b5ae0c7 --- /dev/null +++ b/src/coulobre/hosting/test_mailbox_provisioning.py @@ -0,0 +1,118 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import TestCase, override_settings +from django.urls import reverse + +from coulobre.mail_node import MailboxSpec + +from .models import ( + Customer, + HostingAccount, + HostingMailbox, + HostingMailDomain, + MailboxProvisioning, + Reseller, +) +from .tasks import dispatch_mailbox_provisioning, provision_mailbox + + +@override_settings(LOCAL_MAILBOX_PROVISIONING=True) +class MailboxProvisioningTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_user("operator") + cls.customer = users.create_user("customer") + cls.reseller = users.create_user("reseller") + cls.permissions = Permission.objects.filter( + content_type__app_label="hosting", + codename__in=( + "view_hostingaccount", + "view_hostingmailbox", + "add_mailboxprovisioning", + ), + ) + for user in (cls.operator, cls.customer, cls.reseller): + user.user_permissions.add(*cls.permissions) + cls.account = HostingAccount.objects.create( + name="Mail hosting", + primary_domain="site.example", + customer=Customer.objects.create(user=cls.customer), + reseller=Reseller.objects.create(user=cls.reseller), + ) + domain = HostingMailDomain.objects.create( + account=cls.account, domain="site.example" + ) + cls.mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="support" + ) + + def setUp(self): + self.client.force_login(self.operator) + self.detail = self.account.get_absolute_url() + self.url = reverse("panel:mailbox_provision", args=[self.mailbox.pk]) + + def test_local_worker_provisions_the_requested_address_once(self): + self.assertContains(self.client.get(self.detail), "Provision mailbox") + self.assertEqual(self.client.get(self.url).status_code, 405) + for _ in range(2): + self.assertRedirects(self.client.post(self.url), self.detail) + job = MailboxProvisioning.objects.get(mailbox=self.mailbox) + self.assertContains(self.client.get(self.detail), "Queued") + with patch.object(provision_mailbox, "apply_async") as send: + dispatch_mailbox_provisioning.run() + dispatch_mailbox_provisioning.run() + send.assert_called_once_with( + args=[job.pk], queue="coulobre-mailbox-provisioning", retry=False + ) + + HostingAccount.objects.filter(pk=self.account.pk).update( + primary_domain="new.example" + ) + with patch("coulobre.hosting.tasks.provision_local_mailbox") as apply: + provision_mailbox.run(job.pk) + provision_mailbox.run(job.pk) + apply.assert_called_once_with(MailboxSpec("site.example", "support")) + self.assertContains(self.client.get(self.detail), "Configured") + + def test_customer_reseller_and_viewer_cannot_provision(self): + viewer = get_user_model().objects.create_user("viewer") + viewer.user_permissions.add( + *self.permissions.exclude(codename="add_mailboxprovisioning") + ) + for user in (self.customer, self.reseller, viewer): + with self.subTest(user=user): + self.client.force_login(user) + self.assertNotContains( + self.client.get(self.detail), "Provision mailbox" + ) + self.assertEqual(self.client.post(self.url).status_code, 403) + self.assertFalse(MailboxProvisioning.objects.exists()) + + @override_settings(LOCAL_MAILBOX_PROVISIONING=False) + def test_disabled_provisioning_leaves_manifest_downloads_available(self): + self.assertNotContains(self.client.get(self.detail), "Provision mailbox") + self.assertEqual(self.client.post(self.url).status_code, 404) + manifest_url = reverse("panel:mailbox_manifest", args=[self.mailbox.pk]) + self.assertEqual( + self.client.get(manifest_url).json(), self.mailbox.spec.manifest() + ) + + def test_failed_provisioning_can_be_retried(self): + self.assertRedirects(self.client.post(self.url), self.detail) + job = MailboxProvisioning.objects.get(mailbox=self.mailbox) + with patch( + "coulobre.hosting.tasks.provision_local_mailbox", side_effect=OSError + ): + provision_mailbox.run(job.pk) + detail = self.client.get(self.detail) + self.assertContains(detail, "Retry provisioning") + self.assertContains( + detail, "Could not complete the request to the local mail node" + ) + self.assertRedirects(self.client.post(self.url), self.detail) + job.refresh_from_db() + self.assertEqual(job.state, "queued") + self.assertFalse(job.problem) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index b9a1858..9c5389c 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -67,6 +67,11 @@ urlpatterns = [ views.DownloadMailboxManifest.as_view(), name="mailbox_manifest", ), + path( + "mailboxes//provision/", + views.RequestMailboxProvisioning.as_view(), + name="mailbox_provision", + ), 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 714c400..60eaa11 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -35,6 +35,7 @@ from .models import ( HostingDnsZone, HostingMailbox, HostingPlan, + MailboxProvisioning, Reseller, WebActivation, WebProvisioningPlan, @@ -55,6 +56,7 @@ VIEW_MAILBOXES = "hosting.view_hostingmailbox" ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning") PUBLISH_DNS = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_dnspublication") +PROVISION_MAILBOX = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_mailboxprovisioning") class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): @@ -213,9 +215,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): zone.domain == self.object.primary_domain for zone in zones ) if tenant or user.has_perm(VIEW_MAILBOXES): - context["mailboxes"] = HostingMailbox.objects.filter( + mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object ).select_related("mail_domain") + if not tenant and user.has_perms(PROVISION_MAILBOX): + mailboxes = mailboxes.select_related("provisioning") + context["manage_mailbox_provisioning"] = True + context["local_mailbox_enabled"] = settings.LOCAL_MAILBOX_PROVISIONING + context["mailboxes"] = mailboxes return context @@ -516,6 +523,19 @@ class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): ) +class RequestMailboxProvisioning(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = PROVISION_MAILBOX + + def post(self, request, pk): + if not settings.LOCAL_MAILBOX_PROVISIONING: + raise Http404 + mailbox = get_object_or_404( + HostingMailbox.objects.select_related("mail_domain__account"), pk=pk + ) + MailboxProvisioning.objects.queue(mailbox=mailbox) + return redirect(mailbox.mail_domain.account) + + class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): model = HostingPlan permission_required = VIEW_HOSTING_PLANS diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 34fac6b..82bbfbf 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -111,6 +111,9 @@ LOCAL_DATABASE_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" ) LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1" +LOCAL_MAILBOX_PROVISIONING = ( + os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1" +) CELERY_BEAT_SCHEDULE = { "dispatch-web-provisioning-plans": { "task": "coulobre.hosting.tasks.dispatch_web_plans", @@ -136,3 +139,9 @@ if LOCAL_DNS_PUBLISHING: "schedule": 5.0, "options": {"expires": 4.0}, } +if LOCAL_MAILBOX_PROVISIONING: + CELERY_BEAT_SCHEDULE["dispatch-mailbox-provisioning"] = { + "task": "coulobre.hosting.tasks.dispatch_mailbox_provisioning", + "schedule": 5.0, + "options": {"expires": 4.0}, + }