Publish local BIND9 zones from the panel

This commit is contained in:
parkel committed 2026-11-21 01:41:06 +01:00
1 parent 6e075c25f4
commit 70cb4de81b
14 files changed
+450 -19

No files matched your search

+1
View File
@@ -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
@@ -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
+31
View File
@@ -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/<database-name>.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.
+32
View File
@@ -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
@@ -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,
},
),
]
+20 -9
View File
@@ -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)
+22 -4
View File
@@ -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():
+41 -4
View File
@@ -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)
@@ -114,7 +114,17 @@
</td>
<td>{{ zone.serial }}</td>
{% if is_operator %}
<td><a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a></td>
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a>
{% if manage_dns_publishing %}
{% include "hosting/dns_publication.html" with publication=zone.publication %}
{% endif %}
</div>
{% if manage_dns_publishing and zone.publication.problem %}
<p class="heading-meta">{{ zone.publication.problem }}</p>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
@@ -0,0 +1,24 @@
{% load l10n %}
{% if publication and publication.published_serial is not None %}
<span class="status ready">Published SOA serial {{ publication.published_serial }}</span>
{% endif %}
{% if publication.state == "failed" %}
<span class="status suspended">Publishing failed for serial {{ publication.serial }}</span>
{% elif publication.state == "running" %}
<span class="status pending">Publishing serial {{ publication.serial }}</span>
{% elif publication.state == "queued" %}
<span class="status pending">Queued serial {{ publication.serial }}</span>
{% endif %}
{% if local_dns_enabled %}
{% if not publication or publication.finished_at and publication.published_serial != zone.serial %}
<form method="post" action="{% url 'panel:dns_zone_publish' zone.pk %}">
{% csrf_token %}
<input type="hidden" name="serial" value="{{ zone.serial|unlocalize }}">
{% if publication.state == "failed" and publication.serial == zone.serial %}
<button class="button secondary" type="submit" aria-label="Retry publishing {{ zone.domain }}">Retry publishing</button>
{% else %}
<button class="button secondary" type="submit" aria-label="Publish zone {{ zone.domain }}">Publish zone</button>
{% endif %}
</form>
{% endif %}
{% endif %}
@@ -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)
+5
View File
@@ -52,6 +52,11 @@ urlpatterns = [
views.DownloadDnsZoneManifest.as_view(),
name="dns_zone_manifest",
),
path(
"dns-zones/<int:pk>/publish/",
views.RequestDnsPublication.as_view(),
name="dns_zone_publish",
),
path(
"accounts/<int:pk>/mailboxes/new/",
views.MailboxCreate.as_view(),
+25 -1
View File
@@ -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",)
+7
View File
@@ -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},
}