Merge pull request 'Add virtual mailbox provisioning with Postfix and Dovecot' (#7) from feature/mailbox-provisioning into main

Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
parkel committed 2026-11-19 23:43:44 +01:00
commit 90405f696f
13 files changed
+1304 -1

No files matched your search

+119
View File
@@ -176,6 +176,125 @@ 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
```
### Apply a mailbox manifest
Use an Ubuntu 24.04 mail node with Postfix, Dovecot 2.3 and the `dovecot-imapd`
and `dovecot-lmtpd` packages. Install Coulobre in a root-owned virtual
environment on the node. Use a Postfix hostname outside the set of hosted
mail domains and keep those domains in Postfix's virtual mailbox address
class. See the [Postfix virtual domain guide](https://www.postfix.org/VIRTUAL_README.html).
On a fresh mail node, create the virtual mail user and empty lookup files.
```sh
sudo adduser --system --group --no-create-home --home /srv/coulobre-mail \
--shell /usr/sbin/nologin coulobre-vmail
sudo install -m 0644 /dev/null /etc/postfix/coulobre-domains
sudo install -m 0644 /dev/null /etc/postfix/coulobre-mailboxes
sudo install -o root -g dovecot -m 0640 /dev/null /etc/dovecot/coulobre-users
```
Use these values in Postfix's `main.cf`.
```ini
virtual_mailbox_domains = proxy:texthash:/etc/postfix/coulobre-domains
virtual_mailbox_maps = proxy:texthash:/etc/postfix/coulobre-mailboxes
virtual_transport = lmtp:unix:private/dovecot-lmtp
smtpd_reject_unlisted_recipient = yes
```
Replace the stock `auth-system.conf.ext` include in Dovecot's `10-auth.conf`
with the following virtual user configuration. Configure Dovecot's TLS
certificate and keep encrypted client authentication enabled on a public
mail node. See the [Dovecot passwd-file guide](https://doc.dovecot.org/2.3/configuration_manual/authentication/passwd_file/).
```text
auth_username_format = %Lu
auth_cache_size = 0
passdb {
driver = passwd-file
args = /etc/dovecot/coulobre-users
}
userdb {
driver = passwd-file
args = /etc/dovecot/coulobre-users
}
```
Set the mailbox format and enable the LMTP socket for Postfix in Dovecot.
Use the output of `id -u coulobre-vmail` for both UID settings in place of
the example value `103`. This limits Dovecot mailbox access to the virtual
mail user on this node. See the [Dovecot UID range settings](https://doc.dovecot.org/2.3/settings/core/#first-valid-uid).
```text
protocols = imap lmtp
mail_location = maildir:~/Maildir
first_valid_uid = 103
last_valid_uid = 103
service lmtp {
unix_listener /var/spool/postfix/private/dovecot-lmtp {
user = postfix
group = postfix
mode = 0600
}
}
```
Start Postfix and Dovecot with these settings and apply the manifest.
```sh
sudo /opt/coulobre/bin/coulobre-mail-node apply coulobre-mailbox-1.json
```
The command creates a private mailbox home under `/srv/coulobre-mail/`,
generates the initial password, and prints the path to the root-only
credentials file on the mail node. Dovecot authenticates the full mailbox
address using a password hash. Postfix accepts listed recipients and
hands delivery to Dovecot over the local LMTP socket. Reapply the same
manifest to resume installation with the same credentials.
### Check a mailbox installation
Run the status command on the mail node with the same manifest.
```sh
sudo /opt/coulobre/bin/coulobre-mail-node status coulobre-mailbox-1.json
```
The check reads the local registry, mailbox home and lookup files. It
queries the running Postfix service for the domain and recipient and
tests the saved login against Dovecot's local authentication service.
The JSON report includes the address, state and a diagnostic when the
installation needs attention.
| State | Exit code | Meaning |
| --- | --- | --- |
| `configured` | 0 | The local mailbox and service checks passed. |
| `not_installed` | 2 | The mailbox is absent from the local registry and mail services. |
| `needs_attention` | 2 | An installation, configuration or service check failed. |
Exit code `1` indicates an invalid manifest or an invocation error such as
running the check without root privileges.
## Request an Apache configuration preview
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
+1
View File
@@ -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]
@@ -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",
)
],
},
),
]
+34
View File
@@ -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)
@@ -106,4 +106,38 @@
{% endif %}
</section>
{% endif %}
{% if is_reseller or perms.hosting.view_hostingmailbox %}
<section class="surface" aria-labelledby="mailboxes-heading">
<header class="section-heading">
<h2 id="mailboxes-heading">Mailbox requests</h2>
{% if not is_reseller and perms.hosting.add_hostingmailbox %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
{% endif %}
</header>
{% if mailboxes %}
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Email address</th>
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}
</tr>
</thead>
<tbody>
{% for mailbox in mailboxes %}
<tr>
<td class="domain">{{ mailbox }}</td>
{% if not is_reseller %}
<td><a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No mailboxes requested yet.</p>
{% endif %}
</section>
{% endif %}
{% endblock %}
@@ -0,0 +1,21 @@
{% extends "hosting/base.html" %}
{% block title %}Request mailbox · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Request mailbox</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Request mailbox</button>
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,249 @@
import json
import os
import stat
from contextlib import redirect_stdout
from io import StringIO
from pathlib import Path
from subprocess import CompletedProcess
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from django.test import SimpleTestCase
from coulobre.mail_node import MailboxSpec, main
from coulobre.mail_node_apply import (
apply_mailbox,
credential_path,
ensure_mail_home,
mailbox_status,
run,
)
class MailboxApplyTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.state = directory / "state"
self.storage = directory / "homes"
self.domains = directory / "domains"
self.mailboxes = directory / "mailboxes"
self.users = directory / "users"
settings = {
"STATE_DIRECTORY": self.state,
"MAIL_ROOT": self.storage,
"POSTFIX_DOMAINS": self.domains,
"POSTFIX_MAILBOXES": self.mailboxes,
"DOVECOT_USERS": self.users,
}
for name, value in settings.items():
self.enterContext(patch(f"coulobre.mail_node_apply.{name}", value))
self.enterContext(patch("coulobre.mail_node_apply.os.geteuid", return_value=0))
self.enterContext(
patch(
"coulobre.mail_node_apply.require_root_directory",
side_effect=self.prepare_directory,
)
)
self.enterContext(
patch(
"coulobre.mail_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
)
)
self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001)
self.enterContext(
patch(
"coulobre.mail_node_apply.check_services",
return_value=(self.account, os.getegid()),
)
)
self.resolve_home = self.enterContext(
patch("coulobre.mail_node_apply.dovecot_home", side_effect=self.lookup_home)
)
self.prepare_home = self.enterContext(
patch("coulobre.mail_node_apply.ensure_mail_home")
)
self.commands = self.enterContext(patch("coulobre.mail_node_apply.run"))
self.commands.return_value = "{SHA512-CRYPT}$6$mockSalt$" + ("A" * 86)
self.postfix_lookup = self.enterContext(
patch("coulobre.mail_node_apply.postfix_lookup", return_value=None)
)
self.spec = MailboxSpec("example.net", "support")
def prepare_directory(self, path, *, create_mode=None):
if create_mode is not None:
path.mkdir(mode=create_mode, exist_ok=True)
def lookup_home(self, mailbox):
if self.users.exists() and f"{mailbox.address}:" in self.users.read_text():
return str(self.storage / mailbox.domain / mailbox.local_part)
return None
def test_reapplying_preserves_password_and_privately_publishes_the_hash(self):
credential_file = apply_mailbox(self.spec)
original = credential_file.read_bytes()
self.assertEqual(apply_mailbox(self.spec), credential_file)
self.assertEqual(credential_file.read_bytes(), original)
self.assertEqual(stat.S_IMODE(credential_file.stat().st_mode), 0o600)
record = json.loads(original)
self.assertIn(record["password_hash"], self.users.read_text())
self.assertNotIn(record["password"], self.users.read_text())
self.assertEqual(stat.S_IMODE(self.users.stat().st_mode), 0o640)
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
self.assertIn("example.net\t1", self.domains.read_text())
def test_pending_mailbox_is_published_only_after_its_home_is_prepared(self):
self.prepare_home.side_effect = ValueError("Interrupted before home creation.")
with self.assertRaisesRegex(ValueError, "Interrupted"):
apply_mailbox(self.spec)
credential_file = credential_path(self.spec)
original = credential_file.read_bytes()
self.assertFalse(self.mailboxes.exists())
self.prepare_home.side_effect = None
apply_mailbox(MailboxSpec("example.net", "sales"))
self.assertIn("sales@example.net\t1", self.mailboxes.read_text())
self.assertNotIn("support@example.net", self.mailboxes.read_text())
self.assertEqual(apply_mailbox(self.spec), credential_file)
self.assertEqual(credential_file.read_bytes(), original)
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
def test_waits_for_dovecot_to_read_the_updated_authentication_file(self):
home = self.storage / self.spec.domain / self.spec.local_part
self.resolve_home.side_effect = [None, None, str(home)]
with patch("coulobre.mail_node_apply.time.sleep") as pause:
apply_mailbox(self.spec)
pause.assert_called_once()
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
def test_unmanaged_lookup_is_preserved_without_reserving_credentials(self):
self.mailboxes.write_text("existing@example.net\t1\n", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "differ from Coulobre's registry"):
apply_mailbox(self.spec)
self.assertEqual(self.mailboxes.read_text(), "existing@example.net\t1\n")
self.assertFalse(credential_path(self.spec).exists())
def test_missing_prepared_home_is_not_recreated(self):
home = self.storage / self.spec.domain / self.spec.local_part
with self.assertRaises(FileNotFoundError):
ensure_mail_home(home, self.account, create=False)
self.assertFalse(home.exists())
def test_status_reports_absence_without_creating_files(self):
result = mailbox_status(self.spec)
self.assertEqual(
result,
{"address": self.spec.address, "state": "not_installed", "problem": None},
)
self.assertFalse(self.state.exists())
self.assertFalse(self.storage.exists())
self.assertFalse(self.users.exists())
self.commands.assert_not_called()
def test_status_detects_a_live_recipient_without_a_credentials_record(self):
self.postfix_lookup.return_value = "1"
result = mailbox_status(self.spec)
self.assertEqual(result["state"], "needs_attention")
self.assertIn("outside Coulobre's registry", result["problem"])
def test_status_detects_a_pending_home_preparation(self):
self.prepare_home.side_effect = ValueError("Interrupted before home creation.")
with self.assertRaisesRegex(ValueError, "Interrupted"):
apply_mailbox(self.spec)
result = mailbox_status(self.spec)
self.assertEqual(result["state"], "needs_attention")
self.assertIn("installation is incomplete", result["problem"])
def test_status_runs_local_authentication_with_saved_password_on_stdin(self):
path = apply_mailbox(self.spec)
saved = json.loads(path.read_text())
self.postfix_lookup.return_value = "1"
self.commands.reset_mock()
result = mailbox_status(self.spec)
self.assertEqual(result["state"], "configured")
self.commands.assert_called_once_with(
"doveadm",
"auth",
"login",
"-x",
"service=imap",
self.spec.address,
standard_input=saved["password"] + "\n",
)
def test_status_detects_a_recipient_missing_from_the_active_postfix_map(self):
apply_mailbox(self.spec)
self.postfix_lookup.side_effect = ["1", None]
self.commands.reset_mock()
result = mailbox_status(self.spec)
self.assertEqual(result["state"], "needs_attention")
self.assertIn("Postfix did not resolve", result["problem"])
self.commands.assert_not_called()
def test_status_command_reports_auth_failure_without_exposing_credentials(self):
path = apply_mailbox(self.spec)
saved = json.loads(path.read_text())
self.postfix_lookup.return_value = "1"
self.commands.side_effect = ValueError(
saved["password"] + saved["password_hash"]
)
manifest = self.state.parent / "mailbox.json"
manifest.write_text(json.dumps(self.spec.manifest()), encoding="utf-8")
output = self.enterContext(redirect_stdout(StringIO()))
self.assertEqual(main(["status", str(manifest)]), 2)
report = json.loads(output.getvalue())
self.assertEqual(report["state"], "needs_attention")
self.assertEqual(
report["problem"], "Dovecot could not authenticate the saved mailbox login."
)
self.assertNotIn(saved["password"], output.getvalue())
self.assertNotIn(saved["password_hash"], output.getvalue())
class MailboxCommandTests(SimpleTestCase):
def test_password_tool_errors_omit_sensitive_input_and_output(self):
command = ("doveadm", "pw", "-s", "SHA512-CRYPT")
with (
patch(
"coulobre.mail_node_apply.subprocess.run",
return_value=CompletedProcess(
command, 75, "secret hash", "secret password"
),
),
self.assertRaisesRegex(ValueError, r"^doveadm pw failed \(75\)\.$"),
):
run(*command, standard_input="secret password")
def test_postfix_query_error_is_distinct_from_a_missing_key(self):
command = ("postmap", "-q", "support@example.net", "proxy:texthash:/mailboxes")
with patch(
"coulobre.mail_node_apply.subprocess.run",
side_effect=[
CompletedProcess(command, 1, "", ""),
CompletedProcess(command, 1, "", "postmap: fatal: unavailable"),
],
):
self.assertIsNone(run(*command, missing_exit=1, missing_output=""))
with self.assertRaisesRegex(ValueError, "postmap: fatal: unavailable"):
run(*command, missing_exit=1, missing_output="")
+175
View File
@@ -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)
+10
View File
@@ -40,6 +40,16 @@ urlpatterns = [
views.DownloadDnsZoneManifest.as_view(),
name="dns_zone_manifest",
),
path(
"accounts/<int:pk>/mailboxes/new/",
views.MailboxCreate.as_view(),
name="mailbox_create",
),
path(
"mailboxes/<int:pk>/manifest/",
views.DownloadMailboxManifest.as_view(),
name="mailbox_manifest",
),
path(
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
),
+69
View File
@@ -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
+100
View File
@@ -0,0 +1,100 @@
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)
apply = commands.add_parser(
"apply", help="Install a virtual mailbox on the mail node."
)
apply.add_argument("manifest", type=Path)
status = commands.add_parser("status", help="Check an installed virtual mailbox.")
status.add_argument("manifest", type=Path)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
mailbox = MailboxSpec.from_manifest(payload)
if args.command == "apply":
from .mail_node_apply import apply_mailbox
credentials = apply_mailbox(mailbox)
print(f"Applied virtual mailbox {mailbox.address}.")
print(f"Credentials file {credentials}")
elif args.command == "status":
from .mail_node_apply import mailbox_status
report = mailbox_status(mailbox)
print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 2
else:
print(json.dumps({"address": mailbox.address}, indent=2))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0
+414
View File
@@ -0,0 +1,414 @@
import fcntl
import grp
import hashlib
import json
import os
import pwd
import re
import secrets
import stat
import subprocess
import time
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
from .mail_node import MailboxSpec
from .node_files import read_root_file, require_root_directory, write_new_file
STATE_DIRECTORY = Path("/var/lib/coulobre/mail-node")
MAIL_ROOT = Path("/srv/coulobre-mail")
MAIL_USER = "coulobre-vmail"
POSTFIX_DOMAINS = Path("/etc/postfix/coulobre-domains")
POSTFIX_MAILBOXES = Path("/etc/postfix/coulobre-mailboxes")
DOVECOT_USERS = Path("/etc/dovecot/coulobre-users")
LMTP_SOCKET = Path("/var/spool/postfix/private/dovecot-lmtp")
MANAGED_HEADER = "# Managed by Coulobre Panel\n"
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
PASSWORD_HASH = re.compile(
r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}"
)
@dataclass(frozen=True)
class Credentials:
mailbox: MailboxSpec
password: str
password_hash: str
@property
def home(self):
return mailbox_home(self.mailbox)
@property
def path(self):
return credential_path(self.mailbox)
@property
def home_marker(self):
return self.path.with_suffix(".home-ready")
def save(self):
document = {
"mailbox": self.mailbox.manifest(),
"password": self.password,
"password_hash": self.password_hash,
}
write_new_file(self.path, json.dumps(document, indent=2) + "\n", mode=0o600)
def credential_path(mailbox):
key = hashlib.sha256(mailbox.address.encode("ascii")).hexdigest()
return STATE_DIRECTORY / f"{key}.json"
def mailbox_home(mailbox):
return MAIL_ROOT / mailbox.domain / mailbox.local_part
def load_credentials(path):
try:
data = json.loads(read_root_file(path, mode=0o600))
record = Credentials(
MailboxSpec.from_manifest(data["mailbox"]),
data["password"],
data["password_hash"],
)
if (
record.path != path
or not PASSWORD.fullmatch(record.password)
or not PASSWORD_HASH.fullmatch(record.password_hash)
):
raise ValueError
except (KeyError, TypeError, ValueError):
raise ValueError(f"Invalid mailbox credentials record at {path}.") from None
return record
def apply_mailbox(mailbox):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the mail node.")
for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory)
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
ensure_mail_directory(MAIL_ROOT)
with locked_state(create=True) as directory:
return install_mailbox(mailbox, directory)
@contextmanager
def locked_state(*, create):
try:
require_root_directory(STATE_DIRECTORY, create_mode=0o700 if create else None)
directory = os.open(
STATE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
)
except FileNotFoundError:
if create:
raise
yield None
return
try:
fcntl.flock(directory, fcntl.LOCK_EX if create else fcntl.LOCK_SH)
yield directory
finally:
os.close(directory)
def mailbox_status(mailbox):
if os.geteuid() != 0:
raise ValueError("Run status as root on the mail node.")
try:
with locked_state(create=False):
state = check_mailbox(mailbox)
problem = None
except (OSError, ValueError) as error:
state = "needs_attention"
problem = str(error)
return {"address": mailbox.address, "state": state, "problem": problem}
def check_mailbox(mailbox):
for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory)
account, auth_group = check_services(mailbox)
path = credential_path(mailbox)
home = mailbox_home(mailbox)
if not os.path.lexists(path):
if (
os.path.lexists(path.with_suffix(".home-ready"))
or os.path.lexists(home)
or dovecot_home(mailbox) is not None
or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) is not None
):
raise ValueError("The mailbox has resources outside Coulobre's registry.")
return "not_installed"
record = load_credentials(path)
if not home_is_prepared(record):
raise ValueError("The mailbox installation is incomplete.")
for directory in (MAIL_ROOT, home.parent):
ensure_mail_directory(directory, create=False)
ensure_mail_home(home, account, create=False)
for table, (mode, group, rows) in lookup_tables(
(record,), account, auth_group
).items():
contents = read_lookup_table(table, mode, group)
if not contents.startswith(MANAGED_HEADER) or not rows.issubset(
contents.removeprefix(MANAGED_HEADER).splitlines()
):
raise ValueError(f"The managed mailbox entry is missing from {table}.")
if (
postfix_lookup(mailbox.domain, POSTFIX_DOMAINS) != "1"
or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) != "1"
):
raise ValueError("Postfix did not resolve the managed domain and recipient.")
if dovecot_home(mailbox) != str(home):
raise ValueError("Dovecot did not resolve the managed mailbox home.")
try:
run(
"doveadm",
"auth",
"login",
"-x",
"service=imap",
mailbox.address,
standard_input=f"{record.password}\n",
)
except (OSError, ValueError):
raise ValueError(
"Dovecot could not authenticate the saved mailbox login."
) from None
return "configured"
def install_mailbox(mailbox, state_directory):
account, auth_group = check_services(mailbox)
records = [
load_credentials(path) for path in sorted(STATE_DIRECTORY.glob("*.json"))
]
active = next((record for record in records if record.mailbox == mailbox), None)
prepared = [record for record in records if home_is_prepared(record)]
previous = lookup_tables(prepared, account, auth_group)
ready = {path: check_lookup_table(path, table) for path, table in previous.items()}
home = mailbox_home(mailbox)
ensure_mail_directory(home.parent)
if active is None:
if os.path.lexists(home) or dovecot_home(mailbox) is not None:
raise ValueError("The mailbox already exists outside Coulobre's registry.")
password = secrets.token_urlsafe(32)
password_hash = run(
"doveadm",
"pw",
"-s",
"SHA512-CRYPT",
standard_input=f"{password}\n{password}\n",
)
if not PASSWORD_HASH.fullmatch(password_hash):
raise ValueError("Dovecot did not return the expected password hash.")
active = Credentials(mailbox, password, password_hash)
active.save()
os.fsync(state_directory)
if active not in prepared:
ensure_mail_home(home, account, create=True)
write_new_file(active.home_marker, f"{mailbox.address}\n", mode=0o600)
os.fsync(state_directory)
prepared.append(active)
else:
ensure_mail_home(home, account, create=False)
tables = lookup_tables(prepared, account, auth_group)
publish_table(DOVECOT_USERS, tables[DOVECOT_USERS], ready[DOVECOT_USERS])
wait_for_dovecot_home(mailbox, home)
for path in (POSTFIX_MAILBOXES, POSTFIX_DOMAINS):
publish_table(path, tables[path], ready[path])
run("postfix", "reload")
return active.path
def lookup_tables(records, account, auth_group):
return {
DOVECOT_USERS: (
0o640,
auth_group,
{
f"{record.mailbox.address}:{record.password_hash}:"
f"{account.pw_uid}:{account.pw_gid}::{record.home}::"
for record in records
},
),
POSTFIX_MAILBOXES: (
0o644,
None,
{f"{record.mailbox.address}\t1" for record in records},
),
POSTFIX_DOMAINS: (
0o644,
None,
{f"{record.mailbox.domain}\t1" for record in records},
),
}
def read_lookup_table(path, mode, group):
if not os.path.lexists(path):
return ""
contents = read_root_file(path, mode=mode)
if group is not None and path.lstat().st_gid != group:
raise ValueError(f"Expected ownership by the Dovecot auth group for {path}.")
return contents
def check_lookup_table(path, table):
mode, group, rows = table
contents = read_lookup_table(path, mode, group)
if contents and (
not contents.startswith(MANAGED_HEADER)
or set(contents.removeprefix(MANAGED_HEADER).splitlines()) - rows
):
raise ValueError(f"Existing entries in {path} differ from Coulobre's registry.")
return contents
def publish_table(path, table, previous):
mode, group, rows = table
contents = MANAGED_HEADER + "".join(f"{row}\n" for row in sorted(rows))
if contents == previous:
return
with TemporaryDirectory(dir=path.parent) as scratch:
staged = Path(scratch) / "lookup"
write_new_file(staged, contents, mode=mode, group=group)
os.replace(staged, path)
def home_is_prepared(record):
if not os.path.lexists(record.home_marker):
return False
if read_root_file(record.home_marker, mode=0o600) != f"{record.mailbox.address}\n":
raise ValueError(
"The mailbox home marker conflicts with its credentials record."
)
return True
def ensure_mail_directory(path, *, create=True):
require_root_directory(path.parent)
if create:
try:
path.mkdir(mode=0o755)
except FileExistsError:
pass
else:
path.chmod(0o755)
require_root_directory(path)
if not path.stat().st_mode & stat.S_IXOTH:
raise ValueError(f"Allow the mail service to traverse {path}.")
def ensure_mail_home(home, account, *, create):
if create and not os.path.lexists(home):
home.mkdir(mode=0o700)
info = home.lstat()
if not stat.S_ISDIR(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o700:
raise ValueError(f"Expected a private mailbox directory at {home}.")
if create and info.st_uid == 0 and not any(home.iterdir()):
os.chown(home, account.pw_uid, account.pw_gid, follow_symlinks=False)
elif (info.st_uid, info.st_gid) != (account.pw_uid, account.pw_gid):
raise ValueError(f"Unexpected ownership for the mailbox directory at {home}.")
def check_services(mailbox):
try:
account = pwd.getpwnam(MAIL_USER)
except KeyError:
raise ValueError(
f"Create the {MAIL_USER} system account on the mail node."
) from None
if (
not account.pw_uid
or not account.pw_gid
or account.pw_dir != str(MAIL_ROOT)
or account.pw_shell != "/usr/sbin/nologin"
):
raise ValueError(
f"Unexpected configuration for the {MAIL_USER} system account."
)
settings = {
"virtual_mailbox_domains": f"proxy:texthash:{POSTFIX_DOMAINS}",
"virtual_mailbox_maps": f"proxy:texthash:{POSTFIX_MAILBOXES}",
"virtual_transport": "lmtp:unix:private/dovecot-lmtp",
"smtpd_reject_unlisted_recipient": "yes",
}
for name, expected in settings.items():
if run("postconf", "-hx", name) != expected:
raise ValueError(f"Configure Postfix {name} for Coulobre mailboxes.")
local_domains = run("postconf", "-hx", "mydestination")
if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()):
raise ValueError("The requested mail domain is a local Postfix destination.")
if run("doveconf", "-h", "mail_location") != "maildir:~/Maildir":
raise ValueError("Configure Dovecot mail_location for the managed Maildir.")
first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_valid_uid"))
if account.pw_uid < first_uid or (last_uid and account.pw_uid > last_uid):
raise ValueError(f"Allow the {MAIL_USER} UID in Dovecot's valid UID range.")
if not LMTP_SOCKET.is_socket():
raise ValueError(f"Dovecot is missing its LMTP socket at {LMTP_SOCKET}.")
run("postfix", "status")
try:
auth_group = grp.getgrnam("dovecot").gr_gid
except KeyError:
raise ValueError("The Dovecot auth group is missing.") from None
if not auth_group:
raise ValueError("The Dovecot auth group must be unprivileged.")
return account, auth_group
def dovecot_home(mailbox):
return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67)
def postfix_lookup(key, path):
return run(
"postmap",
"-q",
key,
f"proxy:texthash:{path}",
missing_exit=1,
missing_output="",
)
def wait_for_dovecot_home(mailbox, home):
# Dovecot checks for passwd-file changes at most once per second.
for _ in range(10):
resolved = dovecot_home(mailbox)
if resolved == str(home):
return
if resolved is not None:
break
time.sleep(0.2)
raise ValueError("Dovecot did not resolve the managed mailbox home.")
def run(*command, standard_input=None, missing_exit=None, missing_output=None):
name = " ".join(command[:2])
try:
result = subprocess.run(
command,
input=standard_input,
capture_output=True,
text=True,
timeout=20,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"},
)
except subprocess.TimeoutExpired:
raise ValueError(f"{name} timed out.") from None
if result.returncode:
message = result.stderr.strip() or result.stdout.strip()
if result.returncode == missing_exit and missing_output in (None, message):
return None
details = message if standard_input is None else ""
raise ValueError(f"{name} failed ({result.returncode}). {details}".rstrip())
return result.stdout.strip()
+3 -1
View File
@@ -26,10 +26,12 @@ def read_root_file(path, *, mode=None):
return path.read_text(encoding="utf-8")
def write_new_file(path, content, *, mode):
def write_new_file(path, content, *, mode, group=None):
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged:
staged.write(content)
staged.flush()
if group is not None:
os.fchown(staged.fileno(), -1, group)
os.fchmod(staged.fileno(), mode)
os.fsync(staged.fileno())
os.link(staged.name, path)