diff --git a/docs/development.md b/docs/development.md index 9a20763..731480b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -112,14 +112,25 @@ when the MariaDB administrative connection fails. Open a hosting account and select **Add DNS zone** to configure a zone for its primary domain. Enter the nameservers, SOA mailbox, and any A or AAAA -records. To edit an existing zone, select its domain in the **DNS zones** -table. The panel increments the SOA serial when the zone data changes. -Changing the account's primary domain preserves its existing DNS zones. +records. To edit an existing zone, select its domain in the **DNS zones** table. + +- In **MX records**, enter a name, priority and mail server on each line, + such as `@ 10 mx.provider.example`. Add an A or AAAA record for each + mail server inside the zone. +- In **TXT records**, enter a name and its value on each line, such as + `_dmarc.example.net v=DMARC1; p=none`. Use a quoted JSON string to preserve + leading spaces, line breaks, or an empty value. + +Use `@` for the zone domain in either field. Use fully qualified names +for other records. The panel increments the SOA serial when the zone data +changes. Changing the account's primary domain preserves its existing DNS zones. Select **Download manifest** in the DNS table and copy the file to the hosting server or a separate DNS node. Resellers can see the configured domains and serials for their assigned accounts. Operators with the appropriate permissions can add and edit zones and download manifests. +The panel exports version 2 for zones containing MX or TXT records and +version 1 for other zones. A manifest can also be written directly for local testing. Save the following example as `coulobre-zone.json`. @@ -175,8 +186,9 @@ the updated node command. } ``` -Keep the domain, serial, nameservers, mailbox and addresses from the original -manifest. Use fully qualified record names and supply an A or AAAA record for +Keep the domain, nameservers, mailbox and addresses from the original +manifest. Increase the serial when updating a published zone. Use fully +qualified record names and supply an A or AAAA record for each MX server inside the zone. Use priority `0` and exchange `.` for a null MX record at a name that receives no mail. [RFC 7505](https://www.rfc-editor.org/rfc/rfc7505.html) diff --git a/src/coulobre/hosting/dns_forms.py b/src/coulobre/hosting/dns_forms.py index 544f371..64b3c9c 100644 --- a/src/coulobre/hosting/dns_forms.py +++ b/src/coulobre/hosting/dns_forms.py @@ -1,6 +1,26 @@ +import json + from django import forms -from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone +from coulobre.dns_node import ( + MAX_SOA_SERIAL, + AddressRecord, + DnsZone, + MxRecord, + TxtRecord, +) + + +def format_txt_record(record): + text = record["text"] + if ( + not text + or text != text.strip() + or text.startswith('"') + or not text.isprintable() + ): + text = json.dumps(text) + return f"{record['name']} {text}" class DnsZoneForm(forms.Form): @@ -18,6 +38,19 @@ class DnsZoneForm(forms.Form): widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}), help_text="Enter a fully qualified name and an IPv4 or IPv6 address on each line.", ) + mx_records = forms.CharField( + label="MX records", + required=False, + widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}), + help_text="Enter a name, priority and mail server on each line, such as @ 10 mx.example.net.", + ) + txt_records = forms.CharField( + label="TXT records", + required=False, + strip=False, + widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}), + help_text="Enter a name and text on each line. Use @ for the zone domain or a fully qualified name. Use a quoted JSON string to preserve special whitespace or enter an empty value.", + ) def __init__(self, *args, domain, **kwargs): super().__init__(*args, **kwargs) @@ -39,6 +72,45 @@ class DnsZoneForm(forms.Form): raise forms.ValidationError(f"Line {number}. {error}") from error return tuple(records) + def clean_mx_records(self): + return self.clean_mail_records("mx_records", self.parse_mx_record) + + def clean_txt_records(self): + return self.clean_mail_records("txt_records", self.parse_txt_record) + + def clean_mail_records(self, field, parse): + records = [] + for number, line in enumerate(self.cleaned_data[field].splitlines(), 1): + if not line.strip(): + continue + try: + records.append(parse(line)) + except ValueError as error: + raise forms.ValidationError(f"Line {number}. {error}") from error + return tuple(records) + + def parse_mx_record(self, line): + try: + name, priority, exchange = line.split() + priority = int(priority, 10) + except ValueError: + raise ValueError( + "Enter a name, an integer priority and a mail server." + ) from None + return MxRecord(self.domain if name == "@" else name, priority, exchange) + + def parse_txt_record(self, line): + try: + name, text = line.split(maxsplit=1) + except ValueError: + raise ValueError("Enter a name and text.") from None + if text.startswith('"'): + try: + text = json.loads(text) + except json.JSONDecodeError: + raise ValueError("Enter a valid quoted JSON string.") from None + return TxtRecord(self.domain if name == "@" else name, text) + def clean(self): data = super().clean() if self.errors: @@ -50,13 +122,18 @@ class DnsZoneForm(forms.Form): nameservers=tuple(data["nameservers"].split()), responsible_name=data["responsible_name"], addresses=data["addresses"], + mx_records=data["mx_records"], + txt_records=data["txt_records"], ) except ValueError as error: raise forms.ValidationError(str(error)) from error + manifest = spec.manifest() data.update( - nameservers=list(spec.nameservers), - responsible_name=spec.responsible_name, - addresses=spec.manifest()["addresses"], + nameservers=manifest["nameservers"], + responsible_name=manifest["responsible_name"], + addresses=manifest["addresses"], + mx_records=manifest.get("mx_records", []), + txt_records=manifest.get("txt_records", []), ) return data diff --git a/src/coulobre/hosting/migrations/0009_hostingdnszone_mail_records.py b/src/coulobre/hosting/migrations/0009_hostingdnszone_mail_records.py new file mode 100644 index 0000000..339d848 --- /dev/null +++ b/src/coulobre/hosting/migrations/0009_hostingdnszone_mail_records.py @@ -0,0 +1,22 @@ +# Generated by Django 5.2.19 on 2026-11-19 22:49 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0008_hostingmailbox"), + ] + + operations = [ + migrations.AddField( + model_name="hostingdnszone", + name="mx_records", + field=models.JSONField(default=list), + ), + migrations.AddField( + model_name="hostingdnszone", + name="txt_records", + field=models.JSONField(default=list), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index cb9fd5a..571d97c 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -4,7 +4,13 @@ from django.db import models 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.dns_node import ( + MAX_SOA_SERIAL, + AddressRecord, + DnsZone, + MxRecord, + TxtRecord, +) from coulobre.mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec from .fields import DomainNameField @@ -93,6 +99,8 @@ class HostingDnsZone(models.Model): nameservers = models.JSONField() responsible_name = DomainNameField(max_length=253) addresses = models.JSONField(default=list) + mx_records = models.JSONField(default=list) + txt_records = models.JSONField(default=list) class Meta: ordering = ("domain",) @@ -113,6 +121,10 @@ class HostingDnsZone(models.Model): addresses=tuple( AddressRecord.from_manifest(item) for item in self.addresses ), + mx_records=tuple(MxRecord.from_manifest(item) for item in self.mx_records), + txt_records=tuple( + TxtRecord.from_manifest(item) for item in self.txt_records + ), ) def __str__(self): diff --git a/src/coulobre/hosting/test_dns_zones.py b/src/coulobre/hosting/test_dns_zones.py index df5c747..3b6c8c4 100644 --- a/src/coulobre/hosting/test_dns_zones.py +++ b/src/coulobre/hosting/test_dns_zones.py @@ -1,3 +1,5 @@ +import json + from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase @@ -65,10 +67,116 @@ class DnsZonePanelTests(TestCase): manifest = self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk])) self.assertEqual(manifest["Cache-Control"], "private, no-store") self.assertIn("attachment", manifest["Content-Disposition"]) + self.assertEqual(manifest.json()["version"], 1) spec = DnsZone.from_manifest(manifest.json()) self.assertEqual(spec, zone.spec) self.assertIn("www.account-a.example. IN AAAA 2001:db8::20\n", spec.render()) + def test_operator_can_create_mail_records_and_download_a_version_two_manifest(self): + form = self.client.get(self.add_url) + self.assertContains(form, "MX records") + self.assertContains(form, "TXT records") + dkim = "v=DKIM1; p=" + "A" * 340 + mail_settings = { + "mx_records": "@ 20 NS1.Account-A.Example.\n@ 10 mx.provider.example", + "txt_records": ( + "@ v=spf1 mx -all\n" + "_DMARC.Account-A.Example. v=DMARC1; p=none\n" + f"mail._domainkey.account-a.example {dkim}" + ), + } + self.assertRedirects( + self.client.post(self.add_url, self.zone_data | mail_settings), + self.account.get_absolute_url(), + ) + + zone = self.account.dns_zones.get() + manifest = self.client.get( + reverse("panel:dns_zone_manifest", args=[zone.pk]) + ).json() + self.assertEqual(manifest["version"], 2) + self.assertEqual(manifest["serial"], 1) + self.assertEqual( + manifest["mx_records"][0], + { + "name": "account-a.example", + "priority": 20, + "exchange": "ns1.account-a.example", + }, + ) + self.assertEqual(manifest["txt_records"][1]["name"], "_dmarc.account-a.example") + self.assertEqual(manifest["txt_records"][2]["text"], dkim) + self.assertEqual(DnsZone.from_manifest(manifest), zone.spec) + + def test_adding_and_removing_mail_records_changes_the_serial_and_manifest_version( + self, + ): + zone = self.create_zone() + edit = reverse("panel:dns_zone_edit", args=[zone.pk]) + export = reverse("panel:dns_zone_manifest", args=[zone.pk]) + text = ' "Café"\\\nVerification ' + self.assertRedirects( + self.client.post( + edit, + self.zone_data + | { + "serial": 1, + "mx_records": "@ 10 mx.provider.example", + "txt_records": ( + f'@ {json.dumps(text)}\nempty.account-a.example ""' + ), + }, + ), + self.account.get_absolute_url(), + ) + manifest = self.client.get(export).json() + self.assertEqual((manifest["version"], manifest["serial"]), (2, 2)) + self.assertEqual([item["text"] for item in manifest["txt_records"]], [text, ""]) + + unchanged = self.client.get(edit).context["form"].initial + self.assertRedirects( + self.client.post(edit, unchanged), + self.account.get_absolute_url(), + ) + self.assertEqual(self.client.get(export).json(), manifest) + + self.assertRedirects( + self.client.post(edit, unchanged | {"mx_records": "", "txt_records": ""}), + self.account.get_absolute_url(), + ) + manifest = self.client.get(export).json() + self.assertEqual((manifest["version"], manifest["serial"]), (1, 3)) + self.assertNotIn("mx_records", manifest) + self.assertNotIn("txt_records", manifest) + + def test_invalid_mail_records_leave_existing_zone_unchanged(self): + zone = self.create_zone() + edit = reverse("panel:dns_zone_edit", args=[zone.pk]) + for fields, message in ( + ( + {"mx_records": "@ 65536 mx.provider.example"}, + "MX priority must be an integer", + ), + ( + {"mx_records": "@ 10 missing.account-a.example"}, + "MX exchange needs an address", + ), + ({"txt_records": '@ "unclosed text'}, "Enter a valid quoted JSON string"), + ( + {"txt_records": "_dmarc.other.example v=DMARC1"}, + "records must belong to the zone", + ), + ): + with self.subTest(fields=fields): + self.assertContains( + self.client.post(edit, self.zone_data | {"serial": 1} | fields), + message, + ) + zone.refresh_from_db() + self.assertEqual(zone.serial, 1) + self.assertEqual(zone.mx_records, []) + self.assertEqual(zone.txt_records, []) + def test_duplicate_and_invalid_zones_leave_the_current_zone_unchanged(self): invalid = self.client.post(self.add_url, self.zone_data | {"addresses": ""}) self.assertContains(invalid, "Each in-zone nameserver needs an address record.") diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 3fac36c..d0a81e5 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -14,7 +14,7 @@ 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 +from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .models import ( HostingAccount, HostingDatabase, @@ -297,6 +297,13 @@ class DnsZoneEdit(DnsZoneEditor): f"{record['name']} {record['address']}" for record in self.zone.addresses ), + "mx_records": "\n".join( + f"{record['name']} {record['priority']} {record['exchange']}" + for record in self.zone.mx_records + ), + "txt_records": "\n".join( + format_txt_record(record) for record in self.zone.txt_records + ), } def form_valid(self, form):