From 6e075c25f407604938f90ed3d0771bf747a43309 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 01:30:34 +0100 Subject: [PATCH 1/2] Support local DNS publishing over a restricted Unix socket --- deploy/systemd/coulobre-dns-apply.socket | 14 +++++++ deploy/systemd/coulobre-dns-apply@.service | 20 ++++++++++ docs/development.md | 22 +++++++++++ src/coulobre/dns_node.py | 35 +++++++++++++++--- src/coulobre/hosting/test_dns_node.py | 43 +++++++++++++++++++++- src/coulobre/node_requests.py | 12 +++--- 6 files changed, 134 insertions(+), 12 deletions(-) create mode 100644 deploy/systemd/coulobre-dns-apply.socket create mode 100644 deploy/systemd/coulobre-dns-apply@.service diff --git a/deploy/systemd/coulobre-dns-apply.socket b/deploy/systemd/coulobre-dns-apply.socket new file mode 100644 index 0000000..c1ab9cc --- /dev/null +++ b/deploy/systemd/coulobre-dns-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local BIND9 publishing socket + +[Socket] +ListenStream=/run/coulobre-dns-apply.sock +SocketUser=root +SocketGroup=coulobre-dns-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-dns-apply@.service b/deploy/systemd/coulobre-dns-apply@.service new file mode 100644 index 0000000..fc93753 --- /dev/null +++ b/deploy/systemd/coulobre-dns-apply@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre local BIND9 publishing request +After=named.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-dns-node apply-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +ReadWritePaths=/etc/bind/coulobre diff --git a/docs/development.md b/docs/development.md index e2b6e69..d257c6a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -273,6 +273,28 @@ it again. Coulobre checks the SOA serial, reloads the individual zone, and waits for BIND9 to report the requested serial. Reapply the same manifest to resume after an interrupted reload. See the [BIND9 command reference](https://bind9.readthedocs.io/en/v9.18.39/manpages.html#rndc) and [RFC 1982](https://www.rfc-editor.org/rfc/rfc1982.html). +### Enable local DNS publishing + +On a BIND9 node with the same RNDC setup, install Coulobre in a root-owned +virtual environment at `/opt/coulobre`. Create the managed zone directory and +enable the publishing socket. + +```sh +getent group coulobre-dns-provisioning >/dev/null || sudo groupadd --system coulobre-dns-provisioning +sudo install -d -o root -g root -m 0755 /etc/bind/coulobre +sudo install -m 0644 deploy/systemd/coulobre-dns-apply.socket \ + deploy/systemd/coulobre-dns-apply@.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-dns-apply.socket +``` + +Grant the socket group only to the service identity responsible for publishing +zones. Send one version 1 or 2 zone manifest as UTF-8 JSON to +`/run/coulobre-dns-apply.sock`, with a limit of 1 MiB. Shut down the writing +half of the connection and read the JSON reply to EOF. For a valid manifest, +the reply identifies the domain and SOA serial. A `configured` reply means +BIND9 has loaded that serial. A `failed` reply includes a diagnostic. + ## Request a virtual mailbox Open a hosting account and select **Request mailbox**. Enter the part before diff --git a/src/coulobre/dns_node.py b/src/coulobre/dns_node.py index e6a2922..506dc9f 100644 --- a/src/coulobre/dns_node.py +++ b/src/coulobre/dns_node.py @@ -9,12 +9,14 @@ from pathlib import Path import idna from .domain_names import canonical_domain +from .node_requests import serve_apply_request BASE_MANIFEST_VERSION = 1 MAIL_RECORD_MANIFEST_VERSION = 2 MANIFEST_KIND = "bind9_zone" MAX_SOA_SERIAL = 2**32 - 1 TXT_CHUNK_SIZE = 255 +DNS_REQUEST_LIMIT = 1024 * 1024 def dns_name(value): @@ -254,19 +256,27 @@ class DnsZone: txt_records=read_records(data, "txt_records", TxtRecord), ) - def manifest(self): - manifest = { - "version": BASE_MANIFEST_VERSION, + def manifest_identity(self): + version = ( + MAIL_RECORD_MANIFEST_VERSION + if self.mx_records or self.txt_records + else BASE_MANIFEST_VERSION + ) + return { + "version": version, "kind": MANIFEST_KIND, "domain": self.domain, "serial": self.serial, + } + + def manifest(self): + manifest = self.manifest_identity() | { "nameservers": list(self.nameservers), "responsible_name": self.responsible_name, "addresses": [asdict(record) for record in self.addresses], } - if self.mx_records or self.txt_records: + if manifest["version"] == MAIL_RECORD_MANIFEST_VERSION: 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], ) @@ -296,8 +306,23 @@ def main(argv=None): render.add_argument("manifest", type=Path) apply = commands.add_parser("apply", help="Install or update a primary BIND9 zone.") apply.add_argument("manifest", type=Path) + commands.add_parser( + "apply-request", + help="Publish one BIND9 manifest from standard input and report JSON.", + ) args = parser.parse_args(argv) + if args.command == "apply-request": + from .dns_node_apply import apply_zone + + return serve_apply_request( + BASE_MANIFEST_VERSION, + DnsZone.from_manifest, + apply_zone, + limit=DNS_REQUEST_LIMIT, + identity=DnsZone.manifest_identity, + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) zone = DnsZone.from_manifest(payload) diff --git a/src/coulobre/hosting/test_dns_node.py b/src/coulobre/hosting/test_dns_node.py index 8ee90ff..f7ef92f 100644 --- a/src/coulobre/hosting/test_dns_node.py +++ b/src/coulobre/hosting/test_dns_node.py @@ -1,12 +1,14 @@ import json from contextlib import redirect_stderr, redirect_stdout -from io import StringIO +from io import BytesIO, StringIO from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.dns_node import DnsZone, TxtRecord, main +from coulobre.dns_node import DNS_REQUEST_LIMIT, DnsZone, TxtRecord, main class DnsZoneManifestTests(SimpleTestCase): @@ -170,3 +172,40 @@ class DnsZoneManifestTests(SimpleTestCase): f'{owner}. IN TXT "{"x" * 254}\\195" "\\169\\034\\092\\010"', ) self.assertEqual(TxtRecord(owner, "").render(), f'{owner}. IN TXT ""') + + def test_apply_request_accepts_a_large_zone_and_returns_only_its_identity(self): + manifest = self.manifest | { + "version": 2, + "mx_records": [], + "txt_records": [ + {"name": f"txt{index}.bücher.example", "text": "x" * 256} + for index in range(30) + ], + } + output = self.enterContext(redirect_stdout(StringIO())) + apply = self.enterContext(patch("coulobre.dns_node_apply.apply_zone")) + body = json.dumps(manifest).encode("utf-8") + self.assertGreater(len(body), 4096) + with patch("sys.stdin", SimpleNamespace(buffer=BytesIO(body))): + self.assertEqual(main(["apply-request"]), 0) + apply.assert_called_once_with(DnsZone.from_manifest(manifest)) + self.assertEqual( + json.loads(output.getvalue()), + { + "version": 2, + "kind": "bind9_zone", + "domain": "xn--bcher-kva.example", + "serial": 3, + "state": "configured", + "problem": None, + }, + ) + + def test_apply_request_rejects_oversized_input_before_touching_bind(self): + output = self.enterContext(redirect_stdout(StringIO())) + apply = self.enterContext(patch("coulobre.dns_node_apply.apply_zone")) + body = b" " * (DNS_REQUEST_LIMIT + 1) + with patch("sys.stdin", SimpleNamespace(buffer=BytesIO(body))): + self.assertEqual(main(["apply-request"]), 1) + apply.assert_not_called() + self.assertIn("exceeds", json.loads(output.getvalue())["problem"]) diff --git a/src/coulobre/node_requests.py b/src/coulobre/node_requests.py index 7055796..50803db 100644 --- a/src/coulobre/node_requests.py +++ b/src/coulobre/node_requests.py @@ -4,18 +4,20 @@ import sys MAX_REQUEST_BYTES = 4096 -def serve_apply_request(manifest_version, parse_manifest, apply): +def serve_apply_request( + manifest_version, parse_manifest, apply, *, limit=MAX_REQUEST_BYTES, identity=None +): report = {"version": manifest_version} try: - body = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1) - if len(body) > MAX_REQUEST_BYTES: - raise ValueError(f"The manifest exceeds {MAX_REQUEST_BYTES} bytes.") + body = sys.stdin.buffer.read(limit + 1) + if len(body) > limit: + raise ValueError(f"The manifest exceeds {limit} bytes.") try: payload = json.loads(body.decode("utf-8")) except (ValueError, RecursionError): raise ValueError("Expected a UTF-8 JSON manifest.") from None spec = parse_manifest(payload) - report = spec.manifest() + report = spec.manifest() if identity is None else identity(spec) apply(spec) except (OSError, ValueError) as error: print(json.dumps({**report, "state": "failed", "problem": str(error)})) -- 2.43.0 From 70cb4de81b84ebc80fe63ecbb06d1ed5d6bd12f1 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 01:41:06 +0100 Subject: [PATCH 2/2] Publish local BIND9 zones from the panel --- deploy/panel.env.example | 1 + deploy/systemd/coulobre-dns-publisher.service | 26 +++ docs/deployment.md | 31 ++++ src/coulobre/hosting/dns_publication.py | 32 ++++ .../migrations/0015_dns_publication.py | 53 ++++++ src/coulobre/hosting/models.py | 29 ++-- src/coulobre/hosting/node_client.py | 26 ++- src/coulobre/hosting/tasks.py | 45 +++++- .../templates/hosting/account_detail.html | 12 +- .../templates/hosting/dns_publication.html | 24 +++ src/coulobre/hosting/test_dns_publication.py | 152 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 26 ++- src/coulobre/settings.py | 7 + 14 files changed, 450 insertions(+), 19 deletions(-) create mode 100644 deploy/systemd/coulobre-dns-publisher.service create mode 100644 src/coulobre/hosting/dns_publication.py create mode 100644 src/coulobre/hosting/migrations/0015_dns_publication.py create mode 100644 src/coulobre/hosting/templates/hosting/dns_publication.html create mode 100644 src/coulobre/hosting/test_dns_publication.py diff --git a/deploy/panel.env.example b/deploy/panel.env.example index c276f0d..4a7b1ef 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -10,3 +10,4 @@ COULOBRE_DB_HOST=/run/mysqld/mysqld.sock COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_LOCAL_WEB_ACTIVATION=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1 +# COULOBRE_LOCAL_DNS_PUBLISHING=1 diff --git a/deploy/systemd/coulobre-dns-publisher.service b/deploy/systemd/coulobre-dns-publisher.service new file mode 100644 index 0000000..1c5d026 --- /dev/null +++ b/deploy/systemd/coulobre-dns-publisher.service @@ -0,0 +1,26 @@ +[Unit] +Description=Coulobre Panel local BIND9 publishing worker +Requires=coulobre-dns-apply.socket +Wants=network-online.target +After=network-online.target coulobre-dns-apply.socket mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-dns-publisher +Group=coulobre-dns-publisher +SupplementaryGroups=coulobre-dns-provisioning +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-dns-publishing --hostname=dns-publisher@%H --concurrency=1 +KillMode=mixed +TimeoutStopSec=4min +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/docs/deployment.md b/docs/deployment.md index 5a5057e..6132a21 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -242,3 +242,34 @@ database requests and the **Can add database provisioning** permission. The MariaDB node stores the application login in the root-only file `/var/lib/coulobre/database-node/.json`. Use the credentials from that file when configuring the hosted application. + +## Publish local DNS zones from the panel + +Enable the [DNS publishing socket](development.md#enable-local-dns-publishing) +on the panel host. Install the BIND9 publishing worker under a dedicated +identity with access to that socket. + +```sh +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin coulobre-dns-publisher +sudo install -m 0644 deploy/systemd/coulobre-dns-publisher.service /etc/systemd/system/ +sudo systemctl daemon-reload +``` + +Set `COULOBRE_LOCAL_DNS_PUBLISHING=1` in `/etc/coulobre/panel.env`, then apply +pending migrations and restart the panel services. + +```sh +panel_manage migrate --noinput +sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat +sudo systemctl enable --now coulobre-dns-publisher.service +``` + +Open a hosting account and select **Publish zone**. Reload the account page to +see progress and the last SOA serial confirmed by the local BIND9 node. +Operators need permission to view hosting accounts and DNS zones and the +**Can add DNS publication** permission. + +Each request captures the reviewed SOA serial and records. You can edit the +zone while it publishes. Publish the newer revision after the current request +finishes. Use **Retry publishing** if the current revision failed. diff --git a/src/coulobre/hosting/dns_publication.py b/src/coulobre/hosting/dns_publication.py new file mode 100644 index 0000000..c4e0028 --- /dev/null +++ b/src/coulobre/hosting/dns_publication.py @@ -0,0 +1,32 @@ +from django.db import connection, transaction +from django.db.models import F + +from coulobre.dns_node import DNS_REQUEST_LIMIT + +from .models import DnsPublication, HostingDnsZone +from .node_client import encode_manifest + + +@transaction.atomic +def queue_dns_publication(zone_id, expected_serial): + zones = HostingDnsZone.objects.filter(pk=zone_id) + if connection.vendor == "sqlite": + # Acquire the write lock before reading the revision to publish. + zones.update(serial=F("serial")) + zone = zones.select_for_update().get() + if str(zone.serial) != expected_serial: + raise ValueError( + "This zone changed before publication. Reload the account and try again." + ) + manifest = zone.spec.manifest() + if len(encode_manifest(manifest)) > DNS_REQUEST_LIMIT: + raise ValueError("Local DNS publishing accepts zone manifests up to 1 MiB.") + + jobs = DnsPublication.objects + snapshot = {"manifest": manifest, "serial": zone.serial} + job, created = jobs.get_or_create(zone=zone, defaults=snapshot) + if not created: + jobs.requeue( + jobs.filter(pk=job.pk).exclude(serial=zone.serial, problem=""), **snapshot + ) + return zone diff --git a/src/coulobre/hosting/migrations/0015_dns_publication.py b/src/coulobre/hosting/migrations/0015_dns_publication.py new file mode 100644 index 0000000..ae4a0f5 --- /dev/null +++ b/src/coulobre/hosting/migrations/0015_dns_publication.py @@ -0,0 +1,53 @@ +# Generated by Django 5.2.19 on 2026-11-21 00:33 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0014_database_provisioning"), + ] + + operations = [ + migrations.CreateModel( + name="DnsPublication", + 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)), + ("manifest", models.JSONField()), + ("serial", models.PositiveBigIntegerField()), + ( + "published_serial", + models.PositiveBigIntegerField(blank=True, null=True), + ), + ( + "zone", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="publication", + to="hosting.hostingdnszone", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 42844a8..5af1288 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -229,15 +229,17 @@ class ProvisioningJobManager(models.Manager): def queue(self, **target): job, created = self.get_or_create(**target) if not created: - self.filter(pk=job.pk, finished_at__isnull=False).exclude( - problem="" - ).update( - requested_at=timezone.now(), - last_dispatched_at=None, - started_at=None, - finished_at=None, - problem="", - ) + self.requeue(self.filter(pk=job.pk).exclude(problem="")) + + def requeue(self, jobs, **updates): + jobs.filter(finished_at__isnull=False).update( + requested_at=timezone.now(), + last_dispatched_at=None, + started_at=None, + finished_at=None, + problem="", + **updates, + ) class ProvisioningJob(models.Model): @@ -268,3 +270,12 @@ class DatabaseProvisioning(ProvisioningJob): database = models.OneToOneField( HostingDatabase, on_delete=models.CASCADE, related_name="provisioning" ) + + +class DnsPublication(ProvisioningJob): + zone = models.OneToOneField( + HostingDnsZone, on_delete=models.CASCADE, related_name="publication" + ) + manifest = models.JSONField() + serial = models.PositiveBigIntegerField() + published_serial = models.PositiveBigIntegerField(null=True, blank=True) diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index e003383..a12b601 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -14,12 +14,27 @@ def provision_local_database(database): ) -def apply_on_local_node(spec, socket_path, node, resource): +def publish_local_zone(zone): + apply_on_local_node( + zone, + "/run/coulobre-dns-apply.sock", + "BIND9 node", + "zone", + identity=zone.manifest_identity(), + ) + + +def encode_manifest(manifest): + return json.dumps(manifest).encode("utf-8") + + +def apply_on_local_node(spec, socket_path, node, resource, *, identity=None): manifest = spec.manifest() + expected = manifest if identity is None else identity with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: client.settimeout(195) client.connect(socket_path) - client.sendall(json.dumps(manifest).encode("utf-8")) + client.sendall(encode_manifest(manifest)) client.shutdown(socket.SHUT_WR) with client.makefile("rb") as response: body = response.read(RESPONSE_LIMIT + 1) @@ -29,11 +44,14 @@ def apply_on_local_node(spec, socket_path, node, resource): invalid_response = f"The {node} returned an invalid response for this {resource}." try: reply = json.loads(body.decode("utf-8")) - reply_spec = type(spec).from_manifest({key: reply[key] for key in manifest}) state, problem = reply["state"], reply["problem"] + matches = all( + type(reply.get(key)) is type(value) and reply[key] == value + for key, value in expected.items() + ) except (KeyError, TypeError, ValueError, RecursionError): raise ValueError(invalid_response) from None - if reply_spec == spec: + if matches: if state == "configured" and problem is None: return if state == "failed" and isinstance(problem, str) and problem.strip(): diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 5181308..792b3ff 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -5,14 +5,25 @@ from django.conf import settings from django.db.models import Q from django.utils import timezone +from coulobre.dns_node import DnsZone from coulobre.web_node import WebSite -from .models import DatabaseProvisioning, WebActivation, WebProvisioningPlan -from .node_client import activate_local_site, provision_local_database +from .models import ( + DatabaseProvisioning, + DnsPublication, + WebActivation, + WebProvisioningPlan, +) +from .node_client import ( + activate_local_site, + provision_local_database, + publish_local_zone, +) REDISPATCH_AFTER = timedelta(minutes=5) WEB_ACTIVATION_QUEUE = "coulobre-web-activation" DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning" +DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing" @shared_task @@ -61,6 +72,14 @@ def dispatch_database_provisioning(): ) +@shared_task +def dispatch_dns_publications(): + if settings.LOCAL_DNS_PUBLISHING: + dispatch_provisioning_jobs( + DnsPublication, publish_dns_zone, DNS_PUBLISHING_QUEUE + ) + + def dispatch_provisioning_jobs(model, task, queue): stale_before = timezone.now() - REDISPATCH_AFTER waiting = model.objects.filter(finished_at__isnull=True) @@ -114,6 +133,23 @@ def apply_database_provisioning(provisioning): provision_local_database(provisioning.database.spec) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def publish_dns_zone(publication_id): + if settings.LOCAL_DNS_PUBLISHING: + run_provisioning_job( + DnsPublication.objects.all(), + publication_id, + apply_dns_publication, + "Could not complete the request to the local BIND9 node. Check its socket and try again.", + ) + + +def apply_dns_publication(publication): + zone = DnsZone.from_manifest(publication.manifest) + publish_local_zone(zone) + return {"published_serial": zone.serial} + + def run_provisioning_job(jobs, job_id, apply, connection_problem): started_at = timezone.now() pending = jobs.filter(pk=job_id, finished_at__isnull=True) @@ -128,10 +164,11 @@ def run_provisioning_job(jobs, job_id, apply, connection_problem): if job is None: return problem = "" + updates = {} try: - apply(job) + updates = apply(job) or {} except OSError: problem = connection_problem except ValueError as error: problem = str(error) - running.update(finished_at=timezone.now(), problem=problem) + running.update(finished_at=timezone.now(), problem=problem, **updates) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index ba38818..480b385 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -114,7 +114,17 @@ {{ zone.serial }} {% if is_operator %} - Download manifest + +
+ Download manifest + {% if manage_dns_publishing %} + {% include "hosting/dns_publication.html" with publication=zone.publication %} + {% endif %} +
+ {% if manage_dns_publishing and zone.publication.problem %} +

{{ zone.publication.problem }}

+ {% endif %} + {% endif %} {% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/dns_publication.html b/src/coulobre/hosting/templates/hosting/dns_publication.html new file mode 100644 index 0000000..b7b6ae5 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/dns_publication.html @@ -0,0 +1,24 @@ +{% load l10n %} +{% if publication and publication.published_serial is not None %} + Published SOA serial {{ publication.published_serial }} +{% endif %} +{% if publication.state == "failed" %} + Publishing failed for serial {{ publication.serial }} +{% elif publication.state == "running" %} + Publishing serial {{ publication.serial }} +{% elif publication.state == "queued" %} + Queued serial {{ publication.serial }} +{% endif %} +{% if local_dns_enabled %} + {% if not publication or publication.finished_at and publication.published_serial != zone.serial %} +
+ {% csrf_token %} + + {% if publication.state == "failed" and publication.serial == zone.serial %} + + {% else %} + + {% endif %} +
+ {% endif %} +{% endif %} diff --git a/src/coulobre/hosting/test_dns_publication.py b/src/coulobre/hosting/test_dns_publication.py new file mode 100644 index 0000000..5952688 --- /dev/null +++ b/src/coulobre/hosting/test_dns_publication.py @@ -0,0 +1,152 @@ +import json +from io import BytesIO +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse + +from coulobre.dns_node import DnsZone + +from .models import Customer, DnsPublication, HostingAccount, HostingDnsZone +from .node_client import publish_local_zone +from .tasks import dispatch_dns_publications, publish_dns_zone + + +@override_settings(LOCAL_DNS_PUBLISHING=True) +class DnsPublicationTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.customer = users.create_user("customer") + cls.customer.user_permissions.add( + *Permission.objects.filter(content_type__app_label="hosting") + ) + cls.account = HostingAccount.objects.create( + name="DNS example", + primary_domain="site.example", + customer=Customer.objects.create(user=cls.customer), + ) + cls.zone = HostingDnsZone.objects.create( + account=cls.account, + domain=cls.account.primary_domain, + nameservers=["ns.provider.example"], + responsible_name="hostmaster.site.example", + addresses=[{"name": "site.example", "address": "192.0.2.1"}], + ) + + def setUp(self): + self.client.force_login(self.operator) + self.url = reverse("panel:dns_zone_publish", args=[self.zone.pk]) + self.detail = self.account.get_absolute_url() + + def test_queued_snapshot_survives_edits_and_the_new_revision_can_publish_next(self): + self.assertContains(self.client.get(self.detail), "Publish zone") + self.assertEqual(self.client.get(self.url).status_code, 405) + for _ in range(2): + self.assertRedirects(self.client.post(self.url, {"serial": 1}), self.detail) + publication = DnsPublication.objects.get(zone=self.zone) + self.assertContains(self.client.get(self.detail), "Queued serial 1") + with patch.object(publish_dns_zone, "apply_async") as send: + dispatch_dns_publications.run() + dispatch_dns_publications.run() + send.assert_called_once_with( + args=[publication.pk], queue="coulobre-dns-publishing", retry=False + ) + + edit = reverse("panel:dns_zone_edit", args=[self.zone.pk]) + self.assertRedirects( + self.client.post( + edit, + { + "serial": 1, + "nameservers": "ns.provider.example", + "responsible_name": "hostmaster.site.example", + "addresses": "site.example 192.0.2.2", + }, + ), + self.detail, + ) + self.zone.refresh_from_db() + self.assertEqual(self.zone.serial, 2) + self.assertEqual(self.client.post(self.url, {"serial": 1}).status_code, 409) + self.client.post(self.url, {"serial": 2}) + publication.refresh_from_db() + self.assertEqual(publication.serial, 1) + + with patch("coulobre.hosting.tasks.publish_local_zone") as apply: + publish_dns_zone.run(publication.pk) + published = apply.call_args.args[0] + self.assertEqual(published.serial, 1) + self.assertEqual(published.addresses[0].address, "192.0.2.1") + detail = self.client.get(self.detail) + self.assertContains(detail, "Published SOA serial 1") + self.assertContains(detail, "Publish zone") + + self.assertRedirects(self.client.post(self.url, {"serial": 2}), self.detail) + publication.refresh_from_db() + self.assertEqual(publication.published_serial, 1) + self.assertEqual(publication.serial, 2) + with patch( + "coulobre.hosting.tasks.publish_local_zone", + side_effect=ValueError("BIND9 rejected the update."), + ): + publish_dns_zone.run(publication.pk) + detail = self.client.get(self.detail) + self.assertContains(detail, "Published SOA serial 1") + self.assertContains(detail, "Publishing failed for serial 2") + self.assertContains(detail, "Retry publishing") + self.assertRedirects(self.client.post(self.url, {"serial": 2}), self.detail) + with patch("coulobre.hosting.tasks.publish_local_zone") as apply: + publish_dns_zone.run(publication.pk) + apply.assert_called_once_with(self.zone.spec) + self.assertContains(self.client.get(self.detail), "Published SOA serial 2") + + def test_customer_and_operator_without_publish_permission_cannot_queue(self): + viewer = get_user_model().objects.create_user("viewer") + viewer.user_permissions.add( + *Permission.objects.filter( + codename__in=("view_hostingaccount", "view_hostingdnszone") + ) + ) + for user in (self.customer, viewer): + with self.subTest(user=user): + self.client.force_login(user) + self.assertNotContains(self.client.get(self.detail), "Publish zone") + self.assertEqual( + self.client.post(self.url, {"serial": 1}).status_code, 403 + ) + self.assertFalse(DnsPublication.objects.exists()) + + @override_settings(LOCAL_DNS_PUBLISHING=False) + def test_disabled_publishing_keeps_manifest_downloads_available(self): + self.assertNotContains(self.client.get(self.detail), "Publish zone") + self.assertEqual(self.client.post(self.url, {"serial": 1}).status_code, 404) + manifest_url = reverse("panel:dns_zone_manifest", args=[self.zone.pk]) + self.assertEqual( + self.client.get(manifest_url).json(), self.zone.spec.manifest() + ) + + +class DnsPublicationSocketTests(SimpleTestCase): + def test_receipt_must_identify_the_exact_soa_serial(self): + zone = DnsZone( + "site.example", 1, ("ns.provider.example",), "hostmaster.site.example" + ) + reply = zone.manifest_identity() | {"state": "configured", "problem": None} + with patch("coulobre.hosting.node_client.socket.socket") as socket: + connection = socket.return_value.__enter__.return_value + read = connection.makefile.return_value.__enter__ + read.side_effect = ( + BytesIO(json.dumps(reply).encode()), + BytesIO(json.dumps(reply | {"serial": True}).encode()), + ) + publish_local_zone(zone) + connection.connect.assert_called_once_with("/run/coulobre-dns-apply.sock") + self.assertEqual( + json.loads(connection.sendall.call_args.args[0]), zone.manifest() + ) + with self.assertRaisesMessage(ValueError, "invalid response for this zone"): + publish_local_zone(zone) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index af31eef..b9a1858 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -52,6 +52,11 @@ urlpatterns = [ views.DownloadDnsZoneManifest.as_view(), name="dns_zone_manifest", ), + path( + "dns-zones//publish/", + views.RequestDnsPublication.as_view(), + name="dns_zone_publish", + ), path( "accounts//mailboxes/new/", views.MailboxCreate.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 5681723..714c400 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -26,6 +26,7 @@ from .access import ( reseller_for_user, ) from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record +from .dns_publication import queue_dns_publication from .models import ( Customer, DatabaseProvisioning, @@ -53,6 +54,7 @@ VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning") +PUBLISH_DNS = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_dnspublication") class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): @@ -198,7 +200,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["local_database_enabled"] = settings.LOCAL_DATABASE_PROVISIONING context["databases"] = databases if tenant or user.has_perm(VIEW_DNS_ZONES): - zones = list(self.object.dns_zones.all()) + zone_list = self.object.dns_zones.all() + if not tenant and user.has_perms(PUBLISH_DNS): + zone_list = zone_list.select_related("publication").defer( + "publication__manifest" + ) + context["manage_dns_publishing"] = True + context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING + zones = list(zone_list) context["dns_zones"] = zones context["has_primary_zone"] = any( zone.domain == self.object.primary_domain for zone in zones @@ -463,6 +472,21 @@ class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View): ) +class RequestDnsPublication(OperatorOnlyMixin, PermissionRequiredMixin, View): + permission_required = PUBLISH_DNS + + def post(self, request, pk): + if not settings.LOCAL_DNS_PUBLISHING: + raise Http404 + try: + zone = queue_dns_publication(pk, request.POST.get("serial")) + except HostingDnsZone.DoesNotExist as error: + raise Http404 from error + except ValueError as error: + return HttpResponse(str(error), status=409, content_type="text/plain") + return redirect(zone.account) + + class MailboxCreate(ResourceRequestCreate): model = HostingMailbox fields = ("local_part",) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 3538c88..34fac6b 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -110,6 +110,7 @@ LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1" LOCAL_DATABASE_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" ) +LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1" CELERY_BEAT_SCHEDULE = { "dispatch-web-provisioning-plans": { "task": "coulobre.hosting.tasks.dispatch_web_plans", @@ -129,3 +130,9 @@ if LOCAL_DATABASE_PROVISIONING: "schedule": 5.0, "options": {"expires": 4.0}, } +if LOCAL_DNS_PUBLISHING: + CELERY_BEAT_SCHEDULE["dispatch-dns-publications"] = { + "task": "coulobre.hosting.tasks.dispatch_dns_publications", + "schedule": 5.0, + "options": {"expires": 4.0}, + } -- 2.43.0