From d81e716ff58290cf0e72af7153452ca116be587d Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 24 Nov 2026 13:41:06 +0100 Subject: [PATCH] Set up mail client DNS aliases for managed domains --- deploy/panel_installer/engine.py | 6 +- docs/deployment.md | 8 +++ src/coulobre/hosting/account_setup.py | 20 ++++++- src/coulobre/hosting/invitations.py | 7 +++ src/coulobre/hosting/mail_dns_setup.py | 55 ++++++++++++++++++- src/coulobre/hosting/mail_dns_views.py | 13 +++++ .../templates/hosting/mail_dns_check.html | 1 + .../templates/hosting/panel_invitation.txt | 2 + .../hosting/panel_invitation_body.html | 1 + src/coulobre/hosting/test_account_setup.py | 6 ++ src/coulobre/hosting/test_mail_dns.py | 24 ++++++++ .../hosting/test_panel_authentication.py | 32 ++++++++++- tests/test_panel_installer.py | 17 ++++++ 13 files changed, 185 insertions(+), 7 deletions(-) diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index b7a95ea..952d416 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -626,14 +626,16 @@ class Installer: options["COULOBRE_LOCAL_MAILBOX_PROVISIONING"] = "1" if self.plan.mail.mode in {"local", "remote-install"}: options["COULOBRE_MAIL_NODE_DKIM"] = "1" + options["COULOBRE_MAIL_IMAP_HOST"] = self.plan.mail.mail_hostname + options["COULOBRE_MAIL_SUBMISSION_HOST"] = ( + self.plan.mail.mail_hostname + ) if self.plan.mail.mode == "local": options.update( COULOBRE_SMTP_HOST="127.0.0.1", COULOBRE_SMTP_PORT="25", COULOBRE_SMTP_STARTTLS="0", COULOBRE_EMAIL_FROM=f"panel@{self.plan.mail.host}", - COULOBRE_MAIL_IMAP_HOST=self.plan.mail.host, - COULOBRE_MAIL_SUBMISSION_HOST=self.plan.mail.host, ) hosting = self.plan.hosting if hosting.public_addresses: diff --git a/docs/deployment.md b/docs/deployment.md index f257eb2..aabbdef 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2277,6 +2277,14 @@ policy ID. Checking the HTTPS policy is a separate step. The DKIM check compares the managed selector with the public key received from the mail node. +When IMAP and SMTP submission share a hostname, Coulobre adds a CNAME +for `mail.` when creating or refreshing managed mail DNS. It +keeps existing records at that name. For external DNS, copy the suggested +CNAME from **Check mail DNS**. Use the configured service hostname until +public DNS resolves and the mail service presents a certificate valid for +the alias. Welcome emails list the configured IMAP and submission hostnames +as the defaults. + ### Set up signing on a Coulobre mail node Install the distribution's `rspamd` package on the mail node, including diff --git a/src/coulobre/hosting/account_setup.py b/src/coulobre/hosting/account_setup.py index f86f59d..8a97ba6 100644 --- a/src/coulobre/hosting/account_setup.py +++ b/src/coulobre/hosting/account_setup.py @@ -12,7 +12,7 @@ from .dns_defaults import zone_defaults from .dns_forms import normalize_record_rows from .dns_publication import queue_zone_snapshot from .installation_features import panel_feature_allowed -from .mail_dns_setup import mail_dns_proposal +from .mail_dns_setup import available_mail_client_alias, mail_dns_proposal from .models import ( HostingDnsZone, HostingMailDomain, @@ -110,6 +110,7 @@ def default_dns_zone(account, *, www=None, wildcard=None, managed_mail=False): domain, ) mx = txt = () + extra_records = extra["extra_records"] if managed_mail: public_key = ( account.mail_domains.filter(domain=domain) @@ -124,6 +125,21 @@ def default_dns_zone(account, *, www=None, wildcard=None, managed_mail=False): for record in mail_addresses if record.name == domain or record.name.endswith(f".{domain}") ) + alias = available_mail_client_alias( + domain, + defaults.nameservers, + ( + *addresses, + *extra["addresses"], + *mx, + *extra["mx_records"], + *txt, + *extra["txt_records"], + *extra_records, + ), + ) + if alias is not None: + extra_records += (alias,) return HostingDnsZone( account=account, domain=domain, @@ -141,7 +157,7 @@ def default_dns_zone(account, *, www=None, wildcard=None, managed_mail=False): asdict(record) for record in dict.fromkeys((*txt, *extra["txt_records"])) ], - extra_records=[asdict(record) for record in extra["extra_records"]], + extra_records=[asdict(record) for record in extra_records], manage_mail_dns=bool(managed_mail), ) diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py index dd66045..65c5d5d 100644 --- a/src/coulobre/hosting/invitations.py +++ b/src/coulobre/hosting/invitations.py @@ -32,6 +32,7 @@ from kombu.exceptions import OperationalError from .access import customer_for_user, is_tenant, reseller_for_user from .account_setup import website_records +from .mail_dns_setup import mail_client_alias from .models import ( Customer, HostingAccount, @@ -280,6 +281,11 @@ def welcome_message_context( nameservers, mail_configured, ): + alias = ( + mail_client_alias(account.primary_domain) + if account and mail_configured + else None + ) return { "username": username, "welcome_message": welcome_message, @@ -298,6 +304,7 @@ def welcome_message_context( ), "imap_host": settings.MAIL_IMAP_HOST, "submission_host": settings.MAIL_SUBMISSION_HOST, + "mail_alias": alias.name if alias else "", "mail_configured": mail_configured, } diff --git a/src/coulobre/hosting/mail_dns_setup.py b/src/coulobre/hosting/mail_dns_setup.py index 04dd598..8da6102 100644 --- a/src/coulobre/hosting/mail_dns_setup.py +++ b/src/coulobre/hosting/mail_dns_setup.py @@ -7,8 +7,10 @@ from django.db import transaction from coulobre.dns_node import ( MAX_SOA_SERIAL, AddressRecord, + ExtraRecord, MxRecord, TxtRecord, + dns_name, ) from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version @@ -57,6 +59,42 @@ def mail_dns_proposal(domain, public_key): return addresses, mx, tuple(records) +def mail_client_alias(domain): + """Return an alias for a shared IMAP and submission hostname.""" + name = f"mail.{domain}" + if len(name) > 253: + return None + try: + imap = dns_name(settings.MAIL_IMAP_HOST) + submission = dns_name(settings.MAIL_SUBMISSION_HOST) + except ValueError: + return None + if imap != submission or name == imap or name == settings.MAIL_MX_HOST: + return None + return ExtraRecord(name, "CNAME", imap) + + +def available_mail_client_alias(domain, nameservers, records): + alias = mail_client_alias(domain) + if alias is None or alias.name in nameservers: + return None + aliases = {} + for record in records: + if record.name == alias.name or ( + isinstance(record, MxRecord) and record.exchange == alias.name + ): + return None + if isinstance(record, ExtraRecord) and record.record_type == "CNAME": + aliases[record.name] = record.value.removesuffix(".") + + visited = {alias.name} + target = alias.value.removesuffix(".") + while target in aliases and target not in visited: + visited.add(target) + target = aliases[target] + return alias if target not in visited else None + + @transaction.atomic def sync_mail_dns(mail_domain, *, public_key=None): account = lock_hosting_account(mail_domain.account_id, customer_id=None) @@ -164,7 +202,12 @@ def publish_mail_records(zone, domain, public_key): raise ValueError( "Publish the saved zone revision before updating mail DNS." ) - changed = bool(additions or not current_mx or new_txt) + alias = available_mail_client_alias( + domain, + spec.nameservers, + (*spec.addresses, *spec.mx_records, *existing, *spec.extra_records), + ) + changed = bool(additions or not current_mx or new_txt or alias) if publication and publication.finished_at is None: if changed: raise MailDnsPublicationPendingError @@ -177,14 +220,22 @@ def publish_mail_records(zone, domain, public_key): addresses=spec.addresses + additions, mx_records=spec.mx_records + (mx if not current_mx else ()), txt_records=spec.txt_records + tuple(new_txt), + extra_records=spec.extra_records + ((alias,) if alias else ()), ) manifest = spec.manifest() zone.serial = spec.serial zone.addresses = manifest["addresses"] zone.mx_records = manifest["mx_records"] zone.txt_records = manifest["txt_records"] + zone.extra_records = manifest.get("extra_records", []) zone.save( - update_fields=["serial", "addresses", "mx_records", "txt_records"] + update_fields=[ + "serial", + "addresses", + "mx_records", + "txt_records", + "extra_records", + ] ) if changed or publication is None or publication.problem: queue_zone_snapshot(zone) diff --git a/src/coulobre/hosting/mail_dns_views.py b/src/coulobre/hosting/mail_dns_views.py index 5cc74f9..0061867 100644 --- a/src/coulobre/hosting/mail_dns_views.py +++ b/src/coulobre/hosting/mail_dns_views.py @@ -25,6 +25,7 @@ from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant from .installation_features import panel_feature_allowed from .mail_dns_setup import ( closest_zone, + mail_client_alias, mail_dns_proposal, queue_mail_dns_setup, ) @@ -119,6 +120,7 @@ class MailDnsCheckView( self.zone_txt = () self.zone_mx = () self.zone_addresses = () + self.zone_extra = () if is_tenant(self.request.user) or self.request.user.has_perm( VIEW_DNS_ZONES ): @@ -130,6 +132,7 @@ class MailDnsCheckView( self.zone_txt = spec.txt_records self.zone_mx = spec.mx_records self.zone_addresses = spec.addresses + self.zone_extra = spec.extra_records def get_initial(self): initial = super().get_initial() @@ -174,6 +177,9 @@ class MailDnsCheckView( == {host + "." for host in self.zone.nameservers} ), entries=entries, + has_mail_client_alias=any( + entry.kind == "CNAME" for entry in entries + ), sending_ips=settings.MAIL_SENDING_IPS, explicit_resolver=bool(settings.MAIL_DNS_RESOLVERS), dmarc_example=not any( @@ -224,6 +230,13 @@ class MailDnsCheckView( for record in dict.fromkeys(self.zone_addresses + addresses) if record.name in targets ) + alias = mail_client_alias(self.domain) + if alias is not None and ( + self.zone is None or alias in self.zone_extra + ): + entries.append( + DnsEntry(alias.name, alias.record_type, alias.value) + ) txt_owners = { self.domain: "v=spf1", f"_dmarc.{self.domain}": "v=DMARC1", diff --git a/src/coulobre/hosting/templates/hosting/mail_dns_check.html b/src/coulobre/hosting/templates/hosting/mail_dns_check.html index aacbea6..9977cfc 100644 --- a/src/coulobre/hosting/templates/hosting/mail_dns_check.html +++ b/src/coulobre/hosting/templates/hosting/mail_dns_check.html @@ -95,6 +95,7 @@

