Add mailbox requests and deployment manifests for hosting accounts

This commit is contained in:
parkel committed 2026-11-19 23:24:40 +01:00
1 parent 4e05e63b15
commit 4bd7a90580
10 files changed
+519

No files matched your search

@@ -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 %}
+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
+81
View File
@@ -0,0 +1,81 @@
import argparse
import json
import re
from dataclasses import dataclass
from pathlib import Path
from .domain_names import canonical_domain
MANIFEST_VERSION = 1
MANIFEST_KIND = "virtual_mailbox"
LOCAL_PART_MAX_LENGTH = 64
INVALID_LOCAL_PART = (
"Use 1 to 64 letters, digits, dots, underscores, or hyphens. "
"Start and end with a letter or digit and avoid consecutive dots."
)
@dataclass(frozen=True)
class MailboxSpec:
domain: str
local_part: str
def __post_init__(self):
if not isinstance(self.domain, str):
raise ValueError("Enter a valid mail domain.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
if not isinstance(self.local_part, str) or not self.local_part.isascii():
raise ValueError(INVALID_LOCAL_PART)
local_part = self.local_part.lower()
if (
len(local_part) > LOCAL_PART_MAX_LENGTH
or not re.fullmatch(r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?", local_part)
or ".." in local_part
):
raise ValueError(INVALID_LOCAL_PART)
object.__setattr__(self, "local_part", local_part)
if len(self.address) > 254:
raise ValueError("The full mailbox address must be at most 254 characters.")
@property
def address(self):
return f"{self.local_part}@{self.domain}"
def manifest(self):
return {
"version": MANIFEST_VERSION,
"kind": MANIFEST_KIND,
"domain": self.domain,
"local_part": self.local_part,
}
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"version",
"kind",
"domain",
"local_part",
}:
raise ValueError("Expected a virtual mailbox manifest.")
if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION:
raise ValueError("Unsupported mailbox manifest version.")
if data["kind"] != MANIFEST_KIND:
raise ValueError("Expected a virtual mailbox manifest.")
return cls(data["domain"], data["local_part"])
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-mail-node")
commands = parser.add_subparsers(dest="command", required=True)
inspect = commands.add_parser("inspect", help="Inspect a virtual mailbox manifest.")
inspect.add_argument("manifest", type=Path)
args = parser.parse_args(argv)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
mailbox = MailboxSpec.from_manifest(payload)
print(json.dumps({"address": mailbox.address}, indent=2))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0