Add BIND9 DNS zone management and provisioning #6
No files matched your search
@@ -108,6 +108,74 @@ message when the installation needs attention.
|
||||
Exit code `1` indicates an invalid manifest or an unavailable check, for example
|
||||
when the MariaDB administrative connection fails.
|
||||
|
||||
## Render a BIND9 zone
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
A manifest can also be written directly for local testing. Save the
|
||||
following example as `coulobre-zone.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"kind": "bind9_zone",
|
||||
"domain": "example.net",
|
||||
"serial": 1,
|
||||
"nameservers": ["ns1.example.net", "ns2.provider.example"],
|
||||
"responsible_name": "hostmaster.example.net",
|
||||
"addresses": [
|
||||
{"name": "example.net", "address": "192.0.2.20"},
|
||||
{"name": "ns1.example.net", "address": "192.0.2.53"},
|
||||
{"name": "www.example.net", "address": "2001:db8::20"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The first nameserver is the SOA primary. Supply addresses for nameservers
|
||||
inside the zone. Use fully qualified names in `addresses` and DNS mailbox
|
||||
notation for `responsible_name`, such as `hostmaster.example.net` for
|
||||
`hostmaster@example.net`. Increment the SOA serial when editing a manifest
|
||||
by hand.
|
||||
|
||||
Render the zone file and validate it with the `named-checkzone` utility
|
||||
provided by the Ubuntu `bind9-utils` package. The rendered zone is written to
|
||||
standard output. See the [BIND9 command reference](https://bind9.readthedocs.io/en/stable/manpages.html#named-checkzone).
|
||||
|
||||
```sh
|
||||
coulobre-dns-node render coulobre-zone.json > db.example.net
|
||||
named-checkzone example.net db.example.net
|
||||
```
|
||||
|
||||
### Apply a zone manifest
|
||||
|
||||
Install `bind9` and `bind9-utils` on an Ubuntu DNS node. Use BIND9's default
|
||||
IN view and enable `allow-new-zones yes;` in the existing `options` block.
|
||||
On an authoritative-only DNS node, set `recursion no;` and configure
|
||||
`allow-transfer` to match your secondary servers. Set
|
||||
`allow-transfer { none; };` on a standalone server. Verify that the local
|
||||
RNDC control channel is available after applying your BIND9 configuration.
|
||||
|
||||
```sh
|
||||
sudo rndc -s 127.0.0.1 status
|
||||
sudo /opt/coulobre/bin/coulobre-dns-node apply coulobre-zone.json
|
||||
```
|
||||
|
||||
Coulobre validates the zone with `named-checkzone` and installs it under
|
||||
`/etc/bind/coulobre/`. BIND9 persists the primary zone registration through
|
||||
`rndc addzone`. To publish an edit, download the updated manifest and apply
|
||||
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).
|
||||
|
||||
## Request an Apache configuration preview
|
||||
|
||||
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
||||
|
||||
@@ -17,6 +17,7 @@ dependencies = [
|
||||
|
||||
[project.scripts]
|
||||
coulobre-database-node = "coulobre.database_node:main"
|
||||
coulobre-dns-node = "coulobre.dns_node:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .domain_names import canonical_domain
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_KIND = "bind9_zone"
|
||||
MAX_SOA_SERIAL = 2**32 - 1
|
||||
|
||||
|
||||
def dns_name(value):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("Enter a valid domain name.")
|
||||
return canonical_domain(value)
|
||||
|
||||
|
||||
def in_zone(name, domain):
|
||||
return name == domain or name.endswith(f".{domain}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AddressRecord:
|
||||
name: str
|
||||
address: str
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "name", dns_name(self.name))
|
||||
try:
|
||||
if not isinstance(self.address, str) or "%" in self.address:
|
||||
raise ValueError
|
||||
address = ipaddress.ip_address(self.address)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
"Enter an IPv4 or IPv6 address without a zone identifier."
|
||||
) from None
|
||||
object.__setattr__(self, "address", str(address))
|
||||
|
||||
@property
|
||||
def record_type(self):
|
||||
return "AAAA" if ":" in self.address else "A"
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if not isinstance(data, dict) or data.keys() != {"name", "address"}:
|
||||
raise ValueError("Expected an address record with a name and IP address.")
|
||||
return cls(data["name"], data["address"])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DnsZone:
|
||||
domain: str
|
||||
serial: int
|
||||
nameservers: tuple[str, ...]
|
||||
responsible_name: str
|
||||
addresses: tuple[AddressRecord, ...] = ()
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "domain", dns_name(self.domain))
|
||||
object.__setattr__(self, "responsible_name", dns_name(self.responsible_name))
|
||||
if type(self.serial) is not int or not 0 <= self.serial <= MAX_SOA_SERIAL:
|
||||
raise ValueError("The SOA serial must be an unsigned 32-bit integer.")
|
||||
nameservers = tuple(dns_name(name) for name in self.nameservers)
|
||||
if not nameservers or len(set(nameservers)) != len(nameservers):
|
||||
raise ValueError("Supply at least one nameserver and list each name once.")
|
||||
object.__setattr__(self, "nameservers", nameservers)
|
||||
|
||||
address_names = {record.name for record in self.addresses}
|
||||
if any(not in_zone(name, self.domain) for name in address_names):
|
||||
raise ValueError("Address records must belong to the zone.")
|
||||
if any(
|
||||
in_zone(name, self.domain) and name not in address_names
|
||||
for name in nameservers
|
||||
):
|
||||
raise ValueError("Each in-zone nameserver needs an address record.")
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if not isinstance(data, dict) or data.keys() != {
|
||||
"version",
|
||||
"kind",
|
||||
"domain",
|
||||
"serial",
|
||||
"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:
|
||||
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"]
|
||||
),
|
||||
)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"version": 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
|
||||
],
|
||||
}
|
||||
|
||||
def render(self):
|
||||
lines = [
|
||||
f"$ORIGIN {self.domain}.",
|
||||
"$TTL 3600",
|
||||
f"@ IN SOA {self.nameservers[0]}. {self.responsible_name}. "
|
||||
f"{self.serial} 3600 600 1209600 300",
|
||||
]
|
||||
lines.extend(f"@ IN NS {name}." for name in self.nameservers)
|
||||
lines.extend(
|
||||
f"{record.name}. IN {record.record_type} {record.address}"
|
||||
for record in self.addresses
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-dns-node")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
render = commands.add_parser("render", help="Render a BIND9 zone from a manifest.")
|
||||
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)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
|
||||
zone = DnsZone.from_manifest(payload)
|
||||
if args.command == "apply":
|
||||
from .dns_node_apply import apply_zone
|
||||
|
||||
apply_zone(zone)
|
||||
print(f"Applied BIND9 zone {zone.domain} at SOA serial {zone.serial}.")
|
||||
else:
|
||||
sys.stdout.write(zone.render())
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"coulobre-dns-node: {error}\n")
|
||||
|
||||
return 0
|
||||
@@ -0,0 +1,151 @@
|
||||
import fcntl
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .dns_node import MAX_SOA_SERIAL
|
||||
from .node_files import read_root_file, require_root_directory, write_new_file
|
||||
|
||||
ZONE_DIRECTORY = Path("/etc/bind/coulobre")
|
||||
RNDC = ("rndc", "-s", "127.0.0.1")
|
||||
|
||||
|
||||
def apply_zone(zone):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run apply as root on the BIND9 node.")
|
||||
require_root_directory(ZONE_DIRECTORY, create_mode=0o755)
|
||||
directory = os.open(ZONE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
fcntl.flock(directory, fcntl.LOCK_EX)
|
||||
install_zone(zone, ZONE_DIRECTORY / zone.domain, directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def install_zone(zone, path, directory):
|
||||
domain = zone.domain
|
||||
config = f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
|
||||
registered = check_registration(domain, config)
|
||||
wanted = zone_file(zone)
|
||||
previous = read_root_file(path, mode=0o644) if os.path.lexists(path) else None
|
||||
loaded = None
|
||||
if registered:
|
||||
if previous is None:
|
||||
raise ValueError("The registered zone is missing its managed zone file.")
|
||||
loaded = active_serial(domain)
|
||||
|
||||
if previous is not None:
|
||||
saved = file_serial(domain, previous)
|
||||
if (
|
||||
loaded is not None
|
||||
and loaded != saved
|
||||
and not serial_is_newer(saved, loaded)
|
||||
):
|
||||
raise ValueError("The loaded SOA serial is ahead of the managed zone file.")
|
||||
if wanted != previous and (
|
||||
not serial_is_newer(zone.serial, saved)
|
||||
or (loaded is not None and not serial_is_newer(zone.serial, loaded))
|
||||
):
|
||||
raise ValueError(
|
||||
"The manifest needs a newer SOA serial than the managed file and loaded zone."
|
||||
)
|
||||
|
||||
if wanted != previous:
|
||||
install_zone_file(domain, path, wanted)
|
||||
if registered and loaded == zone.serial:
|
||||
return
|
||||
|
||||
os.fsync(directory)
|
||||
if registered:
|
||||
run(*RNDC, "reload", domain)
|
||||
else:
|
||||
run(*RNDC, "addzone", domain, config)
|
||||
wait_for_serial(domain, zone.serial)
|
||||
|
||||
|
||||
def check_registration(domain, config):
|
||||
missing = (
|
||||
f"rndc: 'showzone' failed: not found\nno matching zone '{domain}' in any view"
|
||||
)
|
||||
shown = run(*RNDC, "showzone", domain, allow_error=missing)
|
||||
if shown is None:
|
||||
return False
|
||||
if " ".join(shown.split()) != f'zone "{domain}" {config}':
|
||||
raise ValueError(
|
||||
"BIND9 already has a zone outside Coulobre's managed configuration."
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def zone_file(zone):
|
||||
content = zone.render()
|
||||
header = f"; Coulobre zone {zone.domain} {zone.serial}"
|
||||
digest = hashlib.sha256(f"{header}\n{content}".encode("utf-8")).hexdigest()
|
||||
return f"{header} {digest}\n{content}"
|
||||
|
||||
|
||||
def file_serial(domain, zone_text):
|
||||
header, _, content = zone_text.partition("\n")
|
||||
metadata, _, checksum = header.rpartition(" ")
|
||||
matched = re.fullmatch(
|
||||
rf"; Coulobre zone {re.escape(domain)} ([0-9]{{1,10}})", metadata
|
||||
)
|
||||
digest = hashlib.sha256(f"{metadata}\n{content}".encode("utf-8")).hexdigest()
|
||||
if matched is None or checksum != digest or int(matched[1]) > MAX_SOA_SERIAL:
|
||||
raise ValueError("The existing zone file is unmanaged or has been modified.")
|
||||
return int(matched[1])
|
||||
|
||||
|
||||
def serial_is_newer(candidate, previous):
|
||||
# RFC 1982 compares serials over the forward half of the 32-bit range.
|
||||
distance = (candidate - previous) % (MAX_SOA_SERIAL + 1)
|
||||
return 0 < distance < 2**31
|
||||
|
||||
|
||||
def install_zone_file(domain, path, content):
|
||||
with TemporaryDirectory(dir=path.parent) as scratch:
|
||||
staged = Path(scratch) / "zone"
|
||||
write_new_file(staged, content, mode=0o644)
|
||||
run("named-checkzone", "-i", "local", domain, str(staged))
|
||||
os.replace(staged, path)
|
||||
|
||||
|
||||
def active_serial(domain):
|
||||
result = run(*RNDC, "zonestatus", domain)
|
||||
match = re.search(r"^serial: ([0-9]{1,10})$", result, re.MULTILINE)
|
||||
if match is None or int(match[1]) > MAX_SOA_SERIAL:
|
||||
raise ValueError("BIND9 did not report a loaded SOA serial.")
|
||||
return int(match[1])
|
||||
|
||||
|
||||
def wait_for_serial(domain, serial):
|
||||
for _ in range(20):
|
||||
if active_serial(domain) == serial:
|
||||
return
|
||||
time.sleep(0.25)
|
||||
raise ValueError(
|
||||
f"BIND9 has not loaded SOA serial {serial}. Reapply the manifest to retry."
|
||||
)
|
||||
|
||||
|
||||
def run(*command, allow_error=None):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
command,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"},
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ValueError(f"{command[0]} timed out.") from None
|
||||
if result.returncode:
|
||||
details = result.stderr.strip() or result.stdout.strip()
|
||||
if details == allow_error:
|
||||
return None
|
||||
raise ValueError(f"{command[0]} failed ({result.returncode}). {details}")
|
||||
return result.stdout.strip()
|
||||
@@ -0,0 +1,67 @@
|
||||
from django import forms
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone
|
||||
|
||||
|
||||
class DnsZoneForm(forms.Form):
|
||||
nameservers = forms.CharField(
|
||||
widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}),
|
||||
help_text="Enter one hostname per line. The first is the SOA primary.",
|
||||
)
|
||||
responsible_name = forms.CharField(
|
||||
label="SOA mailbox",
|
||||
max_length=253,
|
||||
help_text="Use DNS mailbox notation, such as hostmaster.example.net.",
|
||||
)
|
||||
addresses = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}),
|
||||
help_text="Enter a fully qualified name and an IPv4 or IPv6 address on each line.",
|
||||
)
|
||||
|
||||
def __init__(self, *args, domain, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
def clean_addresses(self):
|
||||
records = []
|
||||
for number, line in enumerate(self.cleaned_data["addresses"].splitlines(), 1):
|
||||
if not line.strip():
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) != 2:
|
||||
raise forms.ValidationError(
|
||||
f"Enter a name and an IP address on line {number}."
|
||||
)
|
||||
try:
|
||||
records.append(AddressRecord(*parts))
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(f"Line {number}. {error}") from error
|
||||
return tuple(records)
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if self.errors:
|
||||
return data
|
||||
try:
|
||||
spec = DnsZone(
|
||||
domain=self.domain,
|
||||
serial=data.get("serial", 1),
|
||||
nameservers=tuple(data["nameservers"].split()),
|
||||
responsible_name=data["responsible_name"],
|
||||
addresses=data["addresses"],
|
||||
)
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(str(error)) from error
|
||||
data.update(
|
||||
nameservers=list(spec.nameservers),
|
||||
responsible_name=spec.responsible_name,
|
||||
addresses=spec.manifest()["addresses"],
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
class DnsZoneEditForm(DnsZoneForm):
|
||||
serial = forms.IntegerField(
|
||||
min_value=0, max_value=MAX_SOA_SERIAL, widget=forms.HiddenInput
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-19 22:08
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
import coulobre.hosting.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0006_hostingdatabase"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="HostingDnsZone",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"domain",
|
||||
coulobre.hosting.fields.DomainNameField(
|
||||
max_length=253, unique=True
|
||||
),
|
||||
),
|
||||
("serial", models.PositiveBigIntegerField(default=1)),
|
||||
("nameservers", models.JSONField()),
|
||||
(
|
||||
"responsible_name",
|
||||
coulobre.hosting.fields.DomainNameField(max_length=253),
|
||||
),
|
||||
("addresses", models.JSONField(default=list)),
|
||||
(
|
||||
"account",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.PROTECT,
|
||||
related_name="dns_zones",
|
||||
to="hosting.hostingaccount",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("domain",),
|
||||
"constraints": [
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(("serial__lte", 4294967295)),
|
||||
name="hosting_dns_zone_valid_serial",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -4,6 +4,7 @@ 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 .fields import DomainNameField
|
||||
|
||||
@@ -82,6 +83,41 @@ class HostingDatabase(models.Model):
|
||||
return self.spec.name
|
||||
|
||||
|
||||
class HostingDnsZone(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="dns_zones"
|
||||
)
|
||||
domain = DomainNameField(max_length=253, unique=True)
|
||||
serial = models.PositiveBigIntegerField(default=1)
|
||||
nameservers = models.JSONField()
|
||||
responsible_name = DomainNameField(max_length=253)
|
||||
addresses = models.JSONField(default=list)
|
||||
|
||||
class Meta:
|
||||
ordering = ("domain",)
|
||||
constraints = [
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(serial__lte=MAX_SOA_SERIAL),
|
||||
name="hosting_dns_zone_valid_serial",
|
||||
)
|
||||
]
|
||||
|
||||
@property
|
||||
def spec(self):
|
||||
return DnsZone(
|
||||
domain=self.domain,
|
||||
serial=self.serial,
|
||||
nameservers=tuple(self.nameservers),
|
||||
responsible_name=self.responsible_name,
|
||||
addresses=tuple(
|
||||
AddressRecord.from_manifest(item) for item in self.addresses
|
||||
),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.domain)
|
||||
|
||||
|
||||
class WebProvisioningPlan(models.Model):
|
||||
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
|
||||
primary_domain = DomainNameField(max_length=253)
|
||||
|
||||
@@ -29,7 +29,7 @@ a {
|
||||
text-underline-offset: 0.2em;
|
||||
}
|
||||
|
||||
button, input, select {
|
||||
button, input, select, textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
@@ -296,9 +296,8 @@ h2 {
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
input:not([type="hidden"]), select {
|
||||
input:not([type="hidden"]), select, textarea {
|
||||
min-width: 0;
|
||||
height: 2.55rem;
|
||||
padding: 0.48rem 0.68rem;
|
||||
border: 1px solid #bbcbbf;
|
||||
border-radius: 7px;
|
||||
@@ -306,6 +305,14 @@ input:not([type="hidden"]), select {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
input:not([type="hidden"]), select {
|
||||
height: 2.55rem;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: var(--muted);
|
||||
}
|
||||
@@ -471,7 +478,7 @@ dd {
|
||||
font-weight: 680;
|
||||
}
|
||||
|
||||
.editor input:not([type="hidden"]), .editor select {
|
||||
.editor input:not([type="hidden"]), .editor select, .editor textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
@@ -64,4 +64,46 @@
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if is_reseller or perms.hosting.view_hostingdnszone %}
|
||||
<section class="surface" aria-labelledby="dns-zones-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="dns-zones-heading">DNS zones</h2>
|
||||
{% if not is_reseller and perms.hosting.add_hostingdnszone and not has_primary_zone %}
|
||||
<a class="button primary" href="{% url 'panel:dns_zone_create' account.pk %}">Add DNS zone</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if dns_zones %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Domain</th>
|
||||
<th scope="col">SOA serial</th>
|
||||
{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for zone in dns_zones %}
|
||||
<tr>
|
||||
<td class="domain">
|
||||
{% if not is_reseller and perms.hosting.change_hostingdnszone %}
|
||||
<a class="record-link" href="{% url 'panel:dns_zone_edit' zone.pk %}" aria-label="Edit DNS zone for {{ zone.domain }}">{{ zone.domain }}</a>
|
||||
{% else %}
|
||||
{{ zone.domain }}
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ zone.serial }}</td>
|
||||
{% if not is_reseller %}
|
||||
<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>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No DNS zones configured.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>{{ page_title }}</h1>
|
||||
<p class="heading-meta domain">{{ domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Save zone</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,106 @@
|
||||
import json
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from coulobre.dns_node import DnsZone, main
|
||||
|
||||
|
||||
class DnsZoneManifestTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
self.manifest = {
|
||||
"version": 1,
|
||||
"kind": "bind9_zone",
|
||||
"domain": "BÜCHER.Example.",
|
||||
"serial": 3,
|
||||
"nameservers": ["ns1.bücher.example.", "dns2.provider.example"],
|
||||
"responsible_name": "Hostmaster.provider.example",
|
||||
"addresses": [
|
||||
{"name": "bücher.example", "address": "192.0.2.20"},
|
||||
{"name": "ns1.bücher.example", "address": "2001:0db8::53"},
|
||||
],
|
||||
}
|
||||
|
||||
def test_renders_canonical_soa_nameservers_and_both_address_families(self):
|
||||
zone = DnsZone.from_manifest(self.manifest)
|
||||
|
||||
self.assertEqual(
|
||||
zone.render(),
|
||||
"$ORIGIN xn--bcher-kva.example.\n"
|
||||
"$TTL 3600\n"
|
||||
"@ IN SOA ns1.xn--bcher-kva.example. hostmaster.provider.example. "
|
||||
"3 3600 600 1209600 300\n"
|
||||
"@ IN NS ns1.xn--bcher-kva.example.\n"
|
||||
"@ IN NS dns2.provider.example.\n"
|
||||
"xn--bcher-kva.example. IN A 192.0.2.20\n"
|
||||
"ns1.xn--bcher-kva.example. IN AAAA 2001:db8::53\n",
|
||||
)
|
||||
self.assertEqual(DnsZone.from_manifest(zone.manifest()), zone)
|
||||
|
||||
def test_accepts_a_single_external_nameserver_without_address_records(self):
|
||||
zone = DnsZone.from_manifest(
|
||||
self.manifest | {"nameservers": ["dns.provider.example"], "addresses": []}
|
||||
)
|
||||
self.assertEqual(zone.nameservers, ("dns.provider.example",))
|
||||
self.assertEqual(zone.addresses, ())
|
||||
|
||||
def test_rejects_inconsistent_zones(self):
|
||||
for changes, message in (
|
||||
({"addresses": []}, "in-zone nameserver needs an address"),
|
||||
({"nameservers": []}, "Supply at least one nameserver"),
|
||||
(
|
||||
{"nameservers": ["DNS1.provider.example", "dns1.provider.example."]},
|
||||
"list each name once",
|
||||
),
|
||||
(
|
||||
{
|
||||
"addresses": [
|
||||
{"name": "other-bücher.example", "address": "192.0.2.30"}
|
||||
]
|
||||
},
|
||||
"must belong to the zone",
|
||||
),
|
||||
):
|
||||
with (
|
||||
self.subTest(changes=changes),
|
||||
self.assertRaisesRegex(ValueError, message),
|
||||
):
|
||||
DnsZone.from_manifest(self.manifest | changes)
|
||||
|
||||
def test_rejects_invalid_fields_and_raw_zone_directives(self):
|
||||
for changes in (
|
||||
{"version": True},
|
||||
{"kind": "unknown"},
|
||||
{"domain": None},
|
||||
{"serial": True},
|
||||
{"serial": -1},
|
||||
{"serial": 2**32},
|
||||
{"nameservers": "dns.provider.example"},
|
||||
{"responsible_name": "hostmaster.provider.example\n$INCLUDE local.file"},
|
||||
{"addresses": [{"name": "bücher.example", "address": "fe80::1%eth0"}]},
|
||||
{"addresses": [{"name": "bücher.example", "address": 3232235521}]},
|
||||
{"extra": "value"},
|
||||
):
|
||||
with self.subTest(changes=changes), self.assertRaises(ValueError):
|
||||
DnsZone.from_manifest(self.manifest | changes)
|
||||
|
||||
def test_cli_rejects_an_invalid_manifest_before_writing_a_zone(self):
|
||||
directory = Path(self.enterContext(TemporaryDirectory()))
|
||||
manifest = directory / "zone.json"
|
||||
manifest.write_text(
|
||||
json.dumps(self.manifest | {"serial": -1}), encoding="utf-8"
|
||||
)
|
||||
|
||||
stdout = self.enterContext(redirect_stdout(StringIO()))
|
||||
stderr = self.enterContext(redirect_stderr(StringIO()))
|
||||
with self.assertRaises(SystemExit) as error:
|
||||
main(["render", str(manifest)])
|
||||
|
||||
self.assertEqual(error.exception.code, 1)
|
||||
self.assertEqual(stdout.getvalue(), "")
|
||||
self.assertIn(
|
||||
"SOA serial must be an unsigned 32-bit integer", stderr.getvalue()
|
||||
)
|
||||
@@ -0,0 +1,109 @@
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest.mock import call, patch
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, AddressRecord, DnsZone
|
||||
from coulobre.dns_node_apply import apply_zone, serial_is_newer, zone_file
|
||||
|
||||
|
||||
class DnsZoneApplyTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
directory = Path(self.enterContext(TemporaryDirectory()))
|
||||
self.zone = DnsZone(
|
||||
domain="example.net",
|
||||
serial=1,
|
||||
nameservers=("ns1.provider.example",),
|
||||
responsible_name="hostmaster.example.net",
|
||||
addresses=(AddressRecord("example.net", "192.0.2.20"),),
|
||||
)
|
||||
self.updated = replace(
|
||||
self.zone,
|
||||
serial=2,
|
||||
addresses=(AddressRecord("example.net", "192.0.2.21"),),
|
||||
)
|
||||
self.path = directory / self.zone.domain
|
||||
self.registration = (
|
||||
f'zone "example.net" {{ type primary; file "{self.path}"; '
|
||||
'allow-update { "none"; }; };'
|
||||
)
|
||||
self.commands = self.enterContext(patch("coulobre.dns_node_apply.run"))
|
||||
self.enterContext(patch("coulobre.dns_node_apply.ZONE_DIRECTORY", directory))
|
||||
self.enterContext(patch("coulobre.dns_node_apply.require_root_directory"))
|
||||
self.enterContext(patch("coulobre.dns_node_apply.os.geteuid", return_value=0))
|
||||
self.enterContext(
|
||||
patch(
|
||||
"coulobre.dns_node_apply.read_root_file",
|
||||
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
|
||||
)
|
||||
)
|
||||
|
||||
def test_failed_validation_preserves_existing_zone_file_and_registration(self):
|
||||
self.path.write_text(zone_file(self.zone), encoding="utf-8")
|
||||
self.commands.side_effect = [
|
||||
self.registration,
|
||||
"serial: 1",
|
||||
ValueError("Zone failed validation."),
|
||||
]
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "failed validation"):
|
||||
apply_zone(self.updated)
|
||||
|
||||
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.zone))
|
||||
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
|
||||
self.assertEqual(self.commands.call_args.args[0], "named-checkzone")
|
||||
|
||||
def test_reapplying_after_reload_failure_reuses_the_validated_zone_file(self):
|
||||
self.path.write_text(zone_file(self.zone), encoding="utf-8")
|
||||
self.commands.side_effect = [
|
||||
self.registration,
|
||||
"serial: 1",
|
||||
"OK",
|
||||
ValueError("Reload interrupted."),
|
||||
]
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "Reload interrupted"):
|
||||
apply_zone(self.updated)
|
||||
|
||||
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.updated))
|
||||
self.commands.reset_mock()
|
||||
self.commands.side_effect = [self.registration, "serial: 1", "", "serial: 2"]
|
||||
apply_zone(self.updated)
|
||||
|
||||
self.assertEqual(
|
||||
self.commands.call_args_list[1:],
|
||||
[
|
||||
call("rndc", "-s", "127.0.0.1", "zonestatus", "example.net"),
|
||||
call("rndc", "-s", "127.0.0.1", "reload", "example.net"),
|
||||
call("rndc", "-s", "127.0.0.1", "zonestatus", "example.net"),
|
||||
],
|
||||
)
|
||||
|
||||
def test_unmanaged_running_zone_blocks_installation(self):
|
||||
self.commands.return_value = (
|
||||
'zone "example.net" { type primary; file "/etc/bind/existing.example"; };'
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "outside Coulobre"):
|
||||
apply_zone(self.zone)
|
||||
|
||||
self.assertFalse(self.path.exists())
|
||||
self.commands.assert_called_once()
|
||||
|
||||
def test_modified_zone_file_blocks_replacement(self):
|
||||
modified = zone_file(self.zone).replace("192.0.2.20", "192.0.2.99")
|
||||
self.path.write_text(modified, encoding="utf-8")
|
||||
self.commands.side_effect = [self.registration, "serial: 1"]
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "has been modified"):
|
||||
apply_zone(self.updated)
|
||||
|
||||
self.assertEqual(self.path.read_text(encoding="utf-8"), modified)
|
||||
|
||||
def test_serial_comparison_wraps_and_rejects_ambiguous_half_range(self):
|
||||
self.assertTrue(serial_is_newer(0, MAX_SOA_SERIAL))
|
||||
self.assertFalse(serial_is_newer(MAX_SOA_SERIAL, 0))
|
||||
self.assertFalse(serial_is_newer(2**31, 0))
|
||||
self.assertFalse(serial_is_newer(0, 0))
|
||||
@@ -0,0 +1,201 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL, DnsZone
|
||||
|
||||
from .models import HostingAccount, HostingDnsZone, Reseller
|
||||
|
||||
|
||||
class DnsZonePanelTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.reseller_user = users.create_user("reseller")
|
||||
cls.reader = users.create_user("reader")
|
||||
cls.reader.user_permissions.set(
|
||||
Permission.objects.filter(
|
||||
content_type__app_label="hosting",
|
||||
codename__in=("view_hostingaccount", "view_hostingdnszone"),
|
||||
)
|
||||
)
|
||||
reseller = Reseller.objects.create(user=cls.reseller_user)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Account A", primary_domain="account-a.example", reseller=reseller
|
||||
)
|
||||
cls.other = HostingAccount.objects.create(
|
||||
name="Account B", primary_domain="account-b.example"
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.operator)
|
||||
self.add_url = reverse("panel:dns_zone_create", args=[self.account.pk])
|
||||
self.zone_data = {
|
||||
"nameservers": "NS1.Account-A.Example.\nns2.provider.example",
|
||||
"responsible_name": "Hostmaster.Account-A.Example.",
|
||||
"addresses": (
|
||||
"account-a.example 192.0.2.20\n"
|
||||
"ns1.account-a.example 192.0.2.53\n"
|
||||
"www.account-a.example 2001:0db8::20"
|
||||
),
|
||||
}
|
||||
|
||||
def create_zone(self):
|
||||
self.assertRedirects(
|
||||
self.client.post(self.add_url, self.zone_data),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
return self.account.dns_zones.get()
|
||||
|
||||
def test_operator_can_create_a_zone_and_download_its_renderable_manifest(self):
|
||||
self.assertContains(self.client.get(self.add_url), "Add DNS zone")
|
||||
zone = self.create_zone()
|
||||
self.assertEqual(zone.domain, self.account.primary_domain)
|
||||
self.assertEqual(zone.serial, 1)
|
||||
self.assertEqual(zone.responsible_name, "hostmaster.account-a.example")
|
||||
self.assertEqual(
|
||||
zone.nameservers, ["ns1.account-a.example", "ns2.provider.example"]
|
||||
)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, f"Edit DNS zone for {zone.domain}")
|
||||
self.assertNotContains(account, self.add_url)
|
||||
|
||||
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"])
|
||||
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_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.")
|
||||
invalid = self.client.post(
|
||||
self.add_url, self.zone_data | {"addresses": "ns1.account-a.example"}
|
||||
)
|
||||
self.assertContains(invalid, "Enter a name and an IP address on line 1.")
|
||||
self.assertFalse(HostingDnsZone.objects.exists())
|
||||
|
||||
zone = self.create_zone()
|
||||
duplicate = self.client.post(self.add_url, self.zone_data)
|
||||
self.assertContains(duplicate, "A DNS zone already exists for this domain.")
|
||||
self.assertEqual(self.account.dns_zones.get().pk, zone.pk)
|
||||
|
||||
def test_edit_increments_serial_only_when_data_changes_and_rejects_stale_edits(
|
||||
self,
|
||||
):
|
||||
zone = self.create_zone()
|
||||
edit = reverse("panel:dns_zone_edit", args=[zone.pk])
|
||||
initial = self.client.get(edit)
|
||||
self.assertContains(initial, "Edit DNS zone")
|
||||
self.assertEqual(initial.context["form"].initial["serial"], 1)
|
||||
|
||||
self.assertRedirects(
|
||||
self.client.post(edit, self.zone_data | {"serial": 1}),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 1)
|
||||
|
||||
updated = self.zone_data | {
|
||||
"addresses": self.zone_data["addresses"].replace("192.0.2.20", "192.0.2.21")
|
||||
}
|
||||
self.assertRedirects(
|
||||
self.client.post(edit, updated | {"serial": 1}),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
stale = self.client.post(edit, self.zone_data | {"serial": 1})
|
||||
self.assertContains(stale, "This DNS zone changed while you were editing it.")
|
||||
manifest = self.client.get(
|
||||
reverse("panel:dns_zone_manifest", args=[zone.pk])
|
||||
).json()
|
||||
self.assertEqual(manifest["serial"], 2)
|
||||
self.assertEqual(manifest["addresses"][0]["address"], "192.0.2.21")
|
||||
|
||||
def test_serial_wraps_at_the_dns_boundary(self):
|
||||
zone = self.create_zone()
|
||||
HostingDnsZone.objects.filter(pk=zone.pk).update(serial=MAX_SOA_SERIAL)
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
reverse("panel:dns_zone_edit", args=[zone.pk]),
|
||||
self.zone_data
|
||||
| {
|
||||
"serial": MAX_SOA_SERIAL,
|
||||
"responsible_name": "dns.provider.example",
|
||||
},
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 0)
|
||||
|
||||
def test_renaming_account_keeps_its_existing_zone_and_allows_a_new_primary_zone(
|
||||
self,
|
||||
):
|
||||
zone = self.create_zone()
|
||||
response = self.client.post(
|
||||
reverse("panel:account_edit", args=[self.account.pk]),
|
||||
{"name": self.account.name, "primary_domain": "new.example"},
|
||||
)
|
||||
self.assertRedirects(response, self.account.get_absolute_url())
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, self.add_url)
|
||||
self.assertContains(account, f"Edit DNS zone for {zone.domain}")
|
||||
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
self.add_url,
|
||||
self.zone_data
|
||||
| {"nameservers": "ns2.provider.example", "addresses": ""},
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
self.assertEqual(
|
||||
list(self.account.dns_zones.values_list("domain", flat=True)),
|
||||
["account-a.example", "new.example"],
|
||||
)
|
||||
|
||||
def test_reseller_cannot_edit_or_download_even_with_django_permissions(self):
|
||||
zone = self.create_zone()
|
||||
self.reseller_user.user_permissions.set(
|
||||
Permission.objects.filter(content_type__app_label="hosting")
|
||||
)
|
||||
self.client.force_login(self.reseller_user)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, "DNS zones")
|
||||
self.assertNotContains(account, "Edit DNS zone")
|
||||
self.assertNotContains(account, "Download DNS manifest")
|
||||
self.assertEqual(
|
||||
self.client.get(self.other.get_absolute_url()).status_code, 404
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.post(self.add_url, self.zone_data).status_code, 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
|
||||
403,
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(
|
||||
reverse("panel:dns_zone_manifest", args=[zone.pk])
|
||||
).status_code,
|
||||
403,
|
||||
)
|
||||
|
||||
def test_operator_with_view_permissions_can_download_but_cannot_edit(self):
|
||||
zone = self.create_zone()
|
||||
self.client.force_login(self.reader)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, "Download DNS manifest")
|
||||
self.assertNotContains(account, "Edit DNS zone")
|
||||
self.assertContains(
|
||||
self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk])),
|
||||
zone.domain,
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
|
||||
403,
|
||||
)
|
||||
self.assertEqual(self.client.get(self.add_url).status_code, 403)
|
||||
@@ -29,6 +29,17 @@ urlpatterns = [
|
||||
views.DownloadDatabaseManifest.as_view(),
|
||||
name="database_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/dns-zones/new/",
|
||||
views.DnsZoneCreate.as_view(),
|
||||
name="dns_zone_create",
|
||||
),
|
||||
path("dns-zones/<int:pk>/edit/", views.DnsZoneEdit.as_view(), name="dns_zone_edit"),
|
||||
path(
|
||||
"dns-zones/<int:pk>/manifest/",
|
||||
views.DownloadDnsZoneManifest.as_view(),
|
||||
name="dns_zone_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
|
||||
),
|
||||
|
||||
@@ -7,11 +7,20 @@ from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.functional import cached_property
|
||||
from django.views import View
|
||||
from django.views.generic import CreateView, DetailView, ListView, UpdateView
|
||||
from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
|
||||
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
|
||||
from .models import HostingAccount, HostingDatabase, HostingPlan, WebProvisioningPlan
|
||||
from .dns_forms import DnsZoneEditForm, DnsZoneForm
|
||||
from .models import (
|
||||
HostingAccount,
|
||||
HostingDatabase,
|
||||
HostingDnsZone,
|
||||
HostingPlan,
|
||||
WebProvisioningPlan,
|
||||
)
|
||||
from .reseller_accounts import create_reseller_account
|
||||
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
||||
|
||||
@@ -21,6 +30,7 @@ VIEW_PLANS = "hosting.view_webprovisioningplan"
|
||||
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
|
||||
VIEW_RESELLERS = "hosting.view_reseller"
|
||||
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
||||
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
||||
|
||||
|
||||
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
|
||||
@@ -150,6 +160,12 @@ class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
)[:10]
|
||||
if reseller is not None or user.has_perm(VIEW_DATABASES):
|
||||
context["databases"] = self.object.databases.all()
|
||||
if reseller is not None or user.has_perm(VIEW_DNS_ZONES):
|
||||
zones = list(self.object.dns_zones.all())
|
||||
context["dns_zones"] = zones
|
||||
context["has_primary_zone"] = any(
|
||||
zone.domain == self.object.primary_domain for zone in zones
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
@@ -196,6 +212,118 @@ class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View)
|
||||
)
|
||||
|
||||
|
||||
class DnsZoneEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
|
||||
template_name = "hosting/dns_zone_form.html"
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return {**super().get_form_kwargs(), "domain": self.domain}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
account=self.account, domain=self.domain, **kwargs
|
||||
)
|
||||
|
||||
def get_success_url(self):
|
||||
return self.account.get_absolute_url()
|
||||
|
||||
|
||||
class DnsZoneCreate(DnsZoneEditor):
|
||||
form_class = DnsZoneForm
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_hostingdnszone")
|
||||
extra_context = {"page_title": "Add DNS zone"}
|
||||
|
||||
@cached_property
|
||||
def account(self):
|
||||
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
||||
|
||||
@property
|
||||
def domain(self):
|
||||
return self.account.primary_domain
|
||||
|
||||
def get_initial(self):
|
||||
return {"responsible_name": f"hostmaster.{self.domain}"}
|
||||
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
HostingDnsZone.objects.create(
|
||||
account=self.account, domain=self.domain, **form.cleaned_data
|
||||
)
|
||||
except IntegrityError:
|
||||
if not HostingDnsZone.objects.filter(domain=self.domain).exists():
|
||||
raise
|
||||
form.add_error(None, "A DNS zone already exists for this domain.")
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
class DnsZoneEdit(DnsZoneEditor):
|
||||
form_class = DnsZoneEditForm
|
||||
permission_required = (
|
||||
VIEW_ACCOUNTS,
|
||||
VIEW_DNS_ZONES,
|
||||
"hosting.change_hostingdnszone",
|
||||
)
|
||||
extra_context = {"page_title": "Edit DNS zone"}
|
||||
|
||||
@cached_property
|
||||
def zone(self):
|
||||
return get_object_or_404(
|
||||
HostingDnsZone.objects.select_related("account"), pk=self.kwargs["pk"]
|
||||
)
|
||||
|
||||
@property
|
||||
def account(self):
|
||||
return self.zone.account
|
||||
|
||||
@property
|
||||
def domain(self):
|
||||
return self.zone.domain
|
||||
|
||||
def get_initial(self):
|
||||
return {
|
||||
"serial": self.zone.serial,
|
||||
"nameservers": "\n".join(self.zone.nameservers),
|
||||
"responsible_name": self.zone.responsible_name,
|
||||
"addresses": "\n".join(
|
||||
f"{record['name']} {record['address']}"
|
||||
for record in self.zone.addresses
|
||||
),
|
||||
}
|
||||
|
||||
def form_valid(self, form):
|
||||
values = form.cleaned_data
|
||||
serial = values["serial"]
|
||||
if all(getattr(self.zone, field) == value for field, value in values.items()):
|
||||
return super().form_valid(form)
|
||||
|
||||
next_serial = (serial + 1) % (MAX_SOA_SERIAL + 1)
|
||||
updated = HostingDnsZone.objects.filter(pk=self.zone.pk, serial=serial).update(
|
||||
**(values | {"serial": next_serial})
|
||||
)
|
||||
if not updated:
|
||||
form.add_error(
|
||||
None,
|
||||
"This DNS zone changed while you were editing it. Reopen the form and try again.",
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES)
|
||||
|
||||
def get(self, request, pk):
|
||||
zone = get_object_or_404(HostingDnsZone, pk=pk)
|
||||
return JsonResponse(
|
||||
zone.spec.manifest(),
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": f'attachment; filename="coulobre-zone-{zone.pk}.json"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
||||
model = HostingPlan
|
||||
permission_required = VIEW_HOSTING_PLANS
|
||||
|
||||
Reference in new issue
Block a user