From 1c403debd83b306aa9e4c68a74d5c27baf809dd7 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 23:48:02 +0100 Subject: [PATCH 1/2] Support MX and TXT records in BIND9 deployment manifests --- docs/development.md | 29 ++++ src/coulobre/dns_node.py | 191 +++++++++++++++++++++++--- src/coulobre/hosting/test_dns_node.py | 68 ++++++++- 3 files changed, 268 insertions(+), 20 deletions(-) diff --git a/docs/development.md b/docs/development.md index 2419857..9a20763 100644 --- a/docs/development.md +++ b/docs/development.md @@ -155,6 +155,35 @@ coulobre-dns-node render coulobre-zone.json > db.example.net named-checkzone example.net db.example.net ``` +### Include mail records in a manifest + +Version 2 adds the `mx_records` and `txt_records` arrays. In a version 1 +manifest, update the version to `2` and add both arrays. Use an empty array +when you only need one record type. Version 1 manifests still work with +the updated node command. + +```json +{ + "version": 2, + "mx_records": [ + {"name": "example.net", "priority": 10, "exchange": "mx.provider.example"} + ], + "txt_records": [ + {"name": "example.net", "text": "v=spf1 mx -all"}, + {"name": "_dmarc.example.net", "text": "v=DMARC1; p=none"} + ] +} +``` + +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 +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) + +Supply TXT values as plain JSON strings. The renderer quotes the values and +splits long UTF-8 strings into DNS character strings. DKIM readers concatenate +the strings in the TXT record. [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035.html) and [RFC 6376](https://www.rfc-editor.org/rfc/rfc6376.html) + ### Apply a zone manifest Install `bind9` and `bind9-utils` on an Ubuntu DNS node. Use BIND9's default diff --git a/src/coulobre/dns_node.py b/src/coulobre/dns_node.py index d8f8d7d..e6a2922 100644 --- a/src/coulobre/dns_node.py +++ b/src/coulobre/dns_node.py @@ -1,15 +1,20 @@ import argparse import ipaddress import json +import re import sys -from dataclasses import dataclass +from dataclasses import asdict, dataclass from pathlib import Path +import idna + from .domain_names import canonical_domain -MANIFEST_VERSION = 1 +BASE_MANIFEST_VERSION = 1 +MAIL_RECORD_MANIFEST_VERSION = 2 MANIFEST_KIND = "bind9_zone" MAX_SOA_SERIAL = 2**32 - 1 +TXT_CHUNK_SIZE = 255 def dns_name(value): @@ -22,6 +27,48 @@ def in_zone(name, domain): return name == domain or name.endswith(f".{domain}") +def txt_owner_name(value): + if not isinstance(value, str) or "_" not in value: + return dns_name(value) + + try: + labels = ( + idna.uts46_remap(value.strip(), std3_rules=False) + .removesuffix(".") + .split(".") + ) + ascii_labels = [] + for label in labels: + if "_" in label: + if not re.fullmatch(r"[a-z0-9_-]{1,63}", label): + raise ValueError + ascii_labels.append(label) + else: + ascii_labels.append(idna.encode(label).decode("ascii")) + name = ".".join(ascii_labels) + if len(name) > 253: + raise ValueError + except ValueError: + raise ValueError("Enter a valid TXT record name.") from None + return name + + +def txt_chunks(text): + data = text.encode("utf-8") + return tuple( + data[offset : offset + TXT_CHUNK_SIZE] + for offset in range(0, len(data), TXT_CHUNK_SIZE) + ) or (b"",) + + +def quote_txt_chunk(chunk): + escaped = "".join( + chr(byte) if 32 <= byte <= 126 and byte not in (34, 92) else f"\\{byte:03d}" + for byte in chunk + ) + return f'"{escaped}"' + + @dataclass(frozen=True) class AddressRecord: name: str @@ -50,6 +97,73 @@ class AddressRecord: return cls(data["name"], data["address"]) +@dataclass(frozen=True) +class MxRecord: + name: str + priority: int + exchange: str + + def __post_init__(self): + object.__setattr__(self, "name", dns_name(self.name)) + if type(self.priority) is not int or not 0 <= self.priority <= 65535: + raise ValueError("MX priority must be an integer from 0 to 65535.") + if self.exchange == ".": + if self.priority != 0: + raise ValueError("A null MX record must use priority 0.") + else: + object.__setattr__(self, "exchange", dns_name(self.exchange)) + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "name", + "priority", + "exchange", + }: + raise ValueError( + "Expected an MX record with a name, priority and exchange." + ) + return cls(data["name"], data["priority"], data["exchange"]) + + def render(self): + exchange = "." if self.exchange == "." else f"{self.exchange}." + return f"{self.name}. IN MX {self.priority} {exchange}" + + +@dataclass(frozen=True) +class TxtRecord: + name: str + text: str + + def __post_init__(self): + object.__setattr__(self, "name", txt_owner_name(self.name)) + if not isinstance(self.text, str): + raise ValueError("Expected a string for the TXT record value.") + try: + chunks = txt_chunks(self.text) + except UnicodeEncodeError: + raise ValueError("The TXT record value must be valid Unicode.") from None + if sum(len(chunk) + 1 for chunk in chunks) > 65535: + raise ValueError("The TXT record value is too long for DNS.") + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != {"name", "text"}: + raise ValueError("Expected a TXT record with a name and text.") + return cls(data["name"], data["text"]) + + def render(self): + text = " ".join(quote_txt_chunk(chunk) for chunk in txt_chunks(self.text)) + return f"{self.name}. IN TXT {text}" + + +def read_records(data, key, record_type): + records = data.get(key, []) + if not isinstance(records, list): + raise ValueError(f"Expected a list for {key}.") + return tuple(record_type.from_manifest(record) for record in records) + + @dataclass(frozen=True) class DnsZone: domain: str @@ -57,6 +171,8 @@ class DnsZone: nameservers: tuple[str, ...] responsible_name: str addresses: tuple[AddressRecord, ...] = () + mx_records: tuple[MxRecord, ...] = () + txt_records: tuple[TxtRecord, ...] = () def __post_init__(self): object.__setattr__(self, "domain", dns_name(self.domain)) @@ -76,10 +192,44 @@ class DnsZone: for name in nameservers ): raise ValueError("Each in-zone nameserver needs an address record.") + self.check_mail_records(address_names) + + def check_mail_records(self, address_names): + if any( + not in_zone(record.name, self.domain) + for record in (*self.mx_records, *self.txt_records) + ): + raise ValueError("MX and TXT records must belong to the zone.") + mx_names = set() + null_mx_names = set() + for record in self.mx_records: + if record.exchange == ".": + null_mx_names.add(record.name) + else: + if ( + in_zone(record.exchange, self.domain) + and record.exchange not in address_names + ): + raise ValueError( + "Each in-zone MX exchange needs an address record." + ) + mx_names.add(record.name) + if mx_names & null_mx_names: + raise ValueError( + "A null MX record cannot share a name with another MX record." + ) @classmethod def from_manifest(cls, data): - if not isinstance(data, dict) or data.keys() != { + if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND: + raise ValueError("Expected a BIND9 zone manifest.") + version = data.get("version") + if type(version) is not int or version not in ( + BASE_MANIFEST_VERSION, + MAIL_RECORD_MANIFEST_VERSION, + ): + raise ValueError("Unsupported DNS zone manifest version.") + fields = { "version", "kind", "domain", @@ -87,39 +237,40 @@ class DnsZone: "nameservers", "responsible_name", "addresses", - }: - raise ValueError("Expected a BIND9 zone manifest.") - if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION: - raise ValueError("Unsupported DNS zone manifest version.") - if data["kind"] != MANIFEST_KIND: + } + if version == MAIL_RECORD_MANIFEST_VERSION: + fields.update(("mx_records", "txt_records")) + if data.keys() != fields: raise ValueError("Expected a BIND9 zone manifest.") if not isinstance(data["nameservers"], list): raise ValueError("Expected a list of nameservers.") - if not isinstance(data["addresses"], list): - raise ValueError("Expected a list of address records.") return cls( domain=data["domain"], serial=data["serial"], nameservers=tuple(data["nameservers"]), responsible_name=data["responsible_name"], - addresses=tuple( - AddressRecord.from_manifest(item) for item in data["addresses"] - ), + addresses=read_records(data, "addresses", AddressRecord), + mx_records=read_records(data, "mx_records", MxRecord), + txt_records=read_records(data, "txt_records", TxtRecord), ) def manifest(self): - return { - "version": MANIFEST_VERSION, + manifest = { + "version": BASE_MANIFEST_VERSION, "kind": MANIFEST_KIND, "domain": self.domain, "serial": self.serial, "nameservers": list(self.nameservers), "responsible_name": self.responsible_name, - "addresses": [ - {"name": record.name, "address": record.address} - for record in self.addresses - ], + "addresses": [asdict(record) for record in self.addresses], } + if self.mx_records or self.txt_records: + manifest.update( + version=MAIL_RECORD_MANIFEST_VERSION, + mx_records=[asdict(record) for record in self.mx_records], + txt_records=[asdict(record) for record in self.txt_records], + ) + return manifest def render(self): lines = [ @@ -133,6 +284,8 @@ class DnsZone: f"{record.name}. IN {record.record_type} {record.address}" for record in self.addresses ) + lines.extend(record.render() for record in self.mx_records) + lines.extend(record.render() for record in self.txt_records) return "\n".join(lines) + "\n" diff --git a/src/coulobre/hosting/test_dns_node.py b/src/coulobre/hosting/test_dns_node.py index 00f9ec6..8ee90ff 100644 --- a/src/coulobre/hosting/test_dns_node.py +++ b/src/coulobre/hosting/test_dns_node.py @@ -6,7 +6,7 @@ from tempfile import TemporaryDirectory from django.test import SimpleTestCase -from coulobre.dns_node import DnsZone, main +from coulobre.dns_node import DnsZone, TxtRecord, main class DnsZoneManifestTests(SimpleTestCase): @@ -38,6 +38,7 @@ class DnsZoneManifestTests(SimpleTestCase): "xn--bcher-kva.example. IN A 192.0.2.20\n" "ns1.xn--bcher-kva.example. IN AAAA 2001:db8::53\n", ) + self.assertEqual(zone.manifest()["version"], 1) self.assertEqual(DnsZone.from_manifest(zone.manifest()), zone) def test_accepts_a_single_external_nameserver_without_address_records(self): @@ -104,3 +105,68 @@ class DnsZoneManifestTests(SimpleTestCase): self.assertIn( "SOA serial must be an unsigned 32-bit integer", stderr.getvalue() ) + + def test_version_two_renders_mx_and_txt_with_canonical_names(self): + payload = self.manifest | { + "version": 2, + "mx_records": [ + { + "name": "Bücher.Example.", + "priority": 10, + "exchange": "MX.Provider.Example.", + }, + {"name": "parked.bücher.example", "priority": 0, "exchange": "."}, + ], + "txt_records": [ + {"name": "bücher.example", "text": "v=spf1 mx -all"}, + {"name": "_DMARC.BÜCHER。Example.", "text": "v=DMARC1; p=none"}, + ], + } + + zone = DnsZone.from_manifest(payload) + + self.assertEqual(zone.manifest()["version"], 2) + self.assertEqual(DnsZone.from_manifest(zone.manifest()), zone) + self.assertTrue( + zone.render().endswith( + "xn--bcher-kva.example. IN MX 10 mx.provider.example.\n" + "parked.xn--bcher-kva.example. IN MX 0 .\n" + 'xn--bcher-kva.example. IN TXT "v=spf1 mx -all"\n' + '_dmarc.xn--bcher-kva.example. IN TXT "v=DMARC1; p=none"\n' + ) + ) + + def test_invalid_mail_records_are_rejected(self): + manifest = self.manifest | {"version": 2, "mx_records": [], "txt_records": []} + mail = { + "name": "bücher.example", + "priority": 10, + "exchange": "mx.provider.example", + } + text = {"name": "mail._domainkey.bücher.example", "text": "v=DKIM1; p=abc"} + for changes in ( + {"version": 1}, + {"mx_records": None}, + {"mx_records": [mail | {"priority": True}]}, + {"mx_records": [mail | {"priority": 65536}]}, + {"mx_records": [mail | {"exchange": "missing.bücher.example"}]}, + {"mx_records": [mail | {"exchange": "."}]}, + {"mx_records": [mail, mail | {"priority": 0, "exchange": "."}]}, + {"txt_records": [text | {"name": "_domainkey.not-bücher.example"}]}, + {"txt_records": [text | {"name": "_dmarc" + "_" * 64 + ".bücher.example"}]}, + {"txt_records": [text | {"text": ["multivalued"]}]}, + {"txt_records": [text | {"text": "\ud800"}]}, + {"txt_records": [text | {"text": "x" * 65535}]}, + ): + with self.subTest(changes=set(changes)), self.assertRaises(ValueError): + DnsZone.from_manifest(manifest | changes) + + def test_txt_values_are_escaped_and_split_by_encoded_byte_length(self): + owner = "mail._domainkey.example.net" + record = TxtRecord(owner, "x" * 254 + 'é"\\\n') + + self.assertEqual( + record.render(), + f'{owner}. IN TXT "{"x" * 254}\\195" "\\169\\034\\092\\010"', + ) + self.assertEqual(TxtRecord(owner, "").render(), f'{owner}. IN TXT ""') From 4c165a5a037aef1cd4a8f225e0b360bfdc0e308a Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Fri, 20 Nov 2026 19:46:11 +0100 Subject: [PATCH 2/2] Manage MX and TXT records in the DNS zone editor --- docs/development.md | 22 +++- src/coulobre/hosting/dns_forms.py | 85 +++++++++++++- .../0009_hostingdnszone_mail_records.py | 22 ++++ src/coulobre/hosting/models.py | 14 ++- src/coulobre/hosting/test_dns_zones.py | 108 ++++++++++++++++++ src/coulobre/hosting/views.py | 9 +- 6 files changed, 249 insertions(+), 11 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0009_hostingdnszone_mail_records.py 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):