Provision local mailboxes from Coulobre Panel #16

Merged
parkel merged 3 commits from feature/local-mailbox-provisioning into main 2026-11-21 02:01:46 +01:00
20 changed files with 511 additions and 16 deletions

No files matched your search

+30
View File
@@ -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
}
}
+1
View File
@@ -11,3 +11,4 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_WEB_ACTIVATION=1 # COULOBRE_LOCAL_WEB_ACTIVATION=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# COULOBRE_LOCAL_DNS_PUBLISHING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
+14
View File
@@ -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
@@ -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
@@ -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
+32
View File
@@ -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 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 zone while it publishes. Publish the newer revision after the current request
finishes. Use **Retry publishing** if the current revision failed. 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.
+42 -6
View File
@@ -316,11 +316,11 @@ coulobre-mail-node inspect coulobre-mailbox-1.json
### Apply a mailbox manifest ### Apply a mailbox manifest
Use an Ubuntu 24.04 mail node with Postfix, Dovecot 2.3 and the `dovecot-imapd` Use Ubuntu 24.04 with Dovecot 2.3 or Ubuntu 26.04 with Dovecot 2.4. Install
and `dovecot-lmtpd` packages. Install Coulobre in a root-owned virtual Postfix, `dovecot-imapd`, and `dovecot-lmtpd`. Install Coulobre in a root-owned
environment on the node. Use a Postfix hostname outside the set of hosted virtual environment on the node. Use a Postfix hostname outside the set of
mail domains and keep those domains in Postfix's virtual mailbox address hosted mail domains and keep those domains in Postfix's virtual mailbox
class. See the [Postfix virtual domain guide](https://www.postfix.org/VIRTUAL_README.html). 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. 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 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` Replace the stock `auth-system.conf.ext` include in Dovecot's `10-auth.conf`
with the following virtual user configuration. Configure Dovecot's TLS with the following virtual user configuration. Configure Dovecot's TLS
certificate and keep encrypted client authentication enabled on a public 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 ```sh
sudo /opt/coulobre/bin/coulobre-mail-node apply coulobre-mailbox-1.json 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 Exit code `1` indicates an invalid manifest or an invocation error such as
running the check without root privileges. 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 ## Inspect a DirectAdmin backup
Use an account archive from DirectAdmin's Site Backup, Manage User Backups Use an account archive from DirectAdmin's Site Backup, Manage User Backups
@@ -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,
},
),
]
+6
View File
@@ -279,3 +279,9 @@ class DnsPublication(ProvisioningJob):
manifest = models.JSONField() manifest = models.JSONField()
serial = models.PositiveBigIntegerField() serial = models.PositiveBigIntegerField()
published_serial = models.PositiveBigIntegerField(null=True, blank=True) published_serial = models.PositiveBigIntegerField(null=True, blank=True)
class MailboxProvisioning(ProvisioningJob):
mailbox = models.OneToOneField(
HostingMailbox, on_delete=models.CASCADE, related_name="provisioning"
)
+6
View File
@@ -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): def encode_manifest(manifest):
return json.dumps(manifest).encode("utf-8") return json.dumps(manifest).encode("utf-8")
+26
View File
@@ -11,12 +11,14 @@ from coulobre.web_node import WebSite
from .models import ( from .models import (
DatabaseProvisioning, DatabaseProvisioning,
DnsPublication, DnsPublication,
MailboxProvisioning,
WebActivation, WebActivation,
WebProvisioningPlan, WebProvisioningPlan,
) )
from .node_client import ( from .node_client import (
activate_local_site, activate_local_site,
provision_local_database, provision_local_database,
provision_local_mailbox,
publish_local_zone, publish_local_zone,
) )
@@ -24,6 +26,7 @@ REDISPATCH_AFTER = timedelta(minutes=5)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation" WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning" DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning"
DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing" DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing"
MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning"
@shared_task @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): def dispatch_provisioning_jobs(model, task, queue):
stale_before = timezone.now() - REDISPATCH_AFTER stale_before = timezone.now() - REDISPATCH_AFTER
waiting = model.objects.filter(finished_at__isnull=True) waiting = model.objects.filter(finished_at__isnull=True)
@@ -150,6 +161,21 @@ def apply_dns_publication(publication):
return {"published_serial": zone.serial} 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): def run_provisioning_job(jobs, job_id, apply, connection_problem):
started_at = timezone.now() started_at = timezone.now()
pending = jobs.filter(pk=job_id, finished_at__isnull=True) pending = jobs.filter(pk=job_id, finished_at__isnull=True)
@@ -66,7 +66,8 @@
<div class="form-actions"> <div class="form-actions">
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a> <a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% if manage_database_provisioning %} {% 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 %} {% endif %}
</div> </div>
{% if manage_database_provisioning and database.provisioning.problem %} {% if manage_database_provisioning and database.provisioning.problem %}
@@ -165,7 +166,18 @@
<tr> <tr>
<td class="domain">{{ mailbox }}</td> <td class="domain">{{ mailbox }}</td>
{% if is_operator %} {% if is_operator %}
<td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td> <td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
{% 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 %}
</div>
{% if manage_mailbox_provisioning and mailbox.provisioning.problem %}
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
{% endif %}
</td>
{% endif %} {% endif %}
</tr> </tr>
{% endfor %} {% endfor %}
@@ -7,14 +7,14 @@
{% elif provisioning %} {% elif provisioning %}
<span class="status pending">Queued</span> <span class="status pending">Queued</span>
{% endif %} {% endif %}
{% if local_database_enabled %} {% if enabled %}
{% if not provisioning or provisioning.state == "failed" %} {% if not provisioning or provisioning.state == "failed" %}
<form method="post" action="{% url 'panel:database_provision' database.pk %}"> <form method="post" action="{{ action }}">
{% csrf_token %} {% csrf_token %}
{% if provisioning %} {% if provisioning %}
<button class="button secondary" type="submit" aria-label="Retry provisioning {{ database }}">Retry provisioning</button> <button class="button secondary" type="submit" aria-label="Retry provisioning {{ resource }}">Retry provisioning</button>
{% else %} {% else %}
<button class="button secondary" type="submit" aria-label="Provision database {{ database }}">Provision database</button> <button class="button secondary" type="submit" aria-label="{{ provision_label }} {{ resource }}">{{ provision_label }}</button>
{% endif %} {% endif %}
</form> </form>
{% endif %} {% endif %}
+63 -1
View File
@@ -2,7 +2,7 @@ import json
import os import os
import stat import stat
from contextlib import redirect_stdout from contextlib import redirect_stdout
from io import StringIO from io import BytesIO, StringIO
from pathlib import Path from pathlib import Path
from subprocess import CompletedProcess from subprocess import CompletedProcess
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
@@ -14,6 +14,7 @@ from django.test import SimpleTestCase
from coulobre.mail_node import MailboxSpec, main from coulobre.mail_node import MailboxSpec, main
from coulobre.mail_node_apply import ( from coulobre.mail_node_apply import (
apply_mailbox, apply_mailbox,
check_dovecot_maildir,
credential_path, credential_path,
ensure_mail_home, ensure_mail_home,
mailbox_status, 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): class MailboxApplyTests(SimpleTestCase):
def setUp(self): def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory())) directory = Path(self.enterContext(TemporaryDirectory()))
@@ -222,6 +259,31 @@ class MailboxApplyTests(SimpleTestCase):
class MailboxCommandTests(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): def test_password_tool_errors_omit_sensitive_input_and_output(self):
command = ("doveadm", "pw", "-s", "SHA512-CRYPT") command = ("doveadm", "pw", "-s", "SHA512-CRYPT")
with ( with (
@@ -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)
+5
View File
@@ -67,6 +67,11 @@ urlpatterns = [
views.DownloadMailboxManifest.as_view(), views.DownloadMailboxManifest.as_view(),
name="mailbox_manifest", name="mailbox_manifest",
), ),
path(
"mailboxes/<int:pk>/provision/",
views.RequestMailboxProvisioning.as_view(),
name="mailbox_provision",
),
path( path(
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan" "accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
), ),
+21 -1
View File
@@ -35,6 +35,7 @@ from .models import (
HostingDnsZone, HostingDnsZone,
HostingMailbox, HostingMailbox,
HostingPlan, HostingPlan,
MailboxProvisioning,
Reseller, Reseller,
WebActivation, WebActivation,
WebProvisioningPlan, WebProvisioningPlan,
@@ -55,6 +56,7 @@ VIEW_MAILBOXES = "hosting.view_hostingmailbox"
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning") PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning")
PUBLISH_DNS = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_dnspublication") PUBLISH_DNS = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_dnspublication")
PROVISION_MAILBOX = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_mailboxprovisioning")
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
@@ -213,9 +215,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
zone.domain == self.object.primary_domain for zone in zones zone.domain == self.object.primary_domain for zone in zones
) )
if tenant or user.has_perm(VIEW_MAILBOXES): if tenant or user.has_perm(VIEW_MAILBOXES):
context["mailboxes"] = HostingMailbox.objects.filter( mailboxes = HostingMailbox.objects.filter(
mail_domain__account=self.object mail_domain__account=self.object
).select_related("mail_domain") ).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 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): class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
model = HostingPlan model = HostingPlan
permission_required = VIEW_HOSTING_PLANS permission_required = VIEW_HOSTING_PLANS
+12
View File
@@ -5,6 +5,7 @@ from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from .domain_names import canonical_domain from .domain_names import canonical_domain
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
MANIFEST_KIND = "virtual_mailbox" MANIFEST_KIND = "virtual_mailbox"
@@ -74,10 +75,21 @@ def main(argv=None):
"apply", help="Install a virtual mailbox on the mail node." "apply", help="Install a virtual mailbox on the mail node."
) )
apply.add_argument("manifest", type=Path) 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 = commands.add_parser("status", help="Check an installed virtual mailbox.")
status.add_argument("manifest", type=Path) status.add_argument("manifest", type=Path)
args = parser.parse_args(argv) 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: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))
mailbox = MailboxSpec.from_manifest(payload) mailbox = MailboxSpec.from_manifest(payload)
+15 -2
View File
@@ -347,8 +347,7 @@ def check_services(mailbox):
local_domains = run("postconf", "-hx", "mydestination") local_domains = run("postconf", "-hx", "mydestination")
if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()): if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()):
raise ValueError("The requested mail domain is a local Postfix destination.") raise ValueError("The requested mail domain is a local Postfix destination.")
if run("doveconf", "-h", "mail_location") != "maildir:~/Maildir": check_dovecot_maildir()
raise ValueError("Configure Dovecot mail_location for the managed Maildir.")
first_uid = int(run("doveconf", "-h", "first_valid_uid")) first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_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): 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 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): def dovecot_home(mailbox):
return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67) return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67)
+9
View File
@@ -111,6 +111,9 @@ LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
) )
LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "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 = { CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": { "dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans", "task": "coulobre.hosting.tasks.dispatch_web_plans",
@@ -136,3 +139,9 @@ if LOCAL_DNS_PUBLISHING:
"schedule": 5.0, "schedule": 5.0,
"options": {"expires": 4.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},
}