From 3c35a061d85c798c6b439d2b24b52a26a7945ef4 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Wed, 2 Dec 2026 13:12:25 +0100 Subject: [PATCH] Route mail domain aliases to the primary domain --- deploy/panel_installer/roles.py | 9 + docs/deployment.md | 27 +++ src/coulobre/hosting/account_retirement.py | 6 + src/coulobre/hosting/domain_services.py | 14 ++ .../hosting/mail_domain_alias_views.py | 110 ++++++++++ src/coulobre/hosting/mail_domain_aliases.py | 194 ++++++++++++++++++ .../migrations/0090_mail_domain_alias.py | 61 ++++++ src/coulobre/hosting/models.py | 20 ++ src/coulobre/hosting/reseller_accounts.py | 8 + src/coulobre/hosting/resource_requests.py | 6 + src/coulobre/hosting/tasks.py | 27 +++ .../templates/hosting/account_detail.html | 8 + .../templates/hosting/domain_workspace.html | 3 + .../hosting/mail_domain_alias_form.html | 31 +++ .../hosting/test_mail_domain_alias.py | 160 +++++++++++++++ src/coulobre/hosting/urls.py | 6 + src/coulobre/hosting/views.py | 9 + src/coulobre/hosting/website_aliases.py | 4 + src/coulobre/mail_domain_alias.py | 46 +++++ src/coulobre/mail_node.py | 13 ++ src/coulobre/mail_node_routing.py | 141 ++++++++++++- src/coulobre/receiver_scope.py | 11 + src/coulobre/test_receiver_scope.py | 21 ++ 23 files changed, 929 insertions(+), 6 deletions(-) create mode 100644 src/coulobre/hosting/mail_domain_alias_views.py create mode 100644 src/coulobre/hosting/mail_domain_aliases.py create mode 100644 src/coulobre/hosting/migrations/0090_mail_domain_alias.py create mode 100644 src/coulobre/hosting/templates/hosting/mail_domain_alias_form.html create mode 100644 src/coulobre/hosting/test_mail_domain_alias.py create mode 100644 src/coulobre/mail_domain_alias.py diff --git a/deploy/panel_installer/roles.py b/deploy/panel_installer/roles.py index 110566a..9ded48a 100644 --- a/deploy/panel_installer/roles.py +++ b/deploy/panel_installer/roles.py @@ -125,6 +125,11 @@ def configure_mail(target, modern): dovecot = engine.group("dovecot") ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644) ensure_table(Path("/etc/postfix/coulobre-mailboxes"), mode=0o644) + aliases = Path("/etc/postfix/coulobre-aliases") + if not os.path.lexists(aliases): + engine.put_file(aliases, "# Managed by Coulobre Panel\n", mode=0o644) + else: + engine.root_file(aliases, 0o644) ensure_table( Path("/etc/dovecot/coulobre-users"), mode=0o640, group=dovecot.gr_gid ) @@ -139,6 +144,8 @@ def configure_mail(target, modern): "virtual_mailbox_maps": ( "proxy:texthash:/etc/postfix/coulobre-mailboxes" ), + "virtual_alias_maps": f"proxy:texthash:{aliases}", + "virtual_alias_domains": f"proxy:texthash:{aliases}", "virtual_transport": "lmtp:unix:private/dovecot-lmtp", "smtpd_reject_unlisted_recipient": "yes", "smtpd_tls_security_level": "may", @@ -149,6 +156,8 @@ def configure_mail(target, modern): managed_maps = ( "virtual_mailbox_domains", "virtual_mailbox_maps", + "virtual_alias_maps", + "virtual_alias_domains", "virtual_transport", ) for field in managed_maps: diff --git a/docs/deployment.md b/docs/deployment.md index 9d1013e..77b3133 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2627,6 +2627,33 @@ delivery status notification and the mail node's logs. Verify forwarding to external providers with real test mail because their SPF and DMARC policies can affect delivery. [Postfix virtual aliases](https://www.postfix.org/virtual.5.html) +### Receive mail for another domain without separate mailboxes + +Open the alias domain under **Domains** and choose **Manage mail alias**. +An operator can also use **Mail domain aliases** on the hosting account's +**Email** tab. Select a primary domain with a configured mailbox. The two +domains can be on separate hosting accounts on the same panel if they +belong to the same customer. On a shared mail node, the panel's receiver +key must cover both domains before adding or removing the alias. + +Addresses at the alias domain follow the primary domain's matching mailbox +or forwarder. Unknown addresses are rejected unless the primary domain +has a catch-all. The alias does not add a mailbox, login, sending identity, +or additional quota. Coulobre adds the MX record to a managed DNS zone if +there is no conflicting mail route. For external DNS, copy the MX record +from the panel after the alias is active. Review existing routes before +switching providers and remove manually added MX records before removing +an alias. + +New installer-managed mail nodes configure the Postfix maps for aliases. +Existing installations can reuse the managed map above. For domain aliases, +set both `virtual_alias_maps` and `virtual_alias_domains` to +`proxy:texthash:/etc/postfix/coulobre-aliases`. The latter may already +resolve to that map through Postfix's default. Check the effective settings +with `postconf -hx` and validate and reload Postfix after changing them. +Domain aliases are not enabled against custom alias tables, so Coulobre +cannot take over an address owned by an existing router. + ### Enable scheduled automatic replies Install the distribution's `dovecot-sieve` package. Add the settings in diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index a40ed94..8855e2a 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -214,6 +214,8 @@ def record_action(retirement, actor, action, *, failures=None): @transaction.atomic def request_retirement(account_id, policy, confirmation, digest, actor): + from .mail_domain_aliases import account_aliases + account = lock_hosting_account(account_id, customer_id=None) retirement = getattr(account, "retirement", None) if retirement is not None and retirement.policy == Policy.RELEASE: @@ -237,6 +239,10 @@ def request_retirement(account_id, policy, confirmation, digest, actor): raise ValidationError( "Remove folder SFTP logins before retiring the hosting account." ) + if account_aliases(account).exists(): + raise ValidationError( + "Remove mail domain aliases before retiring the hosting account." + ) if account.mailbox_removals.filter(mailbox__isnull=False).exists(): raise ValidationError( "Finish the mailbox removal before retiring the account." diff --git a/src/coulobre/hosting/domain_services.py b/src/coulobre/hosting/domain_services.py index b6dcf97..fcd004a 100644 --- a/src/coulobre/hosting/domain_services.py +++ b/src/coulobre/hosting/domain_services.py @@ -80,11 +80,22 @@ def allowed_domains(account): @transaction.atomic def save_domain_policy(account_id, domain, customer_id, choices): + from .mail_domain_aliases import account_aliases + account = lock_hosting_account(account_id, customer_id=customer_id) require_open_account(account) if domain not in allowed_domains(account): raise Http404 previous = policy_for(account, domain) + if ( + not choices["mail_managed"] + and account_aliases(account) + .filter(primary__account=account, primary__domain=domain) + .exists() + ): + raise ValidationError( + "Remove mail domain aliases before switching providers." + ) if ( previous.mail_managed and not choices["mail_managed"] @@ -221,6 +232,7 @@ def domain_workspace(request, pk, page): "forwarders": "Forwarders", "replies": "Automatic replies", } + from .mail_domain_alias_views import may_manage_aliases from .mail_policies import mail_policy_available from .mailbox_removal import can_remove_mailbox from .roundcube import roundcube_available @@ -241,6 +253,8 @@ def domain_workspace(request, pk, page): "domain": domain, "form": form, "policy": policy, + "can_manage_mail_alias": may_manage_aliases(request) + and account.website_domains.filter(domain=domain).exists(), "zone": zone, "records": zone_record_rows(zone.spec) if zone else (), "external_website_records": website_records( diff --git a/src/coulobre/hosting/mail_domain_alias_views.py b/src/coulobre/hosting/mail_domain_alias_views.py new file mode 100644 index 0000000..5718db8 --- /dev/null +++ b/src/coulobre/hosting/mail_domain_alias_views.py @@ -0,0 +1,110 @@ +from django import forms +from django.conf import settings +from django.core.exceptions import PermissionDenied, ValidationError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_http_methods + +from .access import can_manage_hosting, customer_for_user +from .mail_domain_aliases import ( + aliases_available, + queue_domain_alias, + remove_domain_alias, +) +from .models import HostingMailDomain, WebsiteDomain + +PERMISSIONS = ( + "hosting.view_hostingaccount", + "hosting.change_hostingmaildomain", +) + + +def may_manage_aliases(request): + return ( + aliases_available() + and not getattr(request, "impersonation", None) + and can_manage_hosting(request.user, PERMISSIONS) + ) + + +class MailDomainAliasForm(forms.Form): + primary = forms.ModelChoiceField( + label="Primary mail domain", queryset=HostingMailDomain.objects.none() + ) + + +@never_cache +@require_http_methods(("GET", "HEAD", "POST")) +def mail_domain_alias(request, pk, domain): + if not aliases_available(): + raise Http404 + if not may_manage_aliases(request): + raise PermissionDenied + customer = customer_for_user(request.user) + claims = WebsiteDomain.objects.select_related("account") + if customer is not None: + claims = claims.filter(account__customer=customer) + reservation = get_object_or_404( + claims, account=pk, domain=domain, account__retired_at__isnull=True + ) + targets = HostingMailDomain.objects.filter( + account__retired_at__isnull=True, + mailboxes__provisioning__finished_at__isnull=False, + mailboxes__provisioning__problem="", + mailboxes__removal__isnull=True, + ).exclude(domain=domain) + if reservation.account.customer_id: + targets = targets.filter( + account__customer_id=reservation.account.customer_id + ) + else: + targets = targets.filter(account=reservation.account) + job = getattr(reservation, "mail_alias", None) + data = request.POST if request.method == "POST" else None + form = MailDomainAliasForm( + data, initial={"primary": job.primary_id} if job else {} + ) + form.fields["primary"].queryset = targets.order_by("domain").distinct() + problem = "" + if request.method == "POST": + try: + action = request.POST.get("action") + if action == "remove" and job is not None: + remove_domain_alias(job, customer) + elif action == "save": + if form.is_valid(): + queue_domain_alias( + reservation, form.cleaned_data["primary"], customer + ) + else: + action = None + else: + raise Http404 + except ValidationError as error: + problem = " ".join(error.messages) + else: + if action is not None: + return redirect(request.path) + backlink = ( + reverse( + "panel:domain_workspace", + args=[pk, "domains"], + query={"domain": domain}, + ) + if customer + else reservation.account.get_absolute_url() + ) + return render( + request, + "hosting/mail_domain_alias_form.html", + { + "domain": domain, + "job": job, + "form": form, + "problem": problem, + "backlink": backlink, + "exchange": settings.MAIL_MX_HOST, + }, + ) diff --git a/src/coulobre/hosting/mail_domain_aliases.py b/src/coulobre/hosting/mail_domain_aliases.py new file mode 100644 index 0000000..4e9f3f2 --- /dev/null +++ b/src/coulobre/hosting/mail_domain_aliases.py @@ -0,0 +1,194 @@ +from dataclasses import replace + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.db import transaction +from django.db.models import Q + +from coulobre.dns_node import MAX_SOA_SERIAL, MxRecord + +from .dns_publication import queue_zone_snapshot +from .domain_policies import policy_for, require_managed +from .mail_dns_setup import closest_zone +from .models import ( + HostingAccount, + HostingDnsZone, + HostingMailDomain, + MailDomainAlias, + WebsiteAlias, + WebsiteDomain, +) +from .node_client import apply_on_local_node +from .resource_requests import require_active_services + + +def aliases_available(): + return settings.LOCAL_MAILBOX_PROVISIONING and bool(settings.MAIL_MX_HOST) + + +def account_aliases(account): + return MailDomainAlias.objects.filter( + Q(reservation__account=account) | Q(primary__account=account) + ) + + +def owned_with(source, target): + return source.pk == target.pk or ( + source.customer_id is not None + and source.customer_id == target.customer_id + ) + + +def mesh_accounts(source_id, target_id): + accounts = { + account.pk: account + for account in HostingAccount.objects.select_for_update() + .filter(pk__in=(source_id, target_id)) + .order_by("pk") + } + return accounts[source_id], accounts[target_id] + + +def validate_alias(reservation, primary, source, target): + require_active_services(source) + require_active_services(target) + if not owned_with(source, target): + raise ValidationError("Both domains must belong to the same customer.") + if reservation.domain == primary.domain: + raise ValidationError("Choose a different primary mail domain.") + if WebsiteAlias.objects.filter( + reservation=reservation, operation=WebsiteAlias.Operation.REMOVE + ).exists(): + raise ValidationError("This domain is being removed.") + require_managed(target, primary.domain, "mail_managed") + if HostingMailDomain.objects.filter(domain=reservation.domain).exists(): + raise ValidationError( + "The alias already has an independent mail domain." + ) + if not primary.mailboxes.filter( + provisioning__finished_at__isnull=False, + provisioning__problem="", + removal__isnull=True, + ).exists(): + raise ValidationError("Provision a primary mailbox first.") + + +@transaction.atomic +def queue_domain_alias(reservation, primary, customer): + source, target = mesh_accounts(reservation.account_id, primary.account_id) + if customer is not None and source.customer_id != customer.pk: + raise ValidationError("This domain is not assigned to you.") + reservation = WebsiteDomain.objects.select_for_update().get( + pk=reservation.pk + ) + if not aliases_available(): + raise ValidationError("Configure managed email and its MX host first.") + validate_alias(reservation, primary, source, target) + dns_change(source, reservation.domain, settings.MAIL_MX_HOST) + job = MailDomainAlias.objects.filter(reservation=reservation).first() + if job is None: + return MailDomainAlias.objects.create( + reservation=reservation, primary=primary + ) + if job.primary_id != primary.pk or job.remove or not job.problem: + raise ValidationError("Remove the current alias before changing it.") + MailDomainAlias.objects.requeue(MailDomainAlias.objects.filter(pk=job.pk)) + return job + + +@transaction.atomic +def remove_domain_alias(job, customer): + source, _ = mesh_accounts( + job.reservation.account_id, job.primary.account_id + ) + if customer is not None and source.customer_id != customer.pk: + raise ValidationError("This domain is not assigned to you.") + if not MailDomainAlias.objects.requeue( + MailDomainAlias.objects.filter(pk=job.pk), remove=True + ): + raise ValidationError("Wait for the current change to finish.") + + +def dns_change(account, domain, exchange, *, remove=False): + if not settings.LOCAL_DNS_PUBLISHING: + return None, None + zone = closest_zone(HostingDnsZone.objects.all(), domain) + if ( + zone is None + or zone.account_id != account.pk + or not policy_for(account, zone.domain).dns_managed + ): + return None, None + zone = HostingDnsZone.objects.select_for_update().get(pk=zone.pk) + spec = zone.spec + mx = MxRecord(domain, 10, exchange) + existing = tuple( + record for record in spec.mx_records if record.name == domain + ) + if remove: + if mx not in existing: + return None, None + records = tuple(item for item in spec.mx_records if item != mx) + else: + if existing: + if any(record.exchange != mx.exchange for record in existing): + raise ValidationError( + "Review the existing MX targets in the DNS editor first." + ) + return None, None + records = (*spec.mx_records, mx) + publication = getattr(zone, "publication", None) + if publication and ( + publication.finished_at is None or publication.serial != zone.serial + ): + raise ValidationError("Finish the current DNS publication first.") + revision = replace( + spec, + serial=(spec.serial + 1) % (MAX_SOA_SERIAL + 1), + mx_records=records, + ) + return zone, revision + + +@transaction.atomic +def apply_domain_alias(job): + source, target = mesh_accounts( + job.reservation.account_id, job.primary.account_id + ) + try: + if job.remove: + change = ( + dns_change( + source, job.spec.domain, job.mx_exchange, remove=True + ) + if job.mx_exchange + else (None, None) + ) + else: + validate_alias(job.reservation, job.primary, source, target) + change = dns_change(source, job.spec.domain, settings.MAIL_MX_HOST) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + apply_on_local_node( + job.spec, + "/run/coulobre-mail-apply.sock", + "mail node", + "mail domain alias", + identity=job.spec.identity(), + ) + zone, revision = change + if zone is not None: + zone.serial = revision.serial + zone.mx_records = revision.manifest().get("mx_records", []) + zone.save(update_fields=["serial", "mx_records"]) + queue_zone_snapshot(zone) + return { + "active": not job.remove, + "mx_exchange": ( + "" + if job.remove + else settings.MAIL_MX_HOST + if zone + else job.mx_exchange + ), + } diff --git a/src/coulobre/hosting/migrations/0090_mail_domain_alias.py b/src/coulobre/hosting/migrations/0090_mail_domain_alias.py new file mode 100644 index 0000000..34a2b78 --- /dev/null +++ b/src/coulobre/hosting/migrations/0090_mail_domain_alias.py @@ -0,0 +1,61 @@ +# Generated by Django 5.2.19 on 2026-12-02 12:08 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0089_wordpress_update_recovery"), + ] + + operations = [ + migrations.CreateModel( + name="MailDomainAlias", + 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)), + ("remove", models.BooleanField(default=False)), + ("active", models.BooleanField(default=False)), + ("mx_exchange", models.CharField(blank=True, max_length=253)), + ( + "primary", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="aliases", + to="hosting.hostingmaildomain", + ), + ), + ( + "reservation", + models.OneToOneField( + on_delete=django.db.models.deletion.PROTECT, + related_name="mail_alias", + to="hosting.websitedomain", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index ec32434..51d3088 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1667,6 +1667,26 @@ class MailPolicyPublication(ProvisioningJob): abstract = True +class MailDomainAlias(ProvisioningJob): + reservation = models.OneToOneField( + WebsiteDomain, on_delete=models.PROTECT, related_name="mail_alias" + ) + primary = models.ForeignKey( + HostingMailDomain, on_delete=models.PROTECT, related_name="aliases" + ) + remove = models.BooleanField(default=False) + active = models.BooleanField(default=False) + mx_exchange = models.CharField(max_length=253, blank=True) + + @property + def spec(self): + from coulobre.mail_domain_alias import MailDomainAliasRequest + + return MailDomainAliasRequest( + self.reservation.domain, self.primary.domain, self.remove + ) + + class MailRoutingPublication(MailPolicyPublication): mail_domain = models.OneToOneField( HostingMailDomain, on_delete=models.CASCADE, related_name="routing" diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index b9e6a66..54ff658 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -165,6 +165,14 @@ def save_operator_account(account, actor, *, changed_fields=None): require_open_account(previous) if "primary_domain" in changed_fields: require_active_services(previous) + if {"customer", "primary_domain"}.intersection(changed_fields): + from .mail_domain_aliases import account_aliases + + if account_aliases(previous).exists(): + raise ValidationError( + "Remove mail domain aliases before changing the " + "customer or primary domain." + ) if {"customer", "primary_domain"}.intersection( changed_fields ) and previous.folder_sftp_logins.exists(): diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index a875491..a75e63a 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -109,6 +109,12 @@ def create_mailbox_request( "This mail domain is outside the hosting account." ) require_managed(account, domain, "mail_managed") + if account.website_domains.filter( + domain=domain, mail_alias__isnull=False + ).exists(): + raise ValidationError( + "Add mailboxes on the primary mail domain, not its alias." + ) try: spec = MailboxSpec(domain, local_part) except ValueError as error: diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 2fafab9..a5c7850 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -36,6 +36,7 @@ from .backup_restores import ( from .backup_retention import plan_backup_expirations from .independent_websites import active_websites, apply_website_operation from .mail_dns_setup import sync_mail_dns +from .mail_domain_aliases import aliases_available, apply_domain_alias from .mail_policies import apply_policy, mail_policy_available from .mailbox_removal import apply_removal from .models import ( @@ -55,6 +56,7 @@ from .models import ( MailboxProvisioning, MailboxRemoval, MailDeliverySearch, + MailDomainAlias, MailFilterCheck, MailRoutingPublication, MailVacationPublication, @@ -359,6 +361,12 @@ def dispatch_mailbox_provisioning(): publish_mail_routing, MAILBOX_PROVISIONING_QUEUE, ) + if aliases_available(): + dispatch_provisioning_jobs( + MailDomainAlias, + publish_mail_domain_alias, + MAILBOX_PROVISIONING_QUEUE, + ) if mail_policy_available("vacation"): dispatch_provisioning_jobs( MailVacationPublication, @@ -882,6 +890,25 @@ def apply_mail_routing_job(job): return apply_policy(job, job.mail_domain) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def publish_mail_domain_alias(job_id): + if aliases_available(): + jobs = MailDomainAlias.objects.select_related("reservation", "primary") + run_provisioning_job( + jobs, + job_id, + apply_domain_alias, + "Could not reach the mail node. Check its connection and retry.", + ) + jobs.filter( + pk=job_id, + remove=True, + active=False, + finished_at__isnull=False, + problem="", + ).delete() + + @shared_task(acks_late=True, reject_on_worker_lost=True) def publish_mail_vacation(job_id): if mail_policy_available("vacation"): diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 6f433c6..a14ee88 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -278,6 +278,14 @@ {% endif %} {% if is_tenant or perms.hosting.view_hostingmailbox %}
+ {% if mail_alias_domains %} +
+

Mail domain aliases

+
    {% for domain in mail_alias_domains %} +
  • {{ domain.domain }}{% if domain.mail_alias %} → {{ domain.mail_alias.primary.domain }}{% endif %}
  • + {% endfor %}
+
+ {% endif %} {% if mail_domains %}
diff --git a/src/coulobre/hosting/templates/hosting/domain_workspace.html b/src/coulobre/hosting/templates/hosting/domain_workspace.html index 6fef4bf..5fa57a5 100644 --- a/src/coulobre/hosting/templates/hosting/domain_workspace.html +++ b/src/coulobre/hosting/templates/hosting/domain_workspace.html @@ -12,6 +12,9 @@ {% endblock %} {% block page_content %} {% if page == 'domains' %} + {% if can_manage_mail_alias %} +

Mail domain alias

Manage mail alias
+ {% endif %}
{% csrf_token %}{{ form.as_div }}
diff --git a/src/coulobre/hosting/templates/hosting/mail_domain_alias_form.html b/src/coulobre/hosting/templates/hosting/mail_domain_alias_form.html new file mode 100644 index 0000000..c9bdaf1 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mail_domain_alias_form.html @@ -0,0 +1,31 @@ +{% extends "hosting/workspace_page.html" %} +{% load static %} +{% block title %}Mail domain alias · Coulobre Panel{% endblock %} +{% block page_title %}Mail domain alias{% endblock %} +{% block page_metadata %}

{{ domain }}

{% endblock %} +{% block page_actions %}Back to hosting{% endblock %} +{% block page_content %} +
+

Deliver mail for this domain using the mailboxes, forwarders and catch-all of its primary mail domain. This does not add a mailbox or let you send from the alias.

+ {% if job %} +

Primary mail domain {{ job.primary.domain }}

+

{% if job.remove %}Removal{% else %}Setup{% endif %} {{ job.state }}.

+ {% if job.problem %}{% endif %} + {% endif %} + {% if problem %}{% endif %} + {% if not job or job.problem and not job.remove %} +
{% csrf_token %}{{ form.as_div }}
+ {% endif %} + {% if job.finished_at %} +
{% csrf_token %}
+ {% endif %} + {% if job.active %} +

Incoming mail DNS

+

For external DNS, review existing mail delivery before setting this record at your DNS provider. Remove it there if you stop using the alias.

+ + +

+ + {% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/test_mail_domain_alias.py b/src/coulobre/hosting/test_mail_domain_alias.py new file mode 100644 index 0000000..f438f13 --- /dev/null +++ b/src/coulobre/hosting/test_mail_domain_alias.py @@ -0,0 +1,160 @@ +from dataclasses import asdict +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.dns_node import MxRecord +from coulobre.mail_domain_alias import MailDomainAliasRequest +from coulobre.mail_node_routing import publish_routes +from coulobre.mail_policy import MailRouting + +from .models import ( + Customer, + HostingAccount, + HostingDnsZone, + HostingMailbox, + HostingMailDomain, + MailboxProvisioning, + MailDomainAlias, +) +from .tasks import publish_mail_domain_alias + + +class RoutingTableTests(SimpleTestCase): + def test_primary_rules_define_exact_alias_recipients(self): + primary = "primary.example.test" + alias = "alias.example.test" + mailbox = f"info@{primary}" + forwarding = f"sales@{primary}" + with patch("coulobre.mail_node_apply.publish_table") as publish: + for catchall in ("", mailbox): + with self.subTest(catchall=catchall): + route = MailRouting( + primary, {"sales": [mailbox]}, catchall + ) + publish_routes( + {primary: route}, + {mailbox}, + "", + aliases={alias: primary}, + ) + rows = publish.call_args.args[1][2] + expected = { + f"{alias} OK", + f"info@{alias} {mailbox}", + f"sales@{alias} {forwarding}", + } + if catchall: + expected.add(f"@{alias} {mailbox}") + self.assertEqual( + {row for row in rows if alias in row}, expected + ) + + +@override_settings( + LOCAL_MAILBOX_PROVISIONING=True, + LOCAL_DNS_PUBLISHING=True, + MAIL_MX_HOST="mx.example.test", +) +class MailDomainAliasTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.user = users.create_user("customer") + cls.customer = Customer.objects.create(user=cls.user) + cls.source = HostingAccount.objects.create( + name="Alias", + primary_domain="alias.example.test", + customer=cls.customer, + ) + cls.owner = HostingAccount.objects.create( + name="Primary", + primary_domain="primary.example.test", + customer=cls.customer, + ) + cls.primary = HostingMailDomain.objects.create( + account=cls.owner, domain=cls.owner.primary_domain + ) + mailbox = HostingMailbox.objects.create( + mail_domain=cls.primary, local_part="info" + ) + MailboxProvisioning.objects.create( + mailbox=mailbox, finished_at=timezone.now() + ) + + def setUp(self): + self.client.force_login(self.user) + self.url = reverse( + "panel:mail_domain_alias", + args=(self.source.pk, self.source.primary_domain), + ) + + def zone(self, mx_records=()): + return HostingDnsZone.objects.create( + account=self.source, + domain=self.source.primary_domain, + nameservers=["ns.example.test"], + responsible_name="hostmaster.example.test", + mx_records=[asdict(mx) for mx in mx_records], + ) + + def queue(self): + return self.client.post( + self.url, {"action": "save", "primary": self.primary.pk} + ) + + def test_add_and_remove_without_creating_a_second_mailbox(self): + zone = self.zone() + self.assertRedirects(self.queue(), self.url) + job = MailDomainAlias.objects.get() + spec = MailDomainAliasRequest( + self.source.primary_domain, self.primary.domain + ) + with patch( + "coulobre.hosting.mail_domain_aliases.apply_on_local_node" + ) as apply: + publish_mail_domain_alias.run(job.pk) + self.assertEqual(apply.call_args.args[0], spec) + self.assertEqual(apply.call_args.kwargs["identity"], spec.identity()) + job.refresh_from_db() + zone.refresh_from_db() + self.assertTrue(job.active) + self.assertEqual(HostingMailbox.objects.count(), 1) + self.assertEqual( + zone.spec.mx_records, + (MxRecord(spec.domain, 10, "mx.example.test"),), + ) + self.assertContains(self.client.get(self.url), "Copy MX record") + + zone.publication.finished_at = timezone.now() + zone.publication.save(update_fields=["finished_at"]) + self.assertRedirects( + self.client.post(self.url, {"action": "remove"}), self.url + ) + with patch( + "coulobre.hosting.mail_domain_aliases.apply_on_local_node" + ) as apply: + publish_mail_domain_alias.run(job.pk) + self.assertTrue(apply.call_args.args[0].remove) + self.assertFalse(MailDomainAlias.objects.exists()) + zone.refresh_from_db() + self.assertEqual(zone.spec.mx_records, ()) + self.assertEqual(HostingMailbox.objects.count(), 1) + + def test_requires_common_owner_and_preserves_existing_mx(self): + current = MxRecord( + self.source.primary_domain, 10, "external.example.test" + ) + zone = self.zone((current,)) + self.assertContains(self.queue(), "Review the existing MX targets") + self.assertFalse(MailDomainAlias.objects.exists()) + zone.refresh_from_db() + self.assertEqual(zone.spec.mx_records, (current,)) + + self.owner.customer = None + self.owner.save(update_fields=["customer"]) + self.assertContains(self.queue(), "Select a valid choice") + self.assertFalse(MailDomainAlias.objects.exists()) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 38159f5..6ca84b3 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -52,6 +52,7 @@ from .invitations import AcceptInvitation, ManageInvitation from .mail_delivery_views import MailDeliveryView from .mail_diagnostics_views import MailDiagnosticsView from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup +from .mail_domain_alias_views import mail_domain_alias from .mail_policy_views import ( MailRoutingEditor, MailSpamEditor, @@ -265,6 +266,11 @@ urlpatterns = [ domain_workspace, name="domain_workspace", ), + path( + "accounts//mail-domain-alias//", + mail_domain_alias, + name="mail_domain_alias", + ), path( "hosting//", customer_workspace, name="customer_workspace" ), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 8747609..f9a75b4 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -105,6 +105,7 @@ from .installation_features import ( ) from .invitations import InviteLoginForm, queue_invitation from .limit_forms import add_unlimited_fields +from .mail_domain_alias_views import may_manage_aliases from .mail_policy_views import mail_policy_enabled from .mailbox_removal import can_remove_mailbox from .models import ( @@ -984,6 +985,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["manage_mail_routing"] = mail_policy_enabled( self.request, "routing" ) + if may_manage_aliases(self.request): + context["mail_alias_domains"] = ( + self.object.website_domains.order_by("domain") + .exclude( + domain__in=self.object.mail_domains.values("domain") + ) + .select_related("mail_alias__primary") + ) context["manage_mail_vacation"] = mail_policy_enabled( self.request, "vacation" ) diff --git a/src/coulobre/hosting/website_aliases.py b/src/coulobre/hosting/website_aliases.py index 370ec01..db9ed41 100644 --- a/src/coulobre/hosting/website_aliases.py +++ b/src/coulobre/hosting/website_aliases.py @@ -62,6 +62,10 @@ def queue_alias_operation(account_id, alias_id, operation, *, allow_https): if not alias.problem: return operation = alias.operation + if operation == WebsiteAlias.Operation.REMOVE and hasattr( + alias.reservation, "mail_alias" + ): + raise ValidationError("Remove the mail domain alias first.") if operation == WebsiteAlias.Operation.HTTPS: if not allow_https: raise PermissionDenied diff --git a/src/coulobre/mail_domain_alias.py b/src/coulobre/mail_domain_alias.py new file mode 100644 index 0000000..34d9bbe --- /dev/null +++ b/src/coulobre/mail_domain_alias.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass + +from .domain_names import canonical_domain +from .mail_policy import MailPolicy + +OPERATION = "set_mail_domain_alias" + + +@dataclass(frozen=True) +class MailDomainAliasRequest(MailPolicy): + domain: str + target: str + remove: bool = False + + def __post_init__(self): + if not isinstance(self.domain, str) or not isinstance( + self.target, str + ): + raise ValueError("Provide the alias and primary mail domains.") + for field in ("domain", "target"): + object.__setattr__( + self, field, canonical_domain(getattr(self, field)) + ) + if self.domain == self.target or type(self.remove) is not bool: + raise ValueError("Choose a different primary mail domain.") + + def manifest(self): + return { + "version": 1, + "operation": OPERATION, + "domain": self.domain, + "target": self.target, + "remove": self.remove, + } + + @classmethod + def from_manifest(cls, data): + if ( + data.keys() + != {"version", "operation", "domain", "target", "remove"} + or type(data["version"]) is not int + or data["version"] != 1 + or data["operation"] != OPERATION + ): + raise ValueError("Invalid mail domain alias request.") + return cls(data["domain"], data["target"], data["remove"]) diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index ab8db66..1fbe773 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -171,6 +171,8 @@ class MailboxRemovalRequest(RetirementRequest): def parse_mailbox_request(data): from .mail_delivery import OPERATION, MailDeliveryRequest + from .mail_domain_alias import OPERATION as DOMAIN_ALIAS_OPERATION + from .mail_domain_alias import MailDomainAliasRequest from .mail_filter_check import OPERATION as FILTER_OPERATION from .mail_filter_check import MailFilterCheckRequest from .mail_policy import OPERATIONS, parse_mail_policy @@ -192,6 +194,11 @@ def parse_mailbox_request(data): return parse_mailbox_password_request(data) if isinstance(data, dict) and data.get("operation") == OPERATION: return MailDeliveryRequest.from_manifest(data) + if ( + isinstance(data, dict) + and data.get("operation") == DOMAIN_ALIAS_OPERATION + ): + return MailDomainAliasRequest.from_manifest(data) if isinstance(data, dict) and data.get("operation") == FILTER_OPERATION: return MailFilterCheckRequest.from_manifest(data) if isinstance(data, dict) and data.get("operation") in { @@ -251,6 +258,7 @@ def mailbox_request_identity(spec): def apply_mailbox_request(request): from .mail_delivery import MailDeliveryRequest, inspect_delivery + from .mail_domain_alias import MailDomainAliasRequest from .mail_filter_check import MailFilterCheckRequest, check_spam_filter from .mail_policy import MailRouting, MailVacation from .mail_queue import ( @@ -287,6 +295,11 @@ def apply_mailbox_request(request): apply_routing(request) return None + if isinstance(request, MailDomainAliasRequest): + from .mail_node_routing import apply_domain_alias + + apply_domain_alias(request) + return None if isinstance(request, MailVacation): from .mail_node_vacation import apply_vacation diff --git a/src/coulobre/mail_node_routing.py b/src/coulobre/mail_node_routing.py index 031e795..e23a5a7 100644 --- a/src/coulobre/mail_node_routing.py +++ b/src/coulobre/mail_node_routing.py @@ -2,6 +2,7 @@ import json import os from . import mail_node_apply as mail +from .mail_domain_alias import MailDomainAliasRequest from .mail_policy import MailRouting, parse_mail_policy from .node_files import ( read_root_file, @@ -41,6 +42,115 @@ def save_policy(spec): path.unlink(missing_ok=True) +def domain_alias_path(): + return mail.STATE_DIRECTORY / "domain-aliases" + + +def domain_aliases(): + path = domain_alias_path() + if not os.path.lexists(path): + return {} + data = json.loads(read_root_file(path, mode=0o600)) + if not isinstance(data, dict): + raise ValueError("Invalid mail domain alias registry.") + for domain, target in data.items(): + spec = MailDomainAliasRequest(domain, target) + if spec.domain != domain or spec.target != target or target in data: + raise ValueError("Invalid mail domain alias registry.") + return data + + +def check_alias_domain_configuration(domain): + expected = f"proxy:texthash:{POSTFIX_ALIASES}" + for setting in ("virtual_alias_domains", "virtual_alias_maps"): + if mail.run("postconf", "-hx", setting) != expected: + raise ValueError( + f"Configure Postfix {setting} to use the Coulobre alias map." + ) + for setting in ("mydestination", "relay_domains"): + destinations = ( + mail.run("postconf", "-hx", setting).replace(",", " ").split() + ) + if any( + unsafe_destination(domain, destination) + for destination in destinations + ): + raise ValueError( + f"Review Postfix {setting} before assigning this domain." + ) + mail.run("postfix", "check") + + +def unsafe_destination(domain, destination): + value = destination.lower().removeprefix(".").removesuffix(".") + # Do not assume that custom tables or patterns exclude the alias. + return ( + not value + or any( + char not in "abcdefghijklmnopqrstuvwxyz0123456789.-" + for char in value + ) + or domain == value + or domain.endswith(f".{value}") + ) + + +def apply_domain_alias(spec): + with mail.locked_state(create=False, exclusive=True) as state: + if state is None: + raise ValueError("Provision a primary mail domain first.") + aliases = domain_aliases() + current = aliases.get(spec.domain) + if current is not None and current != spec.target: + raise ValueError("This alias has a different primary domain.") + if spec.remove and current is None: + return + records = [ + mail.load_credentials(path) + for path in mail.STATE_DIRECTORY.glob("*.json") + ] + recipients = managed_recipients(records) + routes = policies() + if spec.remove: + del aliases[spec.domain] + else: + check_alias_domain_configuration(spec.domain) + if ( + spec.domain in routes + or any( + record.mailbox.domain == spec.domain for record in records + ) + or spec.domain in aliases.values() + or any( + address.endswith(f"@{spec.domain}") + for route in routes.values() + for address in route.destinations + ) + ): + raise ValueError( + "This alias domain already has independent mail routing." + ) + if spec.target in aliases or not any( + address.endswith(f"@{spec.target}") for address in recipients + ): + raise ValueError( + "Choose a primary mail domain with a managed mailbox." + ) + aliases[spec.domain] = spec.target + + previous = read_table() + try: + publish_routes(routes, recipients, previous, aliases=aliases) + mail.run("postfix", "reload") + replace_configuration( + domain_alias_path(), json.dumps(aliases), mode=0o600 + ) + except (OSError, ValueError): + replace_configuration(POSTFIX_ALIASES, previous) + mail.run("postfix", "reload") + raise + + def managed_recipients(records): return { record.mailbox.address @@ -60,6 +170,7 @@ def apply_routing(spec): ] recipients = managed_recipients(records) domains = {address.split("@")[1] for address in recipients} + aliases = domain_aliases() if spec.domain not in domains: raise ValueError("Install a managed mailbox on this domain first.") for local in spec.aliases: @@ -69,8 +180,9 @@ def apply_routing(spec): ) for address in sorted(spec.destinations): domain = address.split("@")[1] - if domain in domains and ( - domain != spec.domain or address not in recipients + if domain in aliases or ( + domain in domains + and (domain != spec.domain or address not in recipients) ): raise ValueError( f"{address} must be a mailbox on this mail domain " @@ -81,7 +193,7 @@ def apply_routing(spec): routes[spec.domain] = spec previous = read_table() try: - publish_routes(routes, recipients, previous) + publish_routes(routes, recipients, previous, aliases=aliases) mail.run("postfix", "reload") save_policy(spec) except (OSError, ValueError): @@ -106,13 +218,14 @@ def read_table(): return contents -def publish_routes(routes, recipients, previous): +def publish_routes(routes, recipients, previous, *, aliases): domains = {} for address in recipients: domain = address.split("@")[1] domains.setdefault(domain, set()).add(address) rows = set() + forwarding = {} for domain, spec in routes.items(): mailboxes = domains.get(domain) if not mailboxes: @@ -129,10 +242,25 @@ def publish_routes(routes, recipients, previous): ] if source not in mailboxes and targets: rows.add(f"{source} {','.join(targets)}") + forwarding.setdefault(domain, set()).add(source) + for alias, domain in aliases.items(): + # Declare the domain and mirror its deliverable recipients. + # A wildcard is present only when the primary has a catch-all. + rows.add(f"{alias} OK") + mailboxes = domains.get(domain, set()) + for address in mailboxes | forwarding.get(domain, set()): + local = address.partition("@")[0] + rows.add(f"{local}@{alias} {address}") + if (spec := routes.get(domain)) and spec.catchall in mailboxes: + rows.add(f"@{alias} {spec.catchall}") mail.publish_table(POSTFIX_ALIASES, (0o644, None, rows), previous) def check_mailbox_alias(mailbox): + if mailbox.domain in domain_aliases(): + raise ValueError( + "Remove the mail domain alias before adding mailboxes." + ) spec = policies().get(mailbox.domain) if spec is not None and mailbox.local_part in spec.aliases: raise ValueError( @@ -142,7 +270,8 @@ def check_mailbox_alias(mailbox): def reconcile_routes(records, *, retired=None): routes = policies() - if not routes: + aliases = domain_aliases() + if not routes and not aliases: return previous = read_table() recipients = managed_recipients(records) @@ -168,6 +297,6 @@ def reconcile_routes(records, *, retired=None): else: spec = MailRouting(spec.domain, {}) routes[spec.domain] = pruned = spec - publish_routes(routes, recipients, previous) + publish_routes(routes, recipients, previous, aliases=aliases) if pruned is not None: save_policy(pruned) diff --git a/src/coulobre/receiver_scope.py b/src/coulobre/receiver_scope.py index 9839d95..c6a3cf5 100644 --- a/src/coulobre/receiver_scope.py +++ b/src/coulobre/receiver_scope.py @@ -103,6 +103,17 @@ def authorized_request(role, spec=None): raise ValueError( "The panel key is not assigned to this domain." ) + if role == "mail" and spec is not None: + from .mail_domain_alias import MailDomainAliasRequest + + if ( + isinstance(spec, MailDomainAliasRequest) + and spec.target not in domains + ): + raise ValueError( + "The panel key is not assigned to the primary " + "mail domain." + ) else: raise ValueError("The peer is not authorized for this receiver.") yield diff --git a/src/coulobre/test_receiver_scope.py b/src/coulobre/test_receiver_scope.py index 0a1e87b..55e0b75 100644 --- a/src/coulobre/test_receiver_scope.py +++ b/src/coulobre/test_receiver_scope.py @@ -12,6 +12,7 @@ from uuid import uuid4 from . import node_maintenance, node_setup, receiver_scope from .dns_node import DnsZone +from .mail_domain_alias import MailDomainAliasRequest from .mail_filter_check import MailFilterCheckRequest from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request from .mail_policy import MailRouting @@ -96,6 +97,26 @@ class ReceiverScopeTests(TestCase): with self.assertRaisesRegex(ValueError, "not assigned"): check_request("mail", MailQueueRequest("alpha.example.test")) + def test_domain_alias_requires_both_domains_in_the_same_scope(self): + spec = MailDomainAliasRequest( + "alias.example.test", "main.example.test" + ) + spec = parse_mailbox_request(spec.manifest()) + with ( + patch.object( + receiver_scope, + "socket_peer", + return_value="coulobre-mail-p-alpha", + ), + patch.object(receiver_scope, "scoped_domains") as scope, + ): + for domains in ({spec.domain}, {spec.target}, set()): + scope.return_value = domains + with self.assertRaisesRegex(ValueError, "not assigned"): + check_request("mail", spec) + scope.return_value = {spec.domain, spec.target} + check_request("mail", spec) + def test_password_requests_never_expose_read_or_cross_panel_access(self): mailbox = MailboxSpec("alpha.example.test", "sales") with self.assertRaisesRegex(ValueError, "password change"): -- 2.43.0