Enter the full record name below, or remove the zone suffix if the editor appends it automatically. Use @ only at that zone’s apex. Enter TXT values without extra quotes.

+ {% if message.mail_alias %}

Use the server names above by default. You can also use {{ message.mail_alias }} once DNS points to your mail service and its TLS certificate covers that name.

{% endif %} {% endif %} {% endif %} {% endif %} diff --git a/src/coulobre/hosting/test_account_setup.py b/src/coulobre/hosting/test_account_setup.py index e6657f9..b11a8c8 100644 --- a/src/coulobre/hosting/test_account_setup.py +++ b/src/coulobre/hosting/test_account_setup.py @@ -15,6 +15,8 @@ from .models import Customer, HostingAccount, PanelInvitation, WebsiteAlias HOSTING_PUBLIC_ADDRESSES=("192.0.2.21", "2001:db8::21"), HOSTING_NAMESERVERS=("ns1.example.test", "ns2.example.test"), MAIL_MX_HOST="mx.example.test", + MAIL_IMAP_HOST="mail.service.example", + MAIL_SUBMISSION_HOST="mail.service.example", MAIL_SENDING_IPS=("192.0.2.21",), ) class HostingAccountSetupTests(TestCase): @@ -54,6 +56,10 @@ class HostingAccountSetupTests(TestCase): {"new.example.test", "www.new.example.test", "*.new.example.test"}, ) self.assertEqual(zone.spec.mx_records[0].exchange, "mx.example.test") + alias = zone.spec.extra_records[0] + self.assertEqual(alias.name, "mail.new.example.test") + self.assertEqual(alias.record_type, "CNAME") + self.assertEqual(alias.value, "mail.service.example.") self.assertTrue( any("v=spf1" in record.text for record in zone.spec.txt_records) ) diff --git a/src/coulobre/hosting/test_mail_dns.py b/src/coulobre/hosting/test_mail_dns.py index 36b2877..04615ad 100644 --- a/src/coulobre/hosting/test_mail_dns.py +++ b/src/coulobre/hosting/test_mail_dns.py @@ -36,6 +36,7 @@ from .tasks import dispatch_dns_publications, provision_mailbox DOMAIN = "example.net" MX = "mx.example.net" +CLIENT_HOST = "mail.service.example" IP = "93.184.215.14" DKIM = "v=DKIM1; k=ed25519; p=" + base64.b64encode(bytes(range(32))).decode() @@ -125,6 +126,8 @@ class MailDnsRecordsTests(SimpleTestCase): LOCAL_MAILBOX_PROVISIONING=True, MANAGE_MAIL_DNS=True, MAIL_MX_HOST=MX, + MAIL_IMAP_HOST=CLIENT_HOST, + MAIL_SUBMISSION_HOST=CLIENT_HOST, MAIL_MX_IPS=(IP,), MAIL_SENDING_IPS=(IP,), ) @@ -177,6 +180,8 @@ class MailDnsPanelTests(TestCase): page = self.client.get(url) self.assertContains(page, "registrar") self.assertContains(page, 'value="mx.example.net."') + self.assertContains(page, 'value="mail.example.net."') + self.assertContains(page, f'value="{CLIENT_HOST}."') self.assertContains(page, 'value="v=spf1 ip4:93.184.215.14 ~all"') self.assertContains(page, 'data-copy-field="dns-name-1"') self.assertContains( @@ -226,6 +231,16 @@ class MailDnsPanelTests(TestCase): zone.mx_records, [{"name": DOMAIN, "priority": 10, "exchange": MX}] ) self.assertEqual(zone.addresses, [{"name": MX, "address": IP}]) + self.assertEqual( + zone.extra_records, + [ + { + "name": f"mail.{DOMAIN}", + "record_type": "CNAME", + "value": f"{CLIENT_HOST}.", + } + ], + ) self.assertEqual( {item["name"]: item["text"] for item in zone.txt_records}, { @@ -240,6 +255,15 @@ class MailDnsPanelTests(TestCase): zone.refresh_from_db() self.assertEqual(zone.serial, 6) + def test_dns_sync_keeps_an_existing_mail_client_host_record(self): + address = {"name": f"mail.{DOMAIN}", "address": "192.0.2.43"} + zone = self.zone(manage_mail_dns=True, addresses=[address]) + sync_mail_dns(self.domain, public_key=DKIM) + zone.refresh_from_db() + self.assertIn(address, zone.addresses) + self.assertEqual(zone.extra_records, []) + self.assertTrue(zone.mx_records) + def test_dns_sync_waits_for_inflight_publication(self): zone = self.zone(manage_mail_dns=True) publication = DnsPublication.objects.create( diff --git a/src/coulobre/hosting/test_panel_authentication.py b/src/coulobre/hosting/test_panel_authentication.py index 9ffb460..8633f5b 100644 --- a/src/coulobre/hosting/test_panel_authentication.py +++ b/src/coulobre/hosting/test_panel_authentication.py @@ -14,10 +14,17 @@ from django_otp.oath import TOTP, totp from django_otp.plugins.otp_email.models import EmailDevice from django_otp.plugins.otp_totp.models import TOTPDevice -from .invitations import deliver_invitation, invitation_token, queue_invitation +from .invitations import ( + deliver_invitation, + invitation_email, + invitation_message_context, + invitation_token, + queue_invitation, +) from .models import ( Customer, HostingAccount, + HostingMailDomain, PanelInvitation, PanelRecoveryCode, Reseller, @@ -255,6 +262,29 @@ class PanelAuthenticationTests(TestCase): 403, ) + @override_settings( + MAIL_IMAP_HOST="srv.example.test", + MAIL_SUBMISSION_HOST="srv.example.test", + ) + def test_welcome_email_keeps_fallback_hosts_and_explains_alias(self): + HostingMailDomain.objects.create( + account=self.account, domain=self.account.primary_domain + ) + context = invitation_message_context(self.customer) + invitation = invitation_email(self.customer.email, context) + html = invitation.alternatives[0].content + for message in (invitation.body, html): + self.assertIn("srv.example.test", message) + self.assertIn(f"mail.{self.account.primary_domain}", message) + self.assertIn("its TLS certificate covers that name", message) + with self.settings(MAIL_SUBMISSION_HOST="submission.example.test"): + context = invitation_message_context(self.customer) + self.assertEqual(context["mail_alias"], "") + self.assertEqual(context["imap_host"], "srv.example.test") + self.assertEqual( + context["submission_host"], "submission.example.test" + ) + def invitation_path(self, body): return urlsplit( next(line for line in body.splitlines() if "/welcome/" in line) diff --git a/tests/test_panel_installer.py b/tests/test_panel_installer.py index 0869627..635433f 100644 --- a/tests/test_panel_installer.py +++ b/tests/test_panel_installer.py @@ -266,6 +266,23 @@ class InstallerParametersTests(unittest.TestCase): ) self.assertIn("192.0.2.41", plan.description()) self.assertNotIn("/root/node-install-key", plan.description()) + with patch( + "deploy.panel_installer.engine.platform_settings", + return_value=(None, True), + ): + installer = Installer(plan, "test-only", Mock()) + installer.state = dict.fromkeys( + ("secret_key", "database_password", "broker_password"), + "test-only", + ) + env = dict( + line.split("=", 1) + for line in installer.environment().splitlines() + ) + self.assertEqual(env["COULOBRE_MAIL_IMAP_HOST"], "mx.example.net") + self.assertEqual( + env["COULOBRE_MAIL_SUBMISSION_HOST"], "mx.example.net" + ) def test_password_file_must_be_private_and_regular(self): with tempfile.TemporaryDirectory() as folder: