From 7c69c65d3666364185089ddd4e4a0af341b08d41 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 22:54:41 +0100 Subject: [PATCH] Improve hosting onboarding, DNS editing and mailbox setup --- deploy/panel_installer/engine.py | 2 + src/coulobre/hosting/account_setup.py | 73 ++++- src/coulobre/hosting/dns_defaults.py | 10 + src/coulobre/hosting/dns_defaults_views.py | 121 ++++++++ src/coulobre/hosting/dns_forms.py | 150 ++++++++- src/coulobre/hosting/invitations.py | 20 ++ .../migrations/0056_dns_zone_defaults.py | 31 ++ src/coulobre/hosting/models.py | 8 + src/coulobre/hosting/reseller_onboarding.py | 4 + src/coulobre/hosting/resource_requests.py | 10 +- .../static/hosting/dns-record-editor.js | 79 +++++ src/coulobre/hosting/static/hosting/panel.css | 30 ++ .../templates/hosting/account_detail.html | 60 ++-- .../templates/hosting/account_list.html | 24 +- .../templates/hosting/account_retirement.html | 2 +- .../templates/hosting/account_setup.html | 24 ++ .../hosting/templates/hosting/base.html | 12 +- .../templates/hosting/customer_list.html | 4 +- .../templates/hosting/dns_defaults_form.html | 25 ++ .../templates/hosting/dns_record_editor.html | 19 ++ .../templates/hosting/dns_record_table.html | 12 + .../templates/hosting/dns_zone_form.html | 28 +- .../templates/hosting/mailbox_form.html | 6 +- .../templates/hosting/panel_invitation.txt | 18 +- .../templates/hosting/reseller_detail.html | 2 +- .../templates/hosting/reseller_list.html | 2 +- src/coulobre/hosting/test_account_setup.py | 38 +++ src/coulobre/hosting/test_dns_zones.py | 24 ++ .../hosting/test_reseller_onboarding.py | 8 +- src/coulobre/hosting/urls.py | 7 + src/coulobre/hosting/views.py | 285 ++++++++++++++++-- src/coulobre/settings.py | 3 + 32 files changed, 1053 insertions(+), 88 deletions(-) create mode 100644 src/coulobre/hosting/dns_defaults.py create mode 100644 src/coulobre/hosting/dns_defaults_views.py create mode 100644 src/coulobre/hosting/migrations/0056_dns_zone_defaults.py create mode 100644 src/coulobre/hosting/static/hosting/dns-record-editor.js create mode 100644 src/coulobre/hosting/templates/hosting/account_setup.html create mode 100644 src/coulobre/hosting/templates/hosting/dns_defaults_form.html create mode 100644 src/coulobre/hosting/templates/hosting/dns_record_editor.html create mode 100644 src/coulobre/hosting/templates/hosting/dns_record_table.html diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index 7932484..81e1a35 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -598,6 +598,8 @@ class Installer: COULOBRE_SMTP_PORT="25", COULOBRE_SMTP_STARTTLS="0", COULOBRE_EMAIL_FROM=f"panel@{self.plan.mail.host}", + COULOBRE_MAIL_IMAP_HOST=self.plan.mail.host, + COULOBRE_MAIL_SUBMISSION_HOST=self.plan.mail.host, ) hosting = self.plan.hosting if hosting.public_addresses: diff --git a/src/coulobre/hosting/account_setup.py b/src/coulobre/hosting/account_setup.py index e088ff8..f53f143 100644 --- a/src/coulobre/hosting/account_setup.py +++ b/src/coulobre/hosting/account_setup.py @@ -8,6 +8,8 @@ from django.utils import timezone from coulobre.dns_node import AddressRecord from coulobre.web_node import WebSite +from .dns_defaults import zone_defaults +from .dns_forms import normalize_record_rows from .dns_publication import queue_zone_snapshot from .mail_dns_setup import mail_dns_proposal from .models import ( @@ -21,7 +23,9 @@ from .models import ( from .php_settings import plan_php_settings -def website_records(domain, *, www=True, wildcard=True): +def website_records(domain, *, www=True, wildcard=True, addresses=None): + if addresses is None: + addresses = settings.HOSTING_PUBLIC_ADDRESSES owners = [domain] if www and len(domain) <= 249: owners.append(f"www.{domain}") @@ -30,7 +34,7 @@ def website_records(domain, *, www=True, wildcard=True): return [ AddressRecord(owner, address) for owner in owners - for address in settings.HOSTING_PUBLIC_ADDRESSES + for address in addresses ] @@ -65,11 +69,16 @@ def setup_new_account(account, options): wait_for_website=True, ) if managed_dns: + existing_managed_mail = ( + settings.LOCAL_MAILBOX_PROVISIONING + and settings.MANAGE_MAIL_DNS + and account.mail_domains.filter(domain=domain).exists() + ) create_default_dns_zone( account, www=add_www, wildcard=add_wildcard, - managed_mail=options.get("setup_email"), + managed_mail=options.get("setup_email") or existing_managed_mail, ) if options.get("setup_email"): _, created = HostingMailDomain.objects.get_or_create( @@ -79,33 +88,71 @@ def setup_new_account(account, options): raise ValidationError("This domain already has email configured.") -def create_default_dns_zone(account, *, www, wildcard, managed_mail): +def default_dns_zone(account, *, www=None, wildcard=None, managed_mail=False): domain = account.primary_domain - addresses = website_records(domain, www=www, wildcard=wildcard) + defaults = zone_defaults() + if not defaults.nameservers or not defaults.addresses: + return None + addresses = website_records( + domain, + www=defaults.include_www if www is None else www, + wildcard=defaults.include_wildcard if wildcard is None else wildcard, + addresses=defaults.addresses, + ) + extra = normalize_record_rows(defaults.records, domain) mx = txt = () if managed_mail: - mail_addresses, mx, txt = mail_dns_proposal(domain, None) + public_key = ( + account.mail_domains.filter(domain=domain) + .values_list("dkim_record", flat=True) + .first() + if account.pk + else None + ) + mail_addresses, mx, txt = mail_dns_proposal(domain, public_key) addresses.extend( record for record in mail_addresses if record.name == domain or record.name.endswith(f".{domain}") ) - zone = HostingDnsZone( + return HostingDnsZone( account=account, domain=domain, - nameservers=list(settings.HOSTING_NAMESERVERS), - responsible_name=f"hostmaster.{settings.HOSTING_NAMESERVERS[0]}", - addresses=[asdict(record) for record in dict.fromkeys(addresses)], - mx_records=[asdict(record) for record in mx], - txt_records=[asdict(record) for record in txt], + nameservers=list(defaults.nameservers), + responsible_name=f"hostmaster.{defaults.nameservers[0]}", + addresses=[ + asdict(record) + for record in dict.fromkeys((*addresses, *extra["addresses"])) + ], + mx_records=[ + asdict(record) + for record in dict.fromkeys((*mx, *extra["mx_records"])) + ], + txt_records=[ + asdict(record) + for record in dict.fromkeys((*txt, *extra["txt_records"])) + ], + extra_records=[asdict(record) for record in extra["extra_records"]], manage_mail_dns=bool(managed_mail), ) + + +def create_default_dns_zone(account, *, www, wildcard, managed_mail): try: + zone = default_dns_zone( + account, www=www, wildcard=wildcard, managed_mail=managed_mail + ) + if zone is None: + raise ValidationError( + "Configure DNS defaults before creating a zone." + ) with transaction.atomic(): zone.save() queue_zone_snapshot(zone) except IntegrityError: - if not HostingDnsZone.objects.filter(domain=domain).exists(): + if not HostingDnsZone.objects.filter( + domain=account.primary_domain + ).exists(): raise raise ValidationError("This domain already has a DNS zone.") from None except ValueError as error: diff --git a/src/coulobre/hosting/dns_defaults.py b/src/coulobre/hosting/dns_defaults.py new file mode 100644 index 0000000..af20e69 --- /dev/null +++ b/src/coulobre/hosting/dns_defaults.py @@ -0,0 +1,10 @@ +from django.conf import settings + +from .models import DnsZoneDefaults + + +def zone_defaults(): + saved = DnsZoneDefaults.objects.filter(pk=1).first() or DnsZoneDefaults() + saved.nameservers = saved.nameservers or settings.HOSTING_NAMESERVERS + saved.addresses = saved.addresses or settings.HOSTING_PUBLIC_ADDRESSES + return saved diff --git a/src/coulobre/hosting/dns_defaults_views.py b/src/coulobre/hosting/dns_defaults_views.py new file mode 100644 index 0000000..2a1f9ac --- /dev/null +++ b/src/coulobre/hosting/dns_defaults_views.py @@ -0,0 +1,121 @@ +from ipaddress import ip_address + +from django import forms +from django.contrib import messages +from django.contrib.auth.mixins import UserPassesTestMixin +from django.urls import reverse_lazy +from django.views.generic import FormView + +from coulobre.dns_node import dns_name + +from .dns_defaults import zone_defaults +from .dns_forms import normalize_record_rows +from .models import DnsZoneDefaults + + +class DnsDefaultsForm(forms.Form): + nameservers = forms.CharField( + required=False, + help_text=( + "Separate hostnames with spaces. " + "Leave blank to use the installation settings." + ), + ) + addresses = forms.CharField( + label="Hosting IP addresses", + required=False, + help_text=( + "Separate IPv4 or IPv6 addresses with spaces. " + "Leave blank to use the installation settings." + ), + ) + include_www = forms.BooleanField(label="Include www", required=False) + include_wildcard = forms.BooleanField( + label="Include a wildcard (*)", required=False + ) + records = forms.CharField( + label="Additional records", + required=False, + widget=forms.Textarea(attrs={"rows": 4}), + help_text=( + "Enter one record per line, for example _verification TXT abc123. " + "Use @ for the new zone name. " + "Enter fully qualified hostnames for record targets." + ), + ) + + def clean_nameservers(self): + try: + return list( + dict.fromkeys( + dns_name(name) + for name in self.cleaned_data["nameservers"].split() + ) + ) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + + def clean_addresses(self): + try: + addresses = list( + dict.fromkeys( + str(ip_address(address)) + for address in self.cleaned_data["addresses"].split() + ) + ) + if any("%" in address for address in addresses): + raise ValueError + except ValueError as error: + raise forms.ValidationError( + "Enter IPv4 or IPv6 addresses without scope identifiers." + ) from error + return addresses + + def clean_records(self): + rows = [] + for line in self.cleaned_data["records"].splitlines(): + parts = line.split(maxsplit=2) + if not parts: + continue + if len(parts) != 3 or parts[0].endswith("."): + raise forms.ValidationError( + "Enter a relative name, a record type and a value." + ) + name, kind, value = parts + rows.append({"name": name, "type": kind.upper(), "value": value}) + normalize_record_rows(rows, "preview.example") + return rows + + +class DnsDefaultsView(UserPassesTestMixin, FormView): + form_class = DnsDefaultsForm + template_name = "hosting/dns_defaults_form.html" + success_url = reverse_lazy("panel:dns_defaults") + + def test_func(self): + return self.request.user.is_superuser + + def get_initial(self): + saved = ( + DnsZoneDefaults.objects.filter(pk=1).first() or DnsZoneDefaults() + ) + return { + "nameservers": " ".join(saved.nameservers), + "addresses": " ".join(saved.addresses), + "include_www": saved.include_www, + "include_wildcard": saved.include_wildcard, + "records": "\n".join( + f"{row['name']} {row['type']} {row['value']}" + for row in saved.records + ), + } + + def get_context_data(self, **kwargs): + return super().get_context_data(effective=zone_defaults(), **kwargs) + + def form_valid(self, form): + DnsZoneDefaults.objects.update_or_create( + pk=1, defaults=form.cleaned_data + ) + messages.success(self.request, "DNS defaults saved for new zones.") + return super().form_valid(form) diff --git a/src/coulobre/hosting/dns_forms.py b/src/coulobre/hosting/dns_forms.py index f0d7d67..d8a746a 100644 --- a/src/coulobre/hosting/dns_forms.py +++ b/src/coulobre/hosting/dns_forms.py @@ -11,6 +11,120 @@ from coulobre.dns_node import ( TxtRecord, ) +RECORD_TYPES = ("A", "AAAA", "MX", "TXT", "CNAME", "SRV", "CAA") +RECORD_FIELDS = ("addresses", "mx_records", "txt_records", "extra_records") + + +def record_rows(spec): + return [ + *( + { + "name": item.name, + "type": item.record_type, + "value": item.address, + } + for item in spec.addresses + ), + *( + { + "name": item.name, + "type": "MX", + "value": f"{item.priority} {item.exchange}", + } + for item in spec.mx_records + ), + *( + {"name": item.name, "type": "TXT", "value": item.text} + for item in spec.txt_records + ), + *( + {"name": item.name, "type": item.record_type, "value": item.value} + for item in spec.extra_records + ), + ] + + +def zone_record_rows(spec): + return [ + *( + {"name": spec.domain, "type": "NS", "value": host} + for host in spec.nameservers + ), + *record_rows(spec), + ] + + +def zone_form_initial(zone): + return { + "serial": zone.serial, + "manage_mail_dns": zone.manage_mail_dns, + "delegate_dns": zone.delegate_dns, + "nameservers": "\n".join(zone.nameservers), + "responsible_name": zone.responsible_name, + "addresses": "\n".join( + f"{row['name']} {row['address']}" for row in zone.addresses + ), + "mx_records": "\n".join( + f"{row['name']} {row['priority']} {row['exchange']}" + for row in zone.mx_records + ), + "txt_records": "\n".join( + format_txt_record(row) for row in zone.txt_records + ), + "extra_records": "\n".join( + f"{row['name']} {row['record_type']} {row['value']}" + for row in zone.extra_records + ), + "record_rows": json.dumps(record_rows(zone.spec)), + } + + +def parse_record_rows(raw): + rows = json.loads(raw) + if not isinstance(rows, list) or any( + not isinstance(row, dict) + or row.keys() != {"name", "type", "value"} + or not all(isinstance(value, str) for value in row.values()) + for row in rows + ): + raise ValueError("Enter records with a name, type and value.") + return rows + + +def normalize_record_rows(rows, domain): + result = {field: [] for field in RECORD_FIELDS} + for number, row in enumerate(rows, 1): + name, kind = row["name"].strip(), row["type"] + if name == "@": + name = domain + elif name.endswith("."): + name = name[:-1] + elif name != domain and not name.endswith(f".{domain}"): + name = f"{name}.{domain}" if name else "" + value = row["value"] + try: + if kind in {"A", "AAAA"}: + record = AddressRecord(name, value.strip()) + if record.record_type != kind: + raise ValueError( + f"Enter an IP address for a {kind} record." + ) + result["addresses"].append(record) + elif kind == "MX": + priority, target = value.split() + result["mx_records"].append( + MxRecord(name, int(priority), target) + ) + elif kind == "TXT": + result["txt_records"].append(TxtRecord(name, value)) + elif kind in {"CNAME", "SRV", "CAA"}: + result["extra_records"].append(ExtraRecord(name, kind, value)) + else: + raise ValueError("Select a supported record type.") + except ValueError as error: + raise forms.ValidationError(f"Record {number}. {error}") from error + return {key: tuple(value) for key, value in result.items()} + def format_txt_record(record): text = record["text"] @@ -25,6 +139,12 @@ def format_txt_record(record): class DnsZoneForm(forms.Form): + record_rows = forms.CharField( + required=False, + max_length=524288, + widget=forms.HiddenInput, + strip=False, + ) nameservers = forms.CharField( widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}), help_text="Enter one hostname per line. The first is the SOA primary.", @@ -85,10 +205,26 @@ class DnsZoneForm(forms.Form): required=False, ) - def __init__(self, *args, domain, **kwargs): - super().__init__(*args, **kwargs) + def __init__(self, data=None, *args, domain, **kwargs): + initial = dict(kwargs.get("initial") or {}) + self.initial_rows = initial.pop("record_rows", "[]") + kwargs["initial"] = initial + if data and data.get("record_rows"): + data = data.copy() + for field in RECORD_FIELDS: + data[field] = "" + super().__init__(data, *args, **kwargs) self.domain = domain + @property + def editor_rows(self): + try: + return parse_record_rows( + self["record_rows"].value() or self.initial_rows + ) + except (ValueError, RecursionError): + return [] + def clean_addresses(self): records = [] for number, line in enumerate( @@ -172,6 +308,16 @@ class DnsZoneForm(forms.Form): data = super().clean() if self.errors: return data + rows = data.pop("record_rows", "") + if rows: + try: + data.update( + normalize_record_rows(parse_record_rows(rows), self.domain) + ) + except (ValueError, RecursionError) as error: + raise forms.ValidationError( + "Enter valid DNS records." + ) from error try: spec = DnsZone( domain=self.domain, diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py index 502352e..02c0499 100644 --- a/src/coulobre/hosting/invitations.py +++ b/src/coulobre/hosting/invitations.py @@ -24,6 +24,7 @@ from django.views.generic import FormView from kombu.exceptions import OperationalError from .access import customer_for_user, is_tenant, reseller_for_user +from .account_setup import website_records from .models import Customer, HostingAccount, PanelInvitation, Reseller from .panel_factors import lock_user from .password_reset import reset_enabled @@ -168,6 +169,11 @@ def deliver_invitation(invitation_id, revision): .order_by("pk") .first() ) + zone = ( + account.dns_zones.filter(domain=account.primary_domain).first() + if account + else None + ) message = render_to_string( "hosting/panel_invitation.txt", { @@ -175,6 +181,20 @@ def deliver_invitation(invitation_id, revision): "setup_url": origin + path, "panel_url": origin + "/", "account": account, + "nameservers": zone.nameservers if zone else (), + "website_records": ( + website_records(account.primary_domain, wildcard=False) + if account and zone is None + else () + ), + "imap_host": settings.MAIL_IMAP_HOST, + "submission_host": settings.MAIL_SUBMISSION_HOST, + "mail_configured": bool( + account + and account.mail_domains.filter( + domain=account.primary_domain + ).exists() + ), }, ) try: diff --git a/src/coulobre/hosting/migrations/0056_dns_zone_defaults.py b/src/coulobre/hosting/migrations/0056_dns_zone_defaults.py new file mode 100644 index 0000000..94a4e4f --- /dev/null +++ b/src/coulobre/hosting/migrations/0056_dns_zone_defaults.py @@ -0,0 +1,31 @@ +# Generated by Django 5.2.19 on 2026-11-22 21:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0055_hosting_setup_defaults"), + ] + + operations = [ + migrations.CreateModel( + name="DnsZoneDefaults", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("nameservers", models.JSONField(blank=True, default=list)), + ("addresses", models.JSONField(blank=True, default=list)), + ("include_www", models.BooleanField(default=True)), + ("include_wildcard", models.BooleanField(default=True)), + ("records", models.JSONField(blank=True, default=list)), + ], + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index c64b089..55bba3f 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -607,6 +607,14 @@ class DirectAdminImport(models.Model): fingerprint = models.CharField(max_length=64, unique=True) +class DnsZoneDefaults(models.Model): + nameservers = models.JSONField(default=list, blank=True) + addresses = models.JSONField(default=list, blank=True) + include_www = models.BooleanField(default=True) + include_wildcard = models.BooleanField(default=True) + records = models.JSONField(default=list, blank=True) + + class HostingDnsZone(models.Model): account = models.ForeignKey( HostingAccount, on_delete=models.PROTECT, related_name="dns_zones" diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py index 0c7e4d7..909e95a 100644 --- a/src/coulobre/hosting/reseller_onboarding.py +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -85,6 +85,10 @@ def request_reseller_resource(access, account_id, create, values): ) resource = create(account.pk, **values) record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource) + if getattr(resource, "provisioning", None) is not None: + record_resource_event( + reseller, account, Action.RESOURCE_PROVISION, resource + ) return resource diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index 192946b..e2a0349 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -49,7 +49,9 @@ def create_database_request(account_id, suffix, *, customer_id=None): @transaction.atomic -def create_mailbox_request(account_id, local_part, *, customer_id=None): +def create_mailbox_request( + account_id, local_part, *, customer_id=None, auto_provision=False +): account = lock_hosting_account(account_id, customer_id) require_open_account(account) try: @@ -83,10 +85,14 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None): raise ValidationError( "This hosting account has reached its mailbox limit." ) - return mail_domain.mailboxes.create( + mailbox = mail_domain.mailboxes.create( local_part=spec.local_part, quota_mib=plan.mailbox_quota_mib if plan is not None else None, ) + if auto_provision: + require_active_services(account) + MailboxProvisioning.objects.queue(mailbox=mailbox) + return mailbox @transaction.atomic diff --git a/src/coulobre/hosting/static/hosting/dns-record-editor.js b/src/coulobre/hosting/static/hosting/dns-record-editor.js new file mode 100644 index 0000000..5a59453 --- /dev/null +++ b/src/coulobre/hosting/static/hosting/dns-record-editor.js @@ -0,0 +1,79 @@ +const editor = document.querySelector("[data-dns-editor]"); +const rows = editor.querySelector("[data-dns-rows]"); +const add = editor.querySelector("[data-add-dns-record]"); +const form = editor.closest("form"); +const data = form.querySelector("[name=record_rows]"); +const valueLabels = { + A: "IPv4 address", AAAA: "IPv6 address", CNAME: "Target hostname", + MX: "Mail server hostname", TXT: "Text", SRV: "Priority, weight, port and target", + CAA: "Flags, tag and value", +}; + +function numberRows() { + Array.from(rows.children).forEach((row, index) => { + row.querySelector("legend").textContent = `Record ${index + 1}`; + }); +} + +function appendRecord(record) { + const row = editor.querySelector("template").content.firstElementChild.cloneNode(true); + const name = row.querySelector("[data-record-name]"); + const type = row.querySelector("[data-record-type]"); + const value = row.querySelector("[data-record-value]"); + const priority = row.querySelector("[data-record-priority]"); + const priorityLabel = row.querySelector("[data-priority-label]"); + const valueLabel = row.querySelector("[data-record-value-label]"); + name.value = record.name; + type.value = record.type; + value.value = record.value; + if (record.type === "MX") { + const [mxPriority, target] = record.value.split(/\s+/, 2); + priority.value = mxPriority; + value.value = target || ""; + } + row.dataset.initialValue = value.value; + row.dataset.initialRecord = record.type === "TXT" ? record.value : value.value; + const updateFields = () => { + const usesPriority = type.value === "MX"; + priorityLabel.hidden = !usesPriority; + priority.required = usesPriority; + priority.disabled = !usesPriority; + value.required = type.value !== "TXT"; + valueLabel.textContent = valueLabels[type.value]; + }; + type.addEventListener("change", updateFields); + row.querySelector("[data-remove-record]").addEventListener("click", () => { + const nextFocus = row.nextElementSibling?.querySelector("input") || add; + row.remove(); + numberRows(); + nextFocus.focus(); + }); + updateFields(); + rows.append(row); + return name; +} + +for (const record of JSON.parse(document.getElementById("dns-record-data").textContent)) { + appendRecord(record); +} +numberRows(); +editor.hidden = false; +form.querySelector("[data-dns-text-fields]").hidden = true; +form.querySelectorAll("[data-dns-text-fields] textarea").forEach((field) => { + field.disabled = true; +}); +add.addEventListener("click", () => { + const field = appendRecord({name: "", type: "A", value: ""}); + numberRows(); + field.focus(); +}); +form.addEventListener("submit", () => { + data.value = JSON.stringify(Array.from(rows.children, (row) => { + const name = row.querySelector("[data-record-name]").value; + const type = row.querySelector("[data-record-type]").value; + const value = row.querySelector("[data-record-value]").value; + const priority = row.querySelector("[data-record-priority]").value; + const text = value === row.dataset.initialValue ? row.dataset.initialRecord : value; + return {name, type, value: type === "MX" ? `${priority} ${value}` : type === "TXT" ? text : value}; + })); +}); diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 3d5eab3..8008682 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -778,6 +778,36 @@ dd { font-size: 0.88rem; } +.dns-surface { + margin-inline: 0; + padding: 1rem; +} + +.dns-editor-rows { + display: grid; + gap: 0.6rem; + margin-block: 0.75rem; +} + +.dns-edit-row { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 0.5rem; + min-width: 0; + margin: 0; + padding: 0.65rem; + border: 1px solid var(--line); + border-radius: 0.5rem; +} + +.dns-edit-row label { flex: 1 1 8rem; margin: 0; } +.dns-edit-row label[hidden] { display: none; } +.dns-edit-row label:has(select, input[type="number"]) { flex: 0 1 6rem; } +.dns-edit-row label:has(textarea) { flex: 2 1 12rem; } +.dns-edit-row textarea { display: block; min-height: 2.45rem; resize: vertical; } +.dns-record-table code { white-space: pre-wrap; overflow-wrap: anywhere; } + .reseller-editor fieldset { min-width: 0; padding: 0; diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index b3b9681..9212aaa 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -49,6 +49,12 @@ {% if can_change_hosting_services or service_change or can_retire_account or is_operator and perms.hosting.change_hostingaccount %}Account management{% endif %}
+ {% if offer_account_setup %} +
+

Some services still need setup.

+ Complete hosting setup +
+ {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index 2f8a6fb..a32342c 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -1,10 +1,10 @@ {% extends "hosting/base.html" %} -{% block title %}Hosting accounts · Coulobre Panel{% endblock %} +{% block title %}{% if is_customer %}My hosting{% else %}Hosting accounts{% endif %} · Coulobre Panel{% endblock %} {% block content %}
-

Hosting accounts

-

Manage domains and their hosting services. Link a customer to give them access.

+

{% if is_customer %}My hosting{% elif is_reseller %}Customer hosting{% else %}Hosting accounts{% endif %}

+ {% if is_operator %}

Manage domains and their hosting services. Link a customer to give them access.

{% endif %}

{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}

{% if account_allowance %}

{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated

{% endif %}
@@ -12,6 +12,17 @@ Add hosting account {% endif %}
+ {% if health_summary %} +
+

{% if not health_summary.configured %}Service checks need setup.{% elif health_summary.needs_attention %}{{ health_summary.needs_attention }} of {{ health_summary.configured }} service checks need attention.{% else %}All {{ health_summary.configured }} service checks are healthy.{% endif %}

+ Service health +
+ {% elif is_reseller %} +
+

Manage the logins for your assigned customers.

+ My customers +
+ {% endif %}
{% if retirement %} diff --git a/src/coulobre/hosting/templates/hosting/account_setup.html b/src/coulobre/hosting/templates/hosting/account_setup.html new file mode 100644 index 0000000..111c537 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_setup.html @@ -0,0 +1,24 @@ +{% extends "hosting/base.html" %} +{% block title %}Complete hosting setup · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +

Complete hosting setup

{{ account.primary_domain }}

+
+ + {% csrf_token %} +

Choose which missing services to set up for this domain. Set up HTTPS once the domain resolves.

+ {{ form.as_div }} +
+ {% if form.fields %}{% endif %} + Back to account +
+ +
+ {% if preview_records or preview_problem %} +
+

Proposed DNS records

+ {% include "hosting/dns_record_table.html" with records=preview_records %} + {% if preview_problem %}

{{ preview_problem }}

{% endif %} +
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index 31170d0..80c01ab 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -30,13 +30,13 @@ {% if is_tenant or perms.hosting.view_hostingaccount %} - Hosting accounts + {% if is_customer %}My hosting{% else %}Hosting accounts{% endif %} {% endif %} {% if is_reseller or is_operator and perms.hosting.view_customer %} - Customers + {% if is_reseller %}My customers{% else %}Customers{% endif %} {% endif %} {% if is_operator and perms.hosting.view_reseller %} @@ -53,7 +53,7 @@ {% endif %} {% if group_customer_navigation %}{% endif %} {% if is_operator and perms.hosting.view_servicehealth %} - + {% endif %} +
+ {{ form.addresses.as_field_group }} + {{ form.mx_records.as_field_group }} + {{ form.txt_records.as_field_group }} + {{ form.extra_records.as_field_group }} +
+ {% if not form.is_bound or form.record_rows.value %} + {% include "hosting/dns_record_editor.html" %} + + {% endif %}
Cancel diff --git a/src/coulobre/hosting/templates/hosting/mailbox_form.html b/src/coulobre/hosting/templates/hosting/mailbox_form.html index e6bd161..93d0ae3 100644 --- a/src/coulobre/hosting/templates/hosting/mailbox_form.html +++ b/src/coulobre/hosting/templates/hosting/mailbox_form.html @@ -1,10 +1,10 @@ {% extends "hosting/base.html" %} -{% block title %}Request mailbox · Coulobre Panel{% endblock %} +{% block title %}{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox · Coulobre Panel{% endblock %} {% block content %} ← {{ account.name }}
-

Request mailbox

+

{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox

{{ account.primary_domain }}

@@ -14,7 +14,7 @@ {{ form.as_div }}
{% if can_request_resource %} - + {% endif %} Cancel
diff --git a/src/coulobre/hosting/templates/hosting/panel_invitation.txt b/src/coulobre/hosting/templates/hosting/panel_invitation.txt index 5832813..88a5c7a 100644 --- a/src/coulobre/hosting/templates/hosting/panel_invitation.txt +++ b/src/coulobre/hosting/templates/hosting/panel_invitation.txt @@ -8,7 +8,23 @@ Set your password by opening this link within 48 hours: {% if account %}Your hosting account is {{ account.primary_domain }}.{% if account.hosting_plan %} Hosting plan: {{ account.hosting_plan.name }} -Website limit: {{ account.hosting_plan.website_limit }}{% endif %} +Website limit: {{ account.hosting_plan.website_limit }} +Scheduled tasks per account: {{ account.hosting_plan.website_job_limit }} +Database limit: {{ account.hosting_plan.database_limit|default_if_none:"Unlimited" }} +Mailbox limit: {{ account.hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}{% if account.hosting_plan.mailbox_quota_mib %} +Storage per new mailbox: {{ account.hosting_plan.mailbox_quota_mib }} MiB{% endif %}{% if account.hosting_plan.website_storage_limit_mib %} +Default website storage limit: {{ account.hosting_plan.website_storage_limit_mib }} MiB{% endif %}{% endif %} +{% if nameservers %} +To use Coulobre DNS, set these nameservers at your registrar: +{% for server in nameservers %}{{ server }} +{% endfor %}{% elif website_records %} +If your DNS is hosted elsewhere, add these website records at your DNS provider: +{% for record in website_records %}{{ record.name }} {{ record.record_type }} {{ record.address }} +{% endfor %}{% endif %}{% if mail_configured %}{% if imap_host or submission_host %} +Use the full mailbox email address as your mail client username.{% if imap_host %} +Incoming mail (IMAP over TLS): {{ imap_host }}, port 993{% endif %}{% if submission_host %} +Outgoing mail (SMTP with STARTTLS): {{ submission_host }}, port 587{% endif %} +{% endif %}{% endif %} After signing in, open the hosting account for website status, DNS settings, and instructions for configuring email. diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index ca7588b..bcad959 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -6,7 +6,7 @@

{{ reseller }}

{% if perms.hosting.change_reseller %} Contact and invitation - Edit reseller + Edit customer manager {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_list.html b/src/coulobre/hosting/templates/hosting/reseller_list.html index e6b64b2..75d9e26 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_list.html @@ -12,7 +12,7 @@ {% endif %}
-
+
diff --git a/src/coulobre/hosting/test_account_setup.py b/src/coulobre/hosting/test_account_setup.py index 77ae31c..dc6b233 100644 --- a/src/coulobre/hosting/test_account_setup.py +++ b/src/coulobre/hosting/test_account_setup.py @@ -64,3 +64,41 @@ class HostingAccountSetupTests(TestCase): response = self.client.get(self.old_account.get_absolute_url()) self.assertContains(response, "Copy website DNS records") self.assertContains(response, "existing.example.test A 192.0.2.21") + + def test_guided_setup_applies_template_and_preserves_existing_zone(self): + self.client.force_login(self.operator) + template_url = reverse("panel:dns_defaults") + self.assertRedirects( + self.client.post( + template_url, + { + "include_www": "on", + "records": "_setup TXT check me", + }, + ), + template_url, + ) + account = self.old_account + page = self.client.get(account.get_absolute_url()) + self.assertContains(page, "Proposed DNS zone") + self.assertContains(page, "_setup.existing.example.test") + setup = reverse("panel:account_setup", args=[account.pk]) + choices = { + "setup_website": "on", + "setup_dns": "on", + "setup_email": "on", + } + for _ in range(2): + self.assertRedirects( + self.client.post(setup, choices), account.get_absolute_url() + ) + self.assertEqual(account.webprovisioningplan_set.count(), 1) + zone = account.dns_zones.get() + self.assertEqual(zone.publication.state, "queued") + self.assertNotIn( + "*.existing.example.test", + {record.name for record in zone.spec.addresses}, + ) + self.assertIn( + "check me", {record.text for record in zone.spec.txt_records} + ) diff --git a/src/coulobre/hosting/test_dns_zones.py b/src/coulobre/hosting/test_dns_zones.py index 0419594..8ed36c7 100644 --- a/src/coulobre/hosting/test_dns_zones.py +++ b/src/coulobre/hosting/test_dns_zones.py @@ -167,6 +167,30 @@ class DnsZonePanelTests(TestCase): self.assertNotIn("mx_records", manifest) self.assertNotIn("txt_records", manifest) + def test_record_editor_validates_types_and_updates_the_zone(self): + zone = self.create_zone() + url = reverse("panel:dns_zone_edit", args=[zone.pk]) + base = self.client.get(url).context["form"].initial + records = [{"name": "ns1", "type": "A", "value": "192.0.2.20"}] + extra = {"name": "www", "type": "AAAA", "value": "192.0.2.21"} + response = self.client.post( + url, base | {"record_rows": json.dumps(records + [extra])} + ) + self.assertContains(response, "Enter an IP address for a AAAA record") + extra["value"] = "2001:db8::21" + self.assertRedirects( + self.client.post( + url, base | {"record_rows": json.dumps(records + [extra])} + ), + self.account.get_absolute_url(), + ) + zone.refresh_from_db() + self.assertEqual(zone.serial, 2) + self.assertEqual(zone.spec.addresses[1].name, "www.account-a.example") + self.assertContains( + self.client.get(self.account.get_absolute_url()), "2001:db8::21" + ) + def test_invalid_mail_records_leave_existing_zone_unchanged(self): zone = self.create_zone() edit = reverse("panel:dns_zone_edit", args=[zone.pk]) diff --git a/src/coulobre/hosting/test_reseller_onboarding.py b/src/coulobre/hosting/test_reseller_onboarding.py index d429298..bc39ea4 100644 --- a/src/coulobre/hosting/test_reseller_onboarding.py +++ b/src/coulobre/hosting/test_reseller_onboarding.py @@ -196,7 +196,13 @@ class ResellerOnboardingTests(TestCase): for model, resource in (("database", database), ("mailbox", mailbox)): url = reverse(f"panel:{model}_provision", args=[resource.pk]) manifest = reverse(f"panel:{model}_manifest", args=[resource.pk]) - self.assertContains(self.client.get(detail), f"Provision {model}") + if model == "database": + self.assertContains( + self.client.get(detail), "Provision database" + ) + else: + self.assertEqual(mailbox.provisioning.state, "queued") + self.assertContains(self.client.get(detail), "Queued") self.assertEqual(self.client.get(manifest).status_code, 403) for _ in range(2): self.assertRedirects(self.client.post(url), detail) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 32f007a..8cdee3e 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -4,6 +4,7 @@ from django.urls import path from . import themes, views from .backup_restores import RestoreKind from .credential_views import DatabaseCredentialView, MailboxCredentialView +from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView from .health_views import ServiceHealthView from .independent_website_views import ( @@ -54,6 +55,12 @@ app_name = "panel" urlpatterns = [ path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"), + path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"), + path( + "accounts//setup/", + views.ExistingAccountSetup.as_view(), + name="account_setup", + ), path( "dns-zones//replication/", DnsReplicaView.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index a9e7a62..a0af15a 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -15,6 +15,7 @@ from django.http import ( ) from django.shortcuts import get_object_or_404, redirect from django.urls import reverse, reverse_lazy +from django.utils import timezone from django.utils.functional import cached_property from django.views import View from django.views.generic import ( @@ -27,8 +28,10 @@ from django.views.generic import ( from django.views.generic.detail import SingleObjectMixin from coulobre.dns_node import MAX_SOA_SERIAL +from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.php_runtime import available_php_versions +from coulobre.service_health import HealthResult from coulobre.sftp_keys import public_key_fingerprint from .access import ( @@ -53,7 +56,7 @@ from .account_backups import ( queue_account_backup, save_backup_schedule, ) -from .account_setup import setup_new_account, website_records +from .account_setup import default_dns_zone, setup_new_account, website_records from .backup_restores import ( RestoreKind, available_restore_resources, @@ -66,8 +69,15 @@ from .backup_restores import ( retry_remote_mail_restore, ) from .backup_retention import change_backup_retention, protect_backup -from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record +from .dns_defaults import zone_defaults +from .dns_forms import ( + DnsZoneEditForm, + DnsZoneForm, + zone_form_initial, + zone_record_rows, +) from .dns_publication import queue_dns_publication +from .health_views import STALE_AFTER from .impersonation import ( CUSTOMER_WRITE_PERMISSIONS, EndReason, @@ -97,6 +107,7 @@ from .models import ( HostingMailbox, HostingPlan, Reseller, + ServiceHealth, WebProvisioningPlan, WebsiteAlias, WebsiteDomain, @@ -135,6 +146,7 @@ from .resource_requests import ( queue_site_storage_limit, queue_site_storage_measurement, queue_web_https, + require_active_services, require_open_account, ) from .retirement_views import RETIRE_ACCOUNTS @@ -226,6 +238,123 @@ PROVISION_MAILBOX = ( CHANGE_MAILBOX_QUOTA = (*PROVISION_MAILBOX, "hosting.change_hostingmailbox") +def automatic_mailbox_provisioning(user): + return settings.LOCAL_MAILBOX_PROVISIONING and ( + is_tenant(user) or user.has_perms(PROVISION_MAILBOX) + ) + + +def missing_account_setup(account, actor): + if is_tenant(actor) or account.services_suspended: + return () + domain = account.primary_domain + defaults = zone_defaults() + options = [] + if ( + settings.LOCAL_WEB_ACTIVATION + and actor.has_perms(ACTIVATE_WEB) + and not account.webprovisioningplan_set.filter( + primary_domain=domain, activation__isnull=False + ).exists() + ): + options.append(("setup_website", "Set up the primary website")) + if ( + settings.LOCAL_DNS_PUBLISHING + and defaults.nameservers + and defaults.addresses + and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) + and not HostingDnsZone.objects.filter(domain=domain).exists() + ): + options.append(("setup_dns", "Publish a Coulobre DNS zone")) + if ( + settings.LOCAL_MAILBOX_PROVISIONING + and settings.MANAGE_MAIL_DNS + and actor.has_perms(PROVISION_MAILBOX) + and not account.mail_domains.filter(domain=domain).exists() + ): + options.append(("setup_email", "Set up the managed mail domain")) + return options + + +class ExistingAccountSetup( + OperatorOnlyMixin, PermissionRequiredMixin, FormView +): + permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS) + template_name = "hosting/account_setup.html" + form_class = forms.Form + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount, pk=self.kwargs["pk"], retired_at__isnull=True + ) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + options = missing_account_setup(self.account, self.request.user) + for name, label in options: + form.fields[name] = forms.BooleanField( + label=label, initial=True, required=False + ) + if "setup_website" in form.fields: + form.fields["setup_landing_page"] = forms.BooleanField( + label="Add a starter page if the web root is empty", + required=False, + ) + return form + + def get_context_data(self, **kwargs): + context = super().get_context_data(account=self.account, **kwargs) + form = context["form"] + if "setup_dns" in form.fields: + try: + draft = default_dns_zone( + self.account, + managed_mail=( + "setup_email" in form.fields + and bool(form["setup_email"].value()) + ) + or ( + settings.MANAGE_MAIL_DNS + and self.account.mail_domains.filter( + domain=self.account.primary_domain + ).exists() + ), + ) + if draft is not None: + context["preview_records"] = zone_record_rows(draft.spec) + except (ValidationError, ValueError) as error: + context["preview_problem"] = str(error) + return context + + def form_valid(self, form): + try: + with transaction.atomic(): + account = lock_hosting_account( + self.account.pk, customer_id=None + ) + require_active_services(account) + available = dict( + missing_account_setup(account, self.request.user) + ) + options = { + name: selected + for name, selected in form.cleaned_data.items() + if name in available or name == "setup_landing_page" + } + if any(options.get(name) for name in available): + defaults = zone_defaults() + options.update( + setup_www=defaults.include_www, + setup_wildcard=defaults.include_wildcard, + ) + setup_new_account(account, options) + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.account) + + class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): queryset = ( HostingAccount.objects.filter(retired_at__isnull=True) @@ -261,6 +390,7 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): def get_context_data(self, **kwargs): context = super().get_context_data(search=self.search, **kwargs) + context["show_customer_website_link"] = settings.WEBSITE_USAGE reseller = reseller_for_user(self.request.user) if reseller is not None: context["account_allowance"] = { @@ -268,6 +398,28 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): "limit": reseller.account_limit, "may_create": reseller.may_create_accounts(), } + elif ( + not self.request.GET + and not is_tenant(self.request.user) + and self.request.user.has_perm("hosting.view_servicehealth") + ): + targets = settings.SERVICE_HEALTH_TARGETS + checks = { + (node.node, service) + for node in targets + for service in node.services + } + healthy = set( + ServiceHealth.objects.filter( + node__in={node.node for node in targets}, + result=HealthResult.ACTIVE, + observed_at__gt=timezone.now() - STALE_AFTER, + ).values_list("node", "service") + ) + context["health_summary"] = { + "configured": len(checks), + "needs_attention": len(checks - healthy), + } return context @@ -306,6 +458,8 @@ class AccountEditor: field.queryset = field.queryset.select_related( "user" ).order_by("user__username") + if "reseller" in form.fields: + form.fields["reseller"].label = "Customer manager" return form @@ -328,13 +482,14 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): form = super().get_form(form_class) actor = self.request.user reseller = reseller_for_user(actor) is not None + defaults = zone_defaults() web = settings.LOCAL_WEB_ACTIVATION and ( reseller or actor.has_perms(ACTIVATE_WEB) ) dns = ( settings.LOCAL_DNS_PUBLISHING - and settings.HOSTING_NAMESERVERS - and settings.HOSTING_PUBLIC_ADDRESSES + and defaults.nameservers + and defaults.addresses and ( reseller or actor.has_perms( @@ -361,7 +516,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): for name, (available, label) in choices.items(): if available: form.fields[name] = forms.BooleanField( - label=label, initial=True, required=False + label=label, + initial={ + "setup_www": defaults.include_www, + "setup_wildcard": defaults.include_wildcard, + }.get(name, True), + required=False, ) return form @@ -449,6 +609,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): reseller = reseller_for_user(user) customer = customer_for_user(user) tenant = reseller is not None or customer is not None + context["offer_account_setup"] = ( + not tenant + and user.has_perm(CHANGE_ACCOUNTS) + and bool(missing_account_setup(self.object, user)) + ) context["show_website_usage"] = settings.WEBSITE_USAGE and ( tenant or user.has_perm("hosting.view_websiteusage") ) @@ -693,6 +858,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING zones = list(zone_list) context["dns_zones"] = zones + context["dns_zone_records"] = [ + (zone, zone_record_rows(zone.spec)) for zone in zones + ] primary_zone = next( ( zone @@ -704,6 +872,21 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["has_primary_zone"] = primary_zone is not None if primary_zone is None: context["dns_readiness"] = "No managed zone" + if not tenant and settings.LOCAL_DNS_PUBLISHING: + try: + draft = default_dns_zone( + self.object, + managed_mail=settings.MANAGE_MAIL_DNS + and self.object.mail_domains.filter( + domain=self.object.primary_domain + ).exists(), + ) + if draft is not None: + context["default_zone_records"] = zone_record_rows( + draft.spec + ) + except (ValidationError, ValueError) as error: + context["default_zone_problem"] = str(error) context["external_website_dns"] = "\n".join( f"{record.name} {record.record_type} {record.address}" for record in website_records(self.object.primary_domain) @@ -714,6 +897,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): publication, "Ready to publish", "Published" ) if tenant or user.has_perm(VIEW_MAILBOXES): + context["automatic_mailbox_provisioning"] = ( + automatic_mailbox_provisioning(user) + ) context["manage_mail_routing"] = mail_policy_enabled( self.request, "routing" ) @@ -730,11 +916,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object - ).select_related("mail_domain") + ).select_related("mail_domain", "provisioning") if manage_resources or ( not tenant and user.has_perms(PROVISION_MAILBOX) ): - mailboxes = mailboxes.select_related("provisioning") context["manage_mailbox_provisioning"] = True context["local_mailbox_enabled"] = ( settings.LOCAL_MAILBOX_PROVISIONING @@ -1927,7 +2112,22 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): return self.account.primary_domain def get_initial(self): - return {"responsible_name": f"hostmaster.{self.domain}"} + try: + draft = default_dns_zone( + self.account, + managed_mail=settings.MANAGE_MAIL_DNS + and self.account.mail_domains.filter( + domain=self.domain + ).exists(), + ) + if draft is not None: + return zone_form_initial(draft) + except (ValidationError, ValueError): + pass # The operator can still enter a manual zone. + return { + "responsible_name": f"hostmaster.{self.domain}", + "record_rows": "[]", + } def form_valid(self, form): try: @@ -1998,28 +2198,38 @@ class DnsZoneEdit(DnsZoneEditor): return self.zone.domain def get_initial(self): - return { - "serial": self.zone.serial, - "manage_mail_dns": self.zone.manage_mail_dns, - "delegate_dns": self.zone.delegate_dns, - "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 - ), - "mx_records": "\n".join( - f"{record['name']} {record['priority']} {record['exchange']}" - for record in self.zone.mx_records - ), - "txt_records": "\n".join( - format_txt_record(record) for record in self.zone.txt_records - ), - "extra_records": "\n".join( - f"{record['name']} {record['record_type']} {record['value']}" - for record in self.zone.extra_records - ), + return zone_form_initial(self.zone) + + def check_managed_mail_records(self, values): + if not (self.zone.manage_mail_dns and values["manage_mail_dns"]): + return + domains = set( + self.account.mail_domains.values_list("domain", flat=True) + ) + dmarc = {f"_dmarc.{domain}" for domain in domains} + dkim = { + f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}" + for domain in domains } + managed_txt = [ + txt + for txt in self.zone.txt_records + if txt["name"] in dkim + or txt["name"] in dmarc + and matches_version(txt["text"], "v=DMARC1") + or txt["name"] in domains + and matches_version(txt["text"], "v=spf1") + ] + managed_mx = [ + mx for mx in self.zone.mx_records if mx["name"] in domains + ] + if any(txt not in values["txt_records"] for txt in managed_txt) or any( + mx not in values["mx_records"] for mx in managed_mx + ): + raise ValidationError( + "Keep the managed mail records or disable automatic mail DNS " + "in Zone settings first." + ) def form_valid(self, form): values = form.cleaned_data @@ -2037,6 +2247,7 @@ class DnsZoneEdit(DnsZoneEditor): self.account.pk, customer_id=None ) require_open_account(account) + self.check_managed_mail_records(values) zones = HostingDnsZone.objects.filter( pk=self.zone.pk, serial=serial ) @@ -2120,7 +2331,21 @@ class MailboxCreate(ResourceRequestCreate): template_name = "hosting/mailbox_form.html" permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:mailbox_create"] audit_operation = CustomerImpersonationAction.Operation.MAILBOX - create_request = staticmethod(create_mailbox_request) + + def create_request(self, account_id, **values): + return create_mailbox_request( + account_id, + auto_provision=automatic_mailbox_provisioning(self.request.user), + **values, + ) + + def get_context_data(self, **kwargs): + return super().get_context_data( + automatic_mailbox_provisioning=automatic_mailbox_provisioning( + self.request.user + ), + **kwargs, + ) def get_form(self, form_class=None): form = super().get_form(form_class) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 1ac3e0c..6eddcfa 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -271,6 +271,9 @@ LOCAL_MAILBOX_CREDENTIALS = ( os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS") == "1" ) MAIL_IMAP_HOST = os.environ.get("COULOBRE_MAIL_IMAP_HOST", "").strip() +MAIL_SUBMISSION_HOST = os.environ.get( + "COULOBRE_MAIL_SUBMISSION_HOST", "" +).strip() MAIL_DNS_RESOLVERS = ip_addresses_env("COULOBRE_MAIL_DNS_RESOLVERS", 3) MAIL_SENDING_IPS = ip_addresses_env("COULOBRE_MAIL_SENDING_IPS", 4) MAIL_MX_IPS = ip_addresses_env("COULOBRE_MAIL_MX_IPS", 4)