diff --git a/deploy/dovecot/coulobre-2.4.conf.example b/deploy/dovecot/coulobre-2.4.conf.example new file mode 100644 index 0000000..f6f4526 --- /dev/null +++ b/deploy/dovecot/coulobre-2.4.conf.example @@ -0,0 +1,30 @@ +dovecot_config_version = 2.4.0 +dovecot_storage_version = 2.4.0 +protocols = imap lmtp + +ssl = required +ssl_server_cert_file = /etc/ssl/coulobre-mail/fullchain.pem +ssl_server_key_file = /etc/ssl/coulobre-mail/privkey.pem + +mail_driver = maildir +mail_path = ~/Maildir +# Set both values to the UID of coulobre-vmail. +first_valid_uid = 103 +last_valid_uid = 103 + +auth_username_format = %{user | lower} +auth_cache_size = 0 +passdb passwd-file { + passwd_file_path = /etc/dovecot/coulobre-users +} +userdb passwd-file { + passwd_file_path = /etc/dovecot/coulobre-users +} + +service lmtp { + unix_listener /var/spool/postfix/private/dovecot-lmtp { + user = postfix + group = postfix + mode = 0600 + } +} 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-mail-apply.socket b/deploy/systemd/coulobre-mail-apply.socket new file mode 100644 index 0000000..af52628 --- /dev/null +++ b/deploy/systemd/coulobre-mail-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local mailbox provisioning socket + +[Socket] +ListenStream=/run/coulobre-mail-apply.sock +SocketUser=root +SocketGroup=coulobre-mail-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-mail-apply@.service b/deploy/systemd/coulobre-mail-apply@.service new file mode 100644 index 0000000..d092357 --- /dev/null +++ b/deploy/systemd/coulobre-mail-apply@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre local mailbox provisioning request +After=postfix.service dovecot.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +StateDirectory=coulobre/mail-node +StateDirectoryMode=0700 +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-mail-node apply-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true 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..3a7b10c 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](development.md#apply-a-mailbox-manifest) on the +Ubuntu 24.04 or 26.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/docs/development.md b/docs/development.md index d257c6a..9eb7d8e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -316,11 +316,11 @@ 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). +Use Ubuntu 24.04 with Dovecot 2.3 or Ubuntu 26.04 with Dovecot 2.4. Install +Postfix, `dovecot-imapd`, and `dovecot-lmtpd`. 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. @@ -341,6 +341,8 @@ virtual_transport = lmtp:unix:private/dovecot-lmtp smtpd_reject_unlisted_recipient = yes ``` +#### Dovecot 2.3 on Ubuntu 24.04 + 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 @@ -378,7 +380,20 @@ service lmtp { } ``` -Start Postfix and Dovecot with these settings and apply the manifest. +#### Dovecot 2.4 on Ubuntu 26.04 + +For a fresh, dedicated mail node, use the +[Dovecot 2.4 configuration example](../deploy/dovecot/coulobre-2.4.conf.example) +as `/etc/dovecot/dovecot.conf`. Set the certificate and key paths for the mail +hostname. Use the output of `id -u coulobre-vmail` for both UID settings. +For an existing mail node, follow the +[Dovecot upgrade guide](https://doc.dovecot.org/2.4.2/installation/upgrade/2.3-to-2.4.html) +to migrate its configuration and retain its Maildirs and Coulobre registry. + +#### Install the mailbox + +Start Postfix first to initialize its spool directory, then start Dovecot so +it can bind the LMTP socket. Apply the manifest once both services are running. ```sh sudo /opt/coulobre/bin/coulobre-mail-node apply coulobre-mailbox-1.json @@ -414,6 +429,27 @@ installation needs attention. Exit code `1` indicates an invalid manifest or an invocation error such as running the check without root privileges. +### Enable local mailbox provisioning + +On a mail node with the same Postfix and Dovecot setup, install Coulobre in a +root-owned virtual environment at `/opt/coulobre` and enable the provisioning +socket. + +```sh +getent group coulobre-mail-provisioning >/dev/null || sudo groupadd --system coulobre-mail-provisioning +sudo install -m 0644 deploy/systemd/coulobre-mail-apply.socket \ + deploy/systemd/coulobre-mail-apply@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-mail-apply.socket +``` + +Grant the socket group only to the service identity responsible for mailbox +provisioning. Send one version 1 mailbox manifest as UTF-8 JSON to +`/run/coulobre-mail-apply.sock`, with a limit of 4 KiB. Shut down the writing +half of the connection and read the JSON reply to EOF. For a valid manifest, +the reply identifies the mailbox and reports `configured` or `failed`. +The generated password stays in a root-only credentials file on the mail node. + ## Inspect a DirectAdmin backup Use an account archive from DirectAdmin's Site Backup, Manage User Backups 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_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index fcc9ea5..ae363aa 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -2,7 +2,7 @@ import json import os import stat from contextlib import redirect_stdout -from io import StringIO +from io import BytesIO, StringIO from pathlib import Path from subprocess import CompletedProcess from tempfile import TemporaryDirectory @@ -14,6 +14,7 @@ from django.test import SimpleTestCase from coulobre.mail_node import MailboxSpec, main from coulobre.mail_node_apply import ( apply_mailbox, + check_dovecot_maildir, credential_path, ensure_mail_home, mailbox_status, @@ -21,6 +22,42 @@ from coulobre.mail_node_apply import ( ) +class MailboxApplyRequestTests(SimpleTestCase): + def setUp(self): + self.mailbox = MailboxSpec("example.net", "support") + self.apply = self.enterContext( + patch( + "coulobre.mail_node_apply.apply_mailbox", + return_value=Path("/private/credentials.json"), + ) + ) + + def request(self, manifest): + output = StringIO() + with ( + patch( + "sys.stdin", + SimpleNamespace(buffer=BytesIO(json.dumps(manifest).encode())), + ), + redirect_stdout(output), + ): + code = main(["apply-request"]) + return code, json.loads(output.getvalue()) + + def test_request_reports_the_mailbox_identity_only(self): + manifest = self.mailbox.manifest() + code, reply = self.request(manifest) + self.apply.assert_called_once_with(self.mailbox) + self.assertEqual(code, 0) + self.assertEqual(reply, manifest | {"state": "configured", "problem": None}) + + def test_request_rejects_extra_credentials_before_acting(self): + code, reply = self.request(self.mailbox.manifest() | {"password": "untrusted"}) + self.assertEqual(code, 1) + self.assertEqual(reply["state"], "failed") + self.apply.assert_not_called() + + class MailboxApplyTests(SimpleTestCase): def setUp(self): directory = Path(self.enterContext(TemporaryDirectory())) @@ -222,6 +259,31 @@ class MailboxApplyTests(SimpleTestCase): class MailboxCommandTests(SimpleTestCase): + def test_dovecot_24_checks_the_maildir_driver_and_path(self): + with patch( + "coulobre.mail_node_apply.run", + side_effect=["2.4.2 (build)", "maildir", "~/Maildir"], + ): + check_dovecot_maildir() + + def test_dovecot_24_rejects_an_unmanaged_driver_or_path(self): + for settings in (["mdbox"], ["maildir", "~/other"]): + with ( + self.subTest(settings=settings), + patch("coulobre.mail_node_apply.run", side_effect=["2.4.2", *settings]), + self.assertRaisesMessage(ValueError, "mail_driver and mail_path"), + ): + check_dovecot_maildir() + + def test_dovecot_23_checks_the_legacy_maildir_setting(self): + with patch( + "coulobre.mail_node_apply.run", + side_effect=["2.3.21 (build)", "maildir:~/Maildir"], + ) as command: + check_dovecot_maildir() + + command.assert_called_with("doveconf", "-h", "mail_location") + def test_password_tool_errors_omit_sensitive_input_and_output(self): command = ("doveadm", "pw", "-s", "SHA512-CRYPT") with ( 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/mail_node.py b/src/coulobre/mail_node.py index 9440986..468f9d5 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -5,6 +5,7 @@ from dataclasses import dataclass from pathlib import Path from .domain_names import canonical_domain +from .node_requests import serve_apply_request MANIFEST_VERSION = 1 MANIFEST_KIND = "virtual_mailbox" @@ -74,10 +75,21 @@ def main(argv=None): "apply", help="Install a virtual mailbox on the mail node." ) apply.add_argument("manifest", type=Path) + commands.add_parser( + "apply-request", + help="Apply one mailbox manifest from standard input and report JSON.", + ) status = commands.add_parser("status", help="Check an installed virtual mailbox.") status.add_argument("manifest", type=Path) args = parser.parse_args(argv) + if args.command == "apply-request": + from .mail_node_apply import apply_mailbox + + return serve_apply_request( + MANIFEST_VERSION, MailboxSpec.from_manifest, apply_mailbox + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) mailbox = MailboxSpec.from_manifest(payload) diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index cf8b0cf..66bf940 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -347,8 +347,7 @@ def check_services(mailbox): 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.") + check_dovecot_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): @@ -365,6 +364,20 @@ def check_services(mailbox): return account, auth_group +def check_dovecot_maildir(): + version = re.match(r"(\d+)\.(\d+)", run("dovecot", "--version")) + if version and tuple(map(int, version.groups())) >= (2, 4): + if ( + run("doveconf", "-h", "mail_driver") != "maildir" + or run("doveconf", "-h", "mail_path") != "~/Maildir" + ): + raise ValueError( + "Configure Dovecot mail_driver and mail_path for the managed Maildir." + ) + elif run("doveconf", "-h", "mail_location") != "maildir:~/Maildir": + raise ValueError("Configure Dovecot mail_location for the managed Maildir.") + + def dovecot_home(mailbox): return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67) 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}, + }