Compare commits
6
Commits
9e4e7c0ebe
...
cf9ce8e5b6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf9ce8e5b6 | ||
|
|
b92edc02f5 | ||
|
|
f50bfbc60d | ||
|
|
3e15cb010b | ||
|
|
b7a156b45e | ||
|
|
7c69c65d36 |
No files matched your search
@@ -47,6 +47,16 @@
|
||||
instructions, and known limitations. Mark a release candidate as a
|
||||
prerelease. Close the milestone when its target version is published.
|
||||
|
||||
For a release tested through the web updater, generate and attach
|
||||
`web-update.json` alongside the matching wheel. List each tested starting
|
||||
package version after the wheel path. Only list versions that can upgrade
|
||||
with the dependencies and service units they already have.
|
||||
|
||||
```sh
|
||||
python tools/web_update_manifest.py dist/coulobre_panel-0.10.1rc2-py3-none-any.whl \
|
||||
0.10.1rc1 > dist/web-update.json
|
||||
```
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Start changes on a dedicated branch from the default branch, named main.
|
||||
|
||||
@@ -579,8 +579,12 @@ class Installer:
|
||||
f"amqp://coulobre:{self.state['broker_password']}@127.0.0.1:5672/coulobre"
|
||||
),
|
||||
"COULOBRE_LOCAL_DATABASE_PROVISIONING": "1",
|
||||
"COULOBRE_SERVICE_HEALTH": json.dumps(
|
||||
{"panel": {"local": services}}, separators=(",", ":")
|
||||
"COULOBRE_SERVICE_HEALTH": (
|
||||
"'"
|
||||
+ json.dumps(
|
||||
{"panel": {"local": services}}, separators=(",", ":")
|
||||
)
|
||||
+ "'"
|
||||
),
|
||||
}
|
||||
if self.php:
|
||||
@@ -598,6 +602,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:
|
||||
@@ -854,6 +860,12 @@ class Installer:
|
||||
HEALTH_TIMER,
|
||||
):
|
||||
install_unit(unit)
|
||||
if not REMOTE_MODES.intersection(
|
||||
(self.plan.dns.mode, self.plan.mail.mode)
|
||||
):
|
||||
install_unit("coulobre-update.socket")
|
||||
install_unit("coulobre-update@.service")
|
||||
workers.append("coulobre-update.socket")
|
||||
systemctl("daemon-reload")
|
||||
systemctl(
|
||||
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release updater socket
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/coulobre-update.sock
|
||||
SocketUser=coulobre-panel
|
||||
SocketGroup=root
|
||||
SocketMode=0600
|
||||
Accept=yes
|
||||
MaxConnections=3
|
||||
RemoveOnStop=true
|
||||
|
||||
[Install]
|
||||
WantedBy=sockets.target
|
||||
@@ -0,0 +1,22 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release update
|
||||
After=mariadb.service network-online.target
|
||||
CollectMode=inactive-or-failed
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User=root
|
||||
WorkingDirectory=/opt/coulobre
|
||||
EnvironmentFile=/etc/coulobre/panel.env
|
||||
StateDirectory=coulobre-update
|
||||
StateDirectoryMode=0755
|
||||
UMask=0077
|
||||
ExecStart=/opt/coulobre/bin/coulobre-update
|
||||
StandardInput=socket
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
RuntimeMaxSec=60min
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/opt/coulobre
|
||||
@@ -573,6 +573,56 @@ sudo systemctl daemon-reload
|
||||
sudo systemctl start coulobre-panel.service coulobre-worker.service coulobre-beat.service
|
||||
```
|
||||
|
||||
### Upgrade from v0.10 to v0.10.1
|
||||
|
||||
Use the in-place procedure above to install v0.10.1 and apply its migrations.
|
||||
Existing DNS zones keep their records. Use **DNS zone template** under
|
||||
**Server and services** to change the defaults for new zones. Use **Complete
|
||||
hosting setup** on an existing account to review and add missing services.
|
||||
|
||||
To include mail client details in new invitations, set
|
||||
`COULOBRE_MAIL_IMAP_HOST` and `COULOBRE_MAIL_SUBMISSION_HOST` to the respective
|
||||
client-facing names when these services are available. For an upgraded panel
|
||||
without service checks, follow [the collector setup](#monitor-local-and-remote-services).
|
||||
|
||||
### Install a compatible release from the panel
|
||||
|
||||
The installer enables **Updates** for single-server deployments. On an
|
||||
existing installer-managed single server, install the updater units from the
|
||||
v0.10.1 source release after upgrading the package:
|
||||
|
||||
```sh
|
||||
sudo install -m 0644 deploy/systemd/coulobre-update.socket \
|
||||
deploy/systemd/coulobre-update@.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now coulobre-update.socket
|
||||
```
|
||||
|
||||
A superuser with a verified second factor can choose a compatible release
|
||||
from **Server and services → Updates**. The updater uses the official Gitea
|
||||
release over HTTPS and checks the wheel against its published SHA-256 hash.
|
||||
It supports the installer-managed local MariaDB database and installer
|
||||
layout. Use the in-place procedure for linked mail or DNS receivers, custom
|
||||
service unit changes, and releases requiring new dependencies. The update
|
||||
manifest lists the tested starting versions.
|
||||
|
||||
The panel and its workers pause during the upgrade. Refresh **Updates** after
|
||||
the panel returns. The latest update status names the recovery directory in
|
||||
`/var/lib/coulobre-update/`. The root-only directory holds the previous
|
||||
virtual environment, `/etc/coulobre` configuration, MariaDB dump, unit list
|
||||
and operation log. Keep enough free space for these copies. Review progress
|
||||
and service errors with `sudo journalctl -u 'coulobre-update@*'`.
|
||||
|
||||
If recovery is required, keep the panel and its workers stopped. Use the
|
||||
saved `units.json` to identify the active units before the update. Restore
|
||||
`venv` to `/opt/coulobre` at the same path and restore the saved `config` to
|
||||
`/etc/coulobre` if needed. Import `panel.sql` with `sudo mariadb` to replace
|
||||
the panel database with the pre-upgrade copy. Rebuild panel static files
|
||||
with `panel_manage collectstatic --noinput`, restart the saved units and
|
||||
verify sign-in and service health. Archive `status.json` as root after
|
||||
recovery to allow a later update. Check that `panel.sql` and `venv` exist
|
||||
before restoring from a directory created by an interrupted update.
|
||||
|
||||
### Upgrade from v0.9 to v0.10
|
||||
|
||||
Use the in-place procedure above with the v0.10 source release. Keep a copy
|
||||
|
||||
+2
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "coulobre-panel"
|
||||
version = "0.10.0rc1"
|
||||
version = "0.10.1rc1"
|
||||
description = "A web hosting control panel for hosting providers and resellers."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
@@ -30,6 +30,7 @@ coulobre-mail-node = "coulobre.mail_node:main"
|
||||
coulobre-node-setup = "coulobre.node_setup:main"
|
||||
coulobre-service-credentials = "coulobre.service_credentials:main"
|
||||
coulobre-service-health = "coulobre.service_health:main"
|
||||
coulobre-update = "coulobre.local_update:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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};
|
||||
}));
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -49,6 +49,12 @@
|
||||
{% if can_change_hosting_services or service_change or can_retire_account or is_operator and perms.hosting.change_hostingaccount %}<a href="#account-management">Account management</a>{% endif %}
|
||||
</nav>
|
||||
<section class="surface account-overview account-content" id="overview" data-account-section tabindex="-1" aria-label="Account overview">
|
||||
{% if offer_account_setup %}
|
||||
<div class="section-heading">
|
||||
<p>Some services still need setup.</p>
|
||||
<a class="button primary" href="{% url 'panel:account_setup' account.pk %}">Complete hosting setup</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<dl class="account-readiness">
|
||||
{% if show_website %}<div><dt>Website</dt><dd><a href="#websites">{{ website_readiness }}</a></dd></div>{% endif %}
|
||||
{% if show_website %}<div><dt>HTTPS</dt><dd><a href="#websites">{{ https_readiness }}</a></dd></div>{% endif %}
|
||||
@@ -239,6 +245,15 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% for zone, records in dns_zone_records %}
|
||||
<header class="section-heading"><h3>Records for {{ zone.domain }}</h3></header>
|
||||
{% include "hosting/dns_record_table.html" %}
|
||||
{% endfor %}
|
||||
{% elif default_zone_records %}
|
||||
<header class="section-heading"><h3>Proposed DNS zone</h3><span class="muted">Preview</span></header>
|
||||
{% include "hosting/dns_record_table.html" with records=default_zone_records %}
|
||||
{% elif default_zone_problem %}
|
||||
<p class="section-text">Check the DNS zone template. {{ default_zone_problem }}</p>
|
||||
{% else %}
|
||||
<p class="empty">No DNS zones configured.</p>
|
||||
{% endif %}
|
||||
@@ -284,7 +299,7 @@
|
||||
<section class="surface" aria-labelledby="mailboxes-heading">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2 id="mailboxes-heading" tabindex="-1">Mailbox requests</h2>
|
||||
<h2 id="mailboxes-heading" tabindex="-1">Mailboxes</h2>
|
||||
{% if is_tenant or perms.hosting.view_hostingplan %}
|
||||
{% if account.hosting_plan and account.hosting_plan.mailbox_limit is not None %}
|
||||
<p class="heading-meta">{{ mailboxes|length }} of {{ account.hosting_plan.mailbox_limit }} mailboxes requested</p>
|
||||
@@ -292,7 +307,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingmailbox %}
|
||||
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
|
||||
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if mailboxes %}
|
||||
@@ -302,14 +317,23 @@
|
||||
<tr>
|
||||
<th scope="col">Email address</th>
|
||||
<th scope="col">Storage limit</th>
|
||||
{% if is_operator or manage_mailbox_provisioning %}<th scope="col">Deployment</th>{% endif %}
|
||||
<th scope="col">Status and actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for mailbox in mailboxes %}
|
||||
<tr>
|
||||
<td class="domain">
|
||||
{{ mailbox }}
|
||||
<th scope="row" class="domain">{{ mailbox }}</th>
|
||||
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
<td>
|
||||
<div class="table-actions">
|
||||
{% if manage_mailbox_provisioning %}
|
||||
{% url 'panel:mailbox_provision' mailbox.pk as provision_url %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %}
|
||||
{% else %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=False %}
|
||||
{% endif %}
|
||||
{% if not mailbox.provisioning %}<span class="status pending">Requested</span>{% endif %}
|
||||
{% if mailbox.pk in webmail_mailbox_ids %}
|
||||
<form method="post" action="{% url 'panel:roundcube_launch' mailbox.pk %}">
|
||||
{% csrf_token %}
|
||||
@@ -317,39 +341,29 @@
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if manage_mail_vacation %}
|
||||
<div><a class="record-link" href="{% url 'panel:mail_vacation' mailbox.pk %}" aria-label="Automatic replies for {{ mailbox }}">Automatic replies</a></div>
|
||||
<a class="record-link" href="{% url 'panel:mail_vacation' mailbox.pk %}" aria-label="Automatic replies for {{ mailbox }}">Automatic replies</a>
|
||||
{% endif %}
|
||||
{% if show_mailbox_credentials %}
|
||||
<div><a class="record-link" href="{% url 'panel:mailbox_credentials' mailbox.pk %}" aria-label="Connection details for {{ mailbox }}">Connection details</a></div>
|
||||
<a class="record-link" href="{% url 'panel:mailbox_credentials' mailbox.pk %}" aria-label="Connection details for {{ mailbox }}">Connection details</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
{% if is_operator or manage_mailbox_provisioning %}
|
||||
<td>
|
||||
<div class="form-actions">
|
||||
{% if is_operator %}
|
||||
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
|
||||
{% endif %}
|
||||
{% if change_mailbox_quota %}
|
||||
<a class="record-link" href="{% url 'panel:mailbox_quota' mailbox.pk %}" aria-label="Change storage limit for {{ mailbox }}">Change storage limit</a>
|
||||
{% endif %}
|
||||
{% if manage_mailbox_provisioning %}
|
||||
{% url 'panel:mailbox_provision' mailbox.pk as provision_url %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
|
||||
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
|
||||
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No mailboxes requested yet.</p>
|
||||
<p class="empty">No mailboxes yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@@ -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 %}
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Hosting accounts</h1>
|
||||
<p class="heading-meta">Manage domains and their hosting services. Link a customer to give them access.</p>
|
||||
<h1>{% if is_customer %}My hosting{% elif is_reseller %}Customer hosting{% else %}Hosting accounts{% endif %}</h1>
|
||||
{% if is_operator %}<p class="heading-meta">Manage domains and their hosting services. Link a customer to give them access.</p>{% endif %}
|
||||
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p>
|
||||
{% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %}
|
||||
</div>
|
||||
@@ -12,6 +12,17 @@
|
||||
<a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if health_summary %}
|
||||
<section class="surface section-heading" aria-label="Server status">
|
||||
<p>{% 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 %}</p>
|
||||
<a class="button secondary" href="{% url 'panel:service_health' %}">Service health</a>
|
||||
</section>
|
||||
{% elif is_reseller %}
|
||||
<section class="surface section-heading" aria-label="Customer access">
|
||||
<p>Manage the logins for your assigned customers.</p>
|
||||
<a class="button secondary" href="{% url 'panel:customers' %}">My customers</a>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="surface" aria-label="Hosting account list">
|
||||
<div class="toolbar account-toolbar">
|
||||
<form class="form-actions" method="get" action="{% url 'panel:accounts' %}" role="search">
|
||||
@@ -42,6 +53,13 @@
|
||||
<td>
|
||||
<a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a>
|
||||
<div class="domain muted account-domain">{{ account.primary_domain }}</div>
|
||||
{% if is_customer %}
|
||||
<div class="table-actions">
|
||||
{% if show_customer_website_link %}<a href="{{ account.get_absolute_url }}#websites">Websites</a>{% endif %}
|
||||
<a href="{{ account.get_absolute_url }}#domains-dns">Domains and DNS</a>
|
||||
<a href="{{ account.get_absolute_url }}#email">Email</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{% include "hosting/account_status.html" %}</td>
|
||||
{% if is_operator and perms.hosting.view_customer %}<td>{{ account.customer|default_if_none:"No customer linked" }}</td>{% endif %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<div><dt>DNS zones</dt><dd>{% for zone in inventory.zones %}{{ zone.domain }}{% if zone.published is not None %} (published serial {{ zone.published }}){% endif %}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}</dd></div>
|
||||
<div><dt>Existing backups</dt><dd>{{ inventory.backups }}</dd></div>
|
||||
{% if inventory.customer %}<div><dt>Customer</dt><dd>{{ inventory.customer }}</dd></div>{% endif %}
|
||||
{% if inventory.reseller %}<div><dt>Reseller</dt><dd>{{ inventory.reseller }}</dd></div>{% endif %}
|
||||
{% if inventory.reseller %}<div><dt>Customer manager</dt><dd>{{ inventory.reseller }}</dd></div>{% endif %}
|
||||
</dl>
|
||||
</section>
|
||||
{% if retirement %}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Complete hosting setup · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading"><div><h1>Complete hosting setup</h1><p class="domain">{{ account.primary_domain }}</p></div></header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<p>Choose which missing services to set up for this domain. Set up HTTPS once the domain resolves.</p>
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
{% if form.fields %}<button class="button primary" type="submit">Set up selected services</button>{% endif %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Back to account</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% if preview_records or preview_problem %}
|
||||
<section class="surface" aria-label="Proposed DNS records">
|
||||
<header class="section-heading"><h2>Proposed DNS records</h2></header>
|
||||
{% include "hosting/dns_record_table.html" with records=preview_records %}
|
||||
{% if preview_problem %}<p class="section-text">{{ preview_problem }}</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -30,13 +30,13 @@
|
||||
{% if is_tenant or perms.hosting.view_hostingaccount %}
|
||||
<a href="{% url 'panel:accounts' %}"{% if panel_section == 'accounts' %} aria-current="{% if current == 'accounts' %}page{% else %}location{% endif %}"{% endif %}>
|
||||
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
|
||||
Hosting accounts
|
||||
{% if is_customer %}My hosting{% else %}Hosting accounts{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if is_reseller or is_operator and perms.hosting.view_customer %}
|
||||
<a href="{% url 'panel:customers' %}"{% if panel_section == 'customers' %} aria-current="{% if current == 'customers' %}page{% else %}location{% endif %}"{% endif %}>
|
||||
<span class="nav-icon nav-icon-customers" aria-hidden="true"></span>
|
||||
Customers
|
||||
{% if is_reseller %}My customers{% else %}Customers{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if is_operator and perms.hosting.view_reseller %}
|
||||
@@ -53,7 +53,7 @@
|
||||
{% endif %}
|
||||
{% if group_customer_navigation %}</details>{% endif %}
|
||||
{% if is_operator and perms.hosting.view_servicehealth %}
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' %} open{% endif %}>
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' or panel_section == 'dns_defaults' or panel_section == 'updates' %} open{% endif %}>
|
||||
<summary>Server and services</summary>
|
||||
{% endif %}
|
||||
{% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
|
||||
@@ -71,6 +71,16 @@
|
||||
<span class="nav-icon nav-icon-information" aria-hidden="true">i</span>
|
||||
About Coulobre
|
||||
</a>
|
||||
{% if request.user.is_superuser %}
|
||||
<a href="{% url 'panel:updates' %}"{% if current == 'updates' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
Updates
|
||||
</a>
|
||||
<a href="{% url 'panel:dns_defaults' %}"{% if current == 'dns_defaults' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
DNS zone template
|
||||
</a>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Customers · Coulobre Panel{% endblock %}
|
||||
{% block title %}{% if is_reseller %}My customers{% else %}Customers{% endif %} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Customers</h1>
|
||||
<h1>{% if is_reseller %}My customers{% else %}Customers{% endif %}</h1>
|
||||
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p>
|
||||
</div>
|
||||
{% if is_operator and perms.hosting.add_customer %}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}DNS zone template · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div><h1>DNS zone template</h1><p class="heading-meta">These settings apply when you create a managed DNS zone.</p></div>
|
||||
</header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<button class="button primary" type="submit">Save template</button>
|
||||
</form>
|
||||
</section>
|
||||
<section class="surface" aria-label="Template preview">
|
||||
<header class="section-heading"><h2>Current template</h2></header>
|
||||
<dl class="details">
|
||||
<div><dt>Nameservers</dt><dd>{{ effective.nameservers|join:", "|default:"Not configured" }}</dd></div>
|
||||
<div><dt>Hosting IP addresses</dt><dd>{{ effective.addresses|join:", "|default:"Not configured" }}</dd></div>
|
||||
<div><dt>Website records</dt><dd>@{% if effective.include_www %}, www{% endif %}{% if effective.include_wildcard %}, *{% endif %}</dd></div>
|
||||
</dl>
|
||||
{% include "hosting/dns_record_table.html" with records=effective.records %}
|
||||
<p class="section-text">Coulobre adds mail records for domains you choose to manage. A DKIM record needs a provisioned signing key.</p>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,19 @@
|
||||
{{ form.editor_rows|json_script:"dns-record-data" }}
|
||||
<div data-dns-editor hidden>
|
||||
<h2>DNS records</h2>
|
||||
<p class="heading-meta">Use @ for the zone name, or enter a name such as www.</p>
|
||||
<div class="dns-editor-rows" data-dns-rows></div>
|
||||
<button class="button secondary" type="button" data-add-dns-record>Add record</button>
|
||||
<template data-dns-row>
|
||||
<fieldset class="dns-edit-row">
|
||||
<legend class="visually-hidden"></legend>
|
||||
<label>Name<input data-record-name placeholder="@" required></label>
|
||||
<label>Type<select data-record-type>
|
||||
<option>A</option><option>AAAA</option><option>CNAME</option><option>MX</option><option>TXT</option><option>SRV</option><option>CAA</option>
|
||||
</select></label>
|
||||
<label data-priority-label hidden>Priority<input data-record-priority type="number" min="0" max="65535" inputmode="numeric"></label>
|
||||
<label><span data-record-value-label>Value</span><textarea rows="1" data-record-value required></textarea></label>
|
||||
<button class="button secondary" type="button" data-remove-record>Remove</button>
|
||||
</fieldset>
|
||||
</template>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
{% if records %}
|
||||
<div class="table-scroll">
|
||||
<table class="dns-record-table">
|
||||
<thead><tr><th scope="col">Name</th><th scope="col">Type</th><th scope="col">Value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for record in records %}
|
||||
<tr><th scope="row" class="domain">{{ record.name }}</th><td>{{ record.type }}</td><td><code>{{ record.value }}</code></td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -1,4 +1,5 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% load static %}
|
||||
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
@@ -8,10 +9,33 @@
|
||||
<p class="heading-meta domain">{{ domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
<section class="surface section-text dns-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
{{ form.non_field_errors }}
|
||||
{% for hidden in form.hidden_fields %}
|
||||
{{ hidden.errors }}
|
||||
{% if hidden.name == 'record_rows' %}<input type="hidden" name="record_rows" value="">{% else %}{{ hidden }}{% endif %}
|
||||
{% endfor %}
|
||||
{% if not form.nameservers.is_hidden %}
|
||||
<details{% if form.nameservers.errors or form.responsible_name.errors or not form.nameservers.value %} open{% endif %}>
|
||||
<summary>Zone settings</summary>
|
||||
{{ form.nameservers.as_field_group }}
|
||||
{{ form.responsible_name.as_field_group }}
|
||||
{{ form.delegate_dns.as_field_group }}
|
||||
{{ form.manage_mail_dns.as_field_group }}
|
||||
</details>
|
||||
{% endif %}
|
||||
<div data-dns-text-fields>
|
||||
{{ form.addresses.as_field_group }}
|
||||
{{ form.mx_records.as_field_group }}
|
||||
{{ form.txt_records.as_field_group }}
|
||||
{{ form.extra_records.as_field_group }}
|
||||
</div>
|
||||
{% if not form.is_bound or form.record_rows.value %}
|
||||
{% include "hosting/dns_record_editor.html" %}
|
||||
<script src="{% static 'hosting/dns-record-editor.js' %}" defer></script>
|
||||
{% endif %}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Save zone</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
|
||||
@@ -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 %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Request mailbox</h1>
|
||||
<h1>{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox</h1>
|
||||
<p class="heading-meta domain">{{ account.primary_domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
@@ -14,7 +14,7 @@
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
{% if can_request_resource %}
|
||||
<button class="button primary" type="submit">Request mailbox</button>
|
||||
<button class="button primary" type="submit">{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox</button>
|
||||
{% endif %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<h1>{{ reseller }}</h1>
|
||||
{% if perms.hosting.change_reseller %}
|
||||
<a class="button secondary" href="{% url 'panel:manage_invitation' 'manager' reseller.pk %}">Contact and invitation</a>
|
||||
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit reseller</a>
|
||||
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit customer manager</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
<dl class="details surface">
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface" aria-label="Reseller list">
|
||||
<section class="surface" aria-label="Customer manager list">
|
||||
<form class="toolbar" method="get" action="{% url 'panel:resellers' %}" role="search">
|
||||
<label class="visually-hidden" for="reseller-search">Search by username</label>
|
||||
<input type="search" id="reseller-search" name="q" placeholder="Username" value="{{ search }}">
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Updates · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
|
||||
<a class="button secondary" href="{% url 'panel:updates' %}">Refresh status</a>
|
||||
</header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
|
||||
{% if update_status %}
|
||||
<section class="surface" aria-labelledby="update-status">
|
||||
<header class="section-heading"><h2 id="update-status">Latest update</h2><span>{{ update_status.target_version }}</span></header>
|
||||
<p class="section-text">{{ update_status.message }}</p>
|
||||
<p class="section-text muted">Requested by {{ update_status.actor }} · {{ update_status.updated_at }}</p>
|
||||
{% if update_status.state == "recovery_required" %}
|
||||
<p class="section-text">Review the updater journal and recovery files in <code>/var/lib/coulobre-update/</code> before starting another upgrade.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if not updater_enabled %}
|
||||
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed single server to use web updates.</p></section>
|
||||
{% elif catalog_problem %}
|
||||
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
||||
{% else %}
|
||||
<section class="surface" aria-labelledby="available-updates">
|
||||
<header class="section-heading"><h2 id="available-updates">Compatible releases</h2></header>
|
||||
{% for release in releases %}
|
||||
<details class="section-text">
|
||||
<summary>{{ release.version }}{% if release.prerelease %} · Prerelease{% endif %}</summary>
|
||||
{{ release.notes|linebreaks }}
|
||||
{% if may_apply and update_status.state != "running" and update_status.state != "recovery_required" %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="version" value="{{ release.version }}">
|
||||
<input type="hidden" name="sha256" value="{{ release.sha256 }}">
|
||||
<label><input type="checkbox" name="confirm" required> I reviewed this release and want to update this server.</label>
|
||||
<p class="heading-meta">The panel goes offline while the updater creates a recovery backup and installs the release.</p>
|
||||
<button class="button primary" type="submit">Install {{ release.version }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% empty %}
|
||||
<p class="empty">No compatible web updates are published.</p>
|
||||
{% endfor %}
|
||||
{% if releases and not may_apply %}<p class="section-text">Sign in with two-factor authentication to install an update.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -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}
|
||||
)
|
||||
@@ -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])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import json
|
||||
import socket
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
|
||||
from django import forms
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import FormView
|
||||
|
||||
from coulobre.local_update import SOCKET, display_status
|
||||
from coulobre.release_updates import (
|
||||
UpdateError,
|
||||
available_releases,
|
||||
version_key,
|
||||
)
|
||||
|
||||
|
||||
class UpdateForm(forms.Form):
|
||||
version = forms.CharField(max_length=32, widget=forms.HiddenInput)
|
||||
sha256 = forms.RegexField(
|
||||
regex=r"\A[0-9a-f]{64}\Z", widget=forms.HiddenInput
|
||||
)
|
||||
confirm = forms.BooleanField(
|
||||
label="I reviewed this release and want to update this server."
|
||||
)
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class UpdateView(UserPassesTestMixin, FormView):
|
||||
form_class = UpdateForm
|
||||
template_name = "hosting/updates.html"
|
||||
success_url = reverse_lazy("panel:updates")
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.is_superuser
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["update_status"] = display_status()
|
||||
context["updater_enabled"] = SOCKET.is_socket()
|
||||
context["may_apply"] = self.request.user.is_verified()
|
||||
try:
|
||||
installed = version("coulobre-panel")
|
||||
except PackageNotFoundError:
|
||||
context["catalog_problem"] = (
|
||||
"The installed release version is unavailable."
|
||||
)
|
||||
return context
|
||||
context["installed_version"] = installed
|
||||
if context["updater_enabled"]:
|
||||
try:
|
||||
context["releases"] = cache.get_or_set(
|
||||
f"coulobre-updates:{installed}",
|
||||
lambda: available_releases(installed),
|
||||
timeout=300,
|
||||
)
|
||||
except UpdateError as error:
|
||||
context["catalog_problem"] = str(error)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
if not self.request.user.is_verified():
|
||||
raise PermissionDenied
|
||||
payload = {
|
||||
"version": form.cleaned_data["version"],
|
||||
"sha256": form.cleaned_data["sha256"],
|
||||
"actor": self.request.user.get_username(),
|
||||
}
|
||||
try:
|
||||
version_key(payload["version"])
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(6)
|
||||
peer.connect(str(SOCKET))
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
with peer.makefile("rb") as reply:
|
||||
result = json.loads(reply.readline(4096))
|
||||
if not result.get("accepted"):
|
||||
raise UpdateError(result["message"])
|
||||
except (OSError, ValueError):
|
||||
form.add_error(
|
||||
None,
|
||||
"The local updater could not be reached. "
|
||||
"Check its socket and service logs.",
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
except UpdateError as error:
|
||||
form.add_error(None, str(error))
|
||||
return self.form_invalid(form)
|
||||
messages.success(
|
||||
self.request,
|
||||
"Update accepted. Check this page again after the panel restarts.",
|
||||
)
|
||||
return super().form_valid(form)
|
||||
@@ -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 (
|
||||
@@ -46,6 +47,7 @@ from .sign_in import (
|
||||
PanelLoginView,
|
||||
VerifyFactorView,
|
||||
)
|
||||
from .update_views import UpdateView
|
||||
from .website_file_views import WebsiteFilesView
|
||||
from .website_job_views import WebsiteJobEditor, WebsiteJobList
|
||||
from .website_usage_views import WebsiteUsageView
|
||||
@@ -54,6 +56,13 @@ app_name = "panel"
|
||||
|
||||
urlpatterns = [
|
||||
path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"),
|
||||
path("updates/", UpdateView.as_view(), name="updates"),
|
||||
path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"),
|
||||
path(
|
||||
"accounts/<int:pk>/setup/",
|
||||
views.ExistingAccountSetup.as_view(),
|
||||
name="account_setup",
|
||||
),
|
||||
path(
|
||||
"dns-zones/<int:pk>/replication/",
|
||||
DnsReplicaView.as_view(),
|
||||
|
||||
+255
-30
@@ -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)
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from pwd import getpwnam
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .release_updates import UpdateError, download_wheel, selected_release
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SOCKET = Path("/run/coulobre-update.sock")
|
||||
STATE = Path("/var/lib/coulobre-update")
|
||||
STATUS = STATE / "status.json"
|
||||
LOCK = STATE / "update.lock"
|
||||
PANEL = "coulobre-panel.service"
|
||||
BEAT = "coulobre-beat.service"
|
||||
WORKER = "coulobre-worker.service"
|
||||
MANAGED_UNITS = frozenset(
|
||||
{
|
||||
PANEL,
|
||||
BEAT,
|
||||
WORKER,
|
||||
"coulobre-health.timer",
|
||||
"coulobre-account-backup.socket",
|
||||
"coulobre-account-offsite.socket",
|
||||
"coulobre-account-restore.socket",
|
||||
"coulobre-backup-worker.service",
|
||||
"coulobre-database-apply.socket",
|
||||
"coulobre-database-provisioner.service",
|
||||
"coulobre-dns-apply.socket",
|
||||
"coulobre-dns-publisher.service",
|
||||
"coulobre-https-apply.socket",
|
||||
"coulobre-https-provisioner.service",
|
||||
"coulobre-mail-apply.socket",
|
||||
"coulobre-mail-archive-backup.socket",
|
||||
"coulobre-mail-archive-restore.socket",
|
||||
"coulobre-mail-credentials.socket",
|
||||
"coulobre-mailbox-provisioner.service",
|
||||
"coulobre-offsite-worker.service",
|
||||
"coulobre-provisioner.service",
|
||||
"coulobre-service-credentials.socket",
|
||||
"coulobre-sftp-apply.socket",
|
||||
"coulobre-sftp-provisioner.service",
|
||||
"coulobre-web-apply.socket",
|
||||
"coulobre-website-files.socket",
|
||||
"coulobre-website-job-worker.service",
|
||||
"coulobre-website-jobs.socket",
|
||||
"coulobre-website-usage.socket",
|
||||
}
|
||||
)
|
||||
VENV = Path("/opt/coulobre")
|
||||
PYTHON = VENV / "bin/python"
|
||||
CONFIG = Path("/etc/coulobre/panel.env")
|
||||
INSTALLATION = Path("/var/lib/coulobre-installer/installation.json")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
REMOTE_RELAY = (
|
||||
"coulobre-dns-apply@.service.d/remote.conf",
|
||||
"coulobre-mail-apply@.service.d/remote.conf",
|
||||
)
|
||||
ROOT_COMMAND_ENV = {
|
||||
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"LC_ALL": "C.UTF-8",
|
||||
}
|
||||
|
||||
|
||||
def read_status():
|
||||
try:
|
||||
payload = json.loads(STATUS.read_text())
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def publish_status(status, state, message):
|
||||
status.update(
|
||||
state=state, message=message, updated_at=datetime.now(UTC).isoformat()
|
||||
)
|
||||
staged = STATUS.with_suffix(".new")
|
||||
with staged.open("w", encoding="utf-8") as stream:
|
||||
json.dump(status, stream)
|
||||
stream.write("\n")
|
||||
os.fchmod(stream.fileno(), 0o644)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
staged.replace(STATUS)
|
||||
directory = os.open(STATUS.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
if state != "running":
|
||||
LOGGER.info(
|
||||
"Update %s for %s requested by %s. %s",
|
||||
state,
|
||||
status.get("target_version"),
|
||||
status.get("actor"),
|
||||
message,
|
||||
)
|
||||
|
||||
|
||||
def display_status():
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
try:
|
||||
with LOCK.open("rb") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
status.update(
|
||||
state="recovery_required",
|
||||
message=(
|
||||
"The update was interrupted. "
|
||||
"Review the recovery files."
|
||||
),
|
||||
)
|
||||
except OSError:
|
||||
pass # The worker holds the lock, or the updater is unavailable.
|
||||
return status
|
||||
|
||||
|
||||
def root_controlled(path):
|
||||
info = path.lstat()
|
||||
return (
|
||||
info.st_uid == 0
|
||||
and not info.st_mode & 0o022
|
||||
and not stat.S_ISLNK(info.st_mode)
|
||||
)
|
||||
|
||||
|
||||
def check_installation():
|
||||
try:
|
||||
if not all(
|
||||
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
|
||||
):
|
||||
raise ValueError
|
||||
installation = json.loads(INSTALLATION.read_text())
|
||||
plan = installation["plan"]
|
||||
if installation.get("complete") is not True or not all(
|
||||
plan[role]["mode"] in {"local", "off"} for role in ("dns", "mail")
|
||||
):
|
||||
raise ValueError
|
||||
if (
|
||||
any((SYSTEMD / relay).exists() for relay in REMOTE_RELAY)
|
||||
or Path("/etc/coulobre-remote").exists()
|
||||
):
|
||||
raise ValueError
|
||||
if (
|
||||
os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
||||
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
||||
):
|
||||
raise ValueError
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise UpdateError(
|
||||
"Web updates require a complete single-server installation "
|
||||
"with the installer-managed MariaDB database."
|
||||
) from error
|
||||
return plan["hostname"]
|
||||
|
||||
|
||||
def run(*args, log, timeout=900, stdout=None, umask=-1):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
check=True,
|
||||
timeout=timeout,
|
||||
env=ROOT_COMMAND_ENV,
|
||||
stdout=stdout if stdout is not None else subprocess.PIPE,
|
||||
stderr=log,
|
||||
stdin=subprocess.DEVNULL,
|
||||
umask=umask,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise UpdateError(
|
||||
f"{Path(args[0]).name} failed. Check the private update log."
|
||||
) from error
|
||||
return (result.stdout or b"").decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def active_units(log):
|
||||
listing = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"--full",
|
||||
"coulobre-*",
|
||||
log=log,
|
||||
)
|
||||
return [
|
||||
unit
|
||||
for line in listing.splitlines()
|
||||
if line.strip()
|
||||
if (unit := line.split()[0]) in MANAGED_UNITS
|
||||
]
|
||||
|
||||
|
||||
def systemctl(action, units, log):
|
||||
if units:
|
||||
run("/usr/bin/systemctl", action, *units, log=log)
|
||||
|
||||
|
||||
def manage(*args, log):
|
||||
run(
|
||||
"/usr/bin/systemd-run",
|
||||
"--wait",
|
||||
"--pipe",
|
||||
"--collect",
|
||||
"--quiet",
|
||||
"--uid=coulobre-panel",
|
||||
"--property=EnvironmentFile=/etc/coulobre/panel.env",
|
||||
PYTHON,
|
||||
"-m",
|
||||
"django",
|
||||
*args,
|
||||
log=log,
|
||||
)
|
||||
|
||||
|
||||
def verify_panel(hostname, release, log):
|
||||
installed = run(
|
||||
PYTHON,
|
||||
"-c",
|
||||
"from importlib.metadata import version; "
|
||||
"print(version('coulobre-panel'))",
|
||||
log=log,
|
||||
).strip()
|
||||
if installed != release.version:
|
||||
raise UpdateError(
|
||||
"The installed version differs from the selected release."
|
||||
)
|
||||
request = (
|
||||
f"GET /sign-in/ HTTP/1.0\r\nHost: {hostname}\r\n"
|
||||
"X-Forwarded-Proto: https\r\n\r\n"
|
||||
)
|
||||
for _ in range(20):
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(2)
|
||||
peer.connect("/run/coulobre-panel/panel.sock")
|
||||
peer.sendall(request.encode("ascii"))
|
||||
with peer.makefile("rb") as reply:
|
||||
if reply.readline(256).split()[1:2] == [b"200"]:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise UpdateError(
|
||||
"The upgraded panel did not respond to the sign-in check."
|
||||
)
|
||||
|
||||
|
||||
def back_up(backup, log):
|
||||
shutil.copytree(VENV, backup / "venv", symlinks=True)
|
||||
shutil.copytree(CONFIG.parent, backup / "config", symlinks=True)
|
||||
with (backup / "panel.sql").open("xb") as dump:
|
||||
run(
|
||||
"/usr/bin/mariadb-dump",
|
||||
"--protocol=socket",
|
||||
"--user=root",
|
||||
"--socket=/run/mysqld/mysqld.sock",
|
||||
"--single-transaction",
|
||||
"--add-drop-database",
|
||||
"--databases",
|
||||
"coulobre_panel",
|
||||
stdout=dump,
|
||||
log=log,
|
||||
)
|
||||
if (backup / "panel.sql").stat().st_size == 0:
|
||||
raise UpdateError("The database recovery dump is empty.")
|
||||
|
||||
|
||||
def apply_update(status, request, hostname):
|
||||
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
||||
backup.mkdir(mode=0o700)
|
||||
status["recovery"] = backup.name
|
||||
changed = False
|
||||
stopped = []
|
||||
with (
|
||||
(backup / "update.log").open("xb") as log,
|
||||
TemporaryDirectory(dir=STATE) as download,
|
||||
):
|
||||
try:
|
||||
release = selected_release(
|
||||
request["version"],
|
||||
status["installed_version"],
|
||||
request["sha256"],
|
||||
)
|
||||
publish_status(status, "running", "Verifying the release package.")
|
||||
wheel = download_wheel(release, download)
|
||||
active = active_units(log)
|
||||
if not {PANEL, BEAT, WORKER} <= set(active):
|
||||
raise UpdateError(
|
||||
"Start the panel, scheduler and worker before updating."
|
||||
)
|
||||
publish_status(
|
||||
status, "running", "Stopping the panel and its workers."
|
||||
)
|
||||
sockets = [
|
||||
unit for unit in active if unit.endswith((".socket", ".timer"))
|
||||
]
|
||||
services = [
|
||||
unit
|
||||
for unit in active
|
||||
if unit not in {PANEL, BEAT} and unit.endswith(".service")
|
||||
]
|
||||
stopped = active
|
||||
systemctl("stop", [PANEL, BEAT, *sockets], log)
|
||||
if "coulobre-health.timer" in active:
|
||||
systemctl("stop", ["coulobre-health.service"], log)
|
||||
systemctl("stop", services, log)
|
||||
if "Result=timeout" in run(
|
||||
"/usr/bin/systemctl",
|
||||
"show",
|
||||
"-p",
|
||||
"Result",
|
||||
*services,
|
||||
log=log,
|
||||
):
|
||||
raise UpdateError(
|
||||
"A worker did not shut down cleanly. "
|
||||
"Finish its jobs before retrying."
|
||||
)
|
||||
pending = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"coulobre-*@*.service",
|
||||
log=log,
|
||||
)
|
||||
if any(
|
||||
not line.startswith("coulobre-update@")
|
||||
for line in pending.splitlines()
|
||||
if line.strip()
|
||||
):
|
||||
raise UpdateError(
|
||||
"A provisioning service is still running. "
|
||||
"Retry after it finishes."
|
||||
)
|
||||
(backup / "units.json").write_text(json.dumps(active))
|
||||
publish_status(status, "running", "Creating the recovery backup.")
|
||||
back_up(backup, log)
|
||||
publish_status(
|
||||
status, "running", "Installing the verified release."
|
||||
)
|
||||
changed = True
|
||||
run(
|
||||
PYTHON,
|
||||
"-m",
|
||||
"pip",
|
||||
"--isolated",
|
||||
"install",
|
||||
"--no-index",
|
||||
"--no-deps",
|
||||
wheel,
|
||||
log=log,
|
||||
umask=0o022,
|
||||
)
|
||||
run(PYTHON, "-m", "pip", "check", log=log)
|
||||
publish_status(
|
||||
status,
|
||||
"running",
|
||||
"Applying migrations and collecting static files.",
|
||||
)
|
||||
manage("check", log=log)
|
||||
manage("migrate", "--noinput", log=log)
|
||||
manage("collectstatic", "--noinput", log=log)
|
||||
publish_status(
|
||||
status, "running", "Starting services and verifying the panel."
|
||||
)
|
||||
systemctl("start", stopped, log)
|
||||
if not set(active) <= set(active_units(log)):
|
||||
raise UpdateError("Some panel services did not restart.")
|
||||
verify_panel(hostname, release, log)
|
||||
status["installed_version"] = release.version
|
||||
publish_status(
|
||||
status,
|
||||
"succeeded",
|
||||
"The updated panel responded and its services restarted.",
|
||||
)
|
||||
except (OSError, UpdateError) as error:
|
||||
if not changed:
|
||||
try:
|
||||
systemctl("start", stopped, log)
|
||||
except UpdateError:
|
||||
changed = True
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "An update operation failed. Check the private log."
|
||||
)
|
||||
publish_status(
|
||||
status, "recovery_required" if changed else "failed", message
|
||||
)
|
||||
|
||||
|
||||
def read_request(peer):
|
||||
peer.settimeout(4)
|
||||
caller = peer.getsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
|
||||
)
|
||||
_, uid, _ = struct.unpack("3i", caller)
|
||||
if uid != getpwnam("coulobre-panel").pw_uid:
|
||||
raise UpdateError("Only the Coulobre panel can request updates.")
|
||||
with peer.makefile("rb") as stream:
|
||||
request = json.loads(stream.readline(2048))
|
||||
if not isinstance(request, dict) or set(request) != {
|
||||
"version",
|
||||
"sha256",
|
||||
"actor",
|
||||
}:
|
||||
raise UpdateError("The update request is invalid.")
|
||||
if not all(
|
||||
isinstance(value, str)
|
||||
and value
|
||||
and len(value) <= 160
|
||||
and value.isprintable()
|
||||
for value in request.values()
|
||||
):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
return request
|
||||
|
||||
|
||||
def reply(peer, **payload):
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
|
||||
|
||||
def handle_request(peer):
|
||||
request = read_request(peer)
|
||||
with LOCK.open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as error:
|
||||
raise UpdateError("An update is already running.") from error
|
||||
os.fchmod(lock.fileno(), 0o644)
|
||||
previous = read_status()
|
||||
if previous.get("state") == "running":
|
||||
publish_status(
|
||||
previous,
|
||||
"recovery_required",
|
||||
"The previous update was interrupted. "
|
||||
"Review the recovery files.",
|
||||
)
|
||||
if previous.get("state") == "recovery_required":
|
||||
raise UpdateError(
|
||||
"Resolve the previous update before starting another one."
|
||||
)
|
||||
installed = version("coulobre-panel")
|
||||
status = {
|
||||
"installed_version": installed,
|
||||
"target_version": request["version"],
|
||||
"actor": request["actor"],
|
||||
}
|
||||
LOGGER.info(
|
||||
"Update from %s to %s requested by %s.",
|
||||
installed,
|
||||
status["target_version"],
|
||||
status["actor"],
|
||||
)
|
||||
try:
|
||||
hostname = check_installation()
|
||||
except UpdateError as error:
|
||||
publish_status(status, "failed", str(error))
|
||||
raise
|
||||
publish_status(status, "running", "Checking release compatibility.")
|
||||
reply(peer, accepted=True)
|
||||
peer.close()
|
||||
apply_update(status, request, hostname)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
with socket.socket(fileno=0) as peer:
|
||||
try:
|
||||
handle_request(peer)
|
||||
except (OSError, ValueError, UpdateError) as error:
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "Could not accept the update request."
|
||||
)
|
||||
with suppress(OSError):
|
||||
reply(peer, accepted=False, message=message)
|
||||
@@ -0,0 +1,187 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
ORIGIN = "https://code.hosting.hippogrief.nl"
|
||||
REPOSITORY = "hippogrief/coulobre"
|
||||
MANIFEST = "web-update.json"
|
||||
VERSION = re.compile(
|
||||
r"(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(?:rc([1-9][0-9]{0,5}))?"
|
||||
)
|
||||
SHA256 = re.compile(r"[0-9a-f]{64}")
|
||||
MAX_WHEEL = 32 * 1024 * 1024
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def version_key(value):
|
||||
match = VERSION.fullmatch(value) if isinstance(value, str) else None
|
||||
if match is None:
|
||||
raise UpdateError("Use a published Coulobre release version.")
|
||||
major, minor, patch, candidate = match.groups()
|
||||
return (
|
||||
int(major),
|
||||
int(minor),
|
||||
int(patch),
|
||||
candidate is None,
|
||||
int(candidate or 0),
|
||||
)
|
||||
|
||||
|
||||
def release_tag(version):
|
||||
version_key(version)
|
||||
base, marker, candidate = version.partition("rc")
|
||||
return f"v{base}-rc.{candidate}" if marker else f"v{base}"
|
||||
|
||||
|
||||
def wheel_name(version):
|
||||
version_key(version)
|
||||
return f"coulobre_panel-{version}-py3-none-any.whl"
|
||||
|
||||
|
||||
def open_project(path):
|
||||
headers = {"User-Agent": "Coulobre Panel updater"}
|
||||
return build_opener(NoRedirect()).open(
|
||||
Request(ORIGIN + path, headers=headers), timeout=8
|
||||
)
|
||||
|
||||
|
||||
def read_json(path, limit=1024 * 1024):
|
||||
try:
|
||||
with open_project(path) as reply:
|
||||
content = reply.read(limit + 1)
|
||||
if len(content) > limit:
|
||||
raise UpdateError("The release response is larger than expected.")
|
||||
return json.loads(content)
|
||||
except (ValueError, OSError, RecursionError) as error:
|
||||
raise UpdateError(
|
||||
"Could not read the published Coulobre release."
|
||||
) from error
|
||||
|
||||
|
||||
def release_asset_path(version, name):
|
||||
return f"/{REPOSITORY}/releases/download/{release_tag(version)}/{name}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Release:
|
||||
version: str
|
||||
notes: str
|
||||
prerelease: bool
|
||||
sha256: str
|
||||
|
||||
|
||||
def compatible_release(item, installed):
|
||||
if not isinstance(item, dict) or item.get("draft") is not False:
|
||||
return None
|
||||
tag = item.get("tag_name")
|
||||
if not isinstance(tag, str) or not tag.startswith("v"):
|
||||
return None
|
||||
version = tag[1:].replace("-rc.", "rc")
|
||||
try:
|
||||
if release_tag(version) != tag or version_key(version) <= version_key(
|
||||
installed
|
||||
):
|
||||
return None
|
||||
except UpdateError:
|
||||
return None
|
||||
assets = item.get("assets")
|
||||
if not isinstance(assets, list):
|
||||
return None
|
||||
names = {
|
||||
asset.get("name")
|
||||
for asset in assets
|
||||
if isinstance(asset, dict) and isinstance(asset.get("name"), str)
|
||||
}
|
||||
if not {MANIFEST, wheel_name(version)} <= names:
|
||||
return None
|
||||
manifest = read_json(release_asset_path(version, MANIFEST), limit=8192)
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("schema") != 1
|
||||
or manifest.get("version") != version
|
||||
or not isinstance(manifest.get("upgrade_from"), list)
|
||||
or not isinstance(manifest.get("sha256"), str)
|
||||
or not SHA256.fullmatch(manifest["sha256"])
|
||||
):
|
||||
raise UpdateError("The published update manifest is invalid.")
|
||||
if installed not in manifest["upgrade_from"]:
|
||||
return None
|
||||
return Release(
|
||||
version,
|
||||
str(item.get("body") or "")[:12000],
|
||||
"rc" in version or bool(item.get("prerelease")),
|
||||
manifest["sha256"],
|
||||
)
|
||||
|
||||
|
||||
def available_releases(installed):
|
||||
version_key(installed)
|
||||
items = read_json(f"/api/v1/repos/{REPOSITORY}/releases?limit=10")
|
||||
if not isinstance(items, list):
|
||||
raise UpdateError("The release catalog is invalid.")
|
||||
releases = [
|
||||
release
|
||||
for item in items
|
||||
if (release := compatible_release(item, installed))
|
||||
]
|
||||
return sorted(
|
||||
releases,
|
||||
key=lambda release: version_key(release.version),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def selected_release(version, installed, digest):
|
||||
tag = release_tag(version)
|
||||
item = read_json(f"/api/v1/repos/{REPOSITORY}/releases/tags/{tag}")
|
||||
release = compatible_release(item, installed)
|
||||
if (
|
||||
release is None
|
||||
or release.version != version
|
||||
or release.sha256 != digest
|
||||
):
|
||||
raise UpdateError(
|
||||
"The selected release changed or is incompatible. "
|
||||
"Review the catalog again."
|
||||
)
|
||||
return release
|
||||
|
||||
|
||||
def download_wheel(release, directory):
|
||||
name = wheel_name(release.version)
|
||||
dest = Path(directory) / name
|
||||
digest = hashlib.sha256()
|
||||
total = 0
|
||||
try:
|
||||
with (
|
||||
open_project(release_asset_path(release.version, name)) as reply,
|
||||
dest.open("xb") as output,
|
||||
):
|
||||
while chunk := reply.read(65536):
|
||||
total += len(chunk)
|
||||
if total > MAX_WHEEL:
|
||||
raise UpdateError(
|
||||
"The release package is larger than expected."
|
||||
)
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
except OSError as error:
|
||||
raise UpdateError(
|
||||
"Could not download the Coulobre release package."
|
||||
) from error
|
||||
if digest.hexdigest() != release.sha256:
|
||||
raise UpdateError(
|
||||
"The release package does not match its published checksum."
|
||||
)
|
||||
return dest
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
|
||||
from . import local_update, release_updates
|
||||
from .release_updates import Release, UpdateError
|
||||
|
||||
|
||||
class ReleaseCatalogTests(TestCase):
|
||||
def test_requires_compatible_published_manifest_and_marks_candidates(self):
|
||||
target = "0.10.1rc2"
|
||||
installed = "0.10.1rc1"
|
||||
item = {
|
||||
"draft": False,
|
||||
"tag_name": "v0.10.1-rc.2",
|
||||
"prerelease": False,
|
||||
"assets": [
|
||||
{"name": "web-update.json"},
|
||||
{"name": release_updates.wheel_name(target)},
|
||||
],
|
||||
}
|
||||
manifest = {
|
||||
"schema": 1,
|
||||
"version": target,
|
||||
"upgrade_from": [installed],
|
||||
"sha256": "a" * 64,
|
||||
}
|
||||
with patch(
|
||||
"coulobre.release_updates.read_json", return_value=manifest
|
||||
):
|
||||
release = release_updates.compatible_release(item, installed)
|
||||
self.assertTrue(release.prerelease)
|
||||
self.assertEqual(release.version, target)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(
|
||||
item | {"draft": True}, installed
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.0rc1")
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.1")
|
||||
)
|
||||
|
||||
def test_rejects_a_package_with_the_wrong_checksum(self):
|
||||
release = Release(
|
||||
"0.10.1rc2", "", True, hashlib.sha256(b"expected").hexdigest()
|
||||
)
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.release_updates.open_project",
|
||||
return_value=BytesIO(b"other"),
|
||||
),
|
||||
self.assertRaisesRegex(UpdateError, "published checksum"),
|
||||
):
|
||||
release_updates.download_wheel(release, directory)
|
||||
|
||||
|
||||
class LocalUpdateStatusTests(TestCase):
|
||||
def test_orphaned_running_state_is_visible_after_a_restart(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
lock = root / "update.lock"
|
||||
lock.touch()
|
||||
with patch.multiple(
|
||||
local_update, STATUS=root / "status.json", LOCK=lock
|
||||
):
|
||||
local_update.publish_status(
|
||||
{}, "running", "Applying migrations."
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "recovery_required"
|
||||
)
|
||||
with lock.open("a") as active:
|
||||
local_update.fcntl.flock(
|
||||
active, local_update.fcntl.LOCK_EX
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "running"
|
||||
)
|
||||
|
||||
def test_fails_preflight_before_mutating_packages_or_services(self):
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.local_update.selected_release",
|
||||
side_effect=UpdateError("Incompatible release."),
|
||||
),
|
||||
patch("coulobre.local_update.run") as commands,
|
||||
):
|
||||
root = Path(directory)
|
||||
with patch.multiple(
|
||||
local_update, STATE=root, STATUS=root / "status.json"
|
||||
):
|
||||
local_update.apply_update(
|
||||
{"installed_version": "0.10.1rc1"},
|
||||
{"version": "0.10.1rc2", "sha256": "a" * 64},
|
||||
"panel.example.net",
|
||||
)
|
||||
self.assertEqual(local_update.read_status()["state"], "failed")
|
||||
self.assertFalse(commands.called)
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import shlex
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -69,7 +70,7 @@ class InstallerParametersTests(unittest.TestCase):
|
||||
"rabbitmq",
|
||||
]
|
||||
self.assertEqual(
|
||||
json.loads(env["COULOBRE_SERVICE_HEALTH"]),
|
||||
json.loads(shlex.split(env["COULOBRE_SERVICE_HEALTH"])[0]),
|
||||
{"panel": {"local": base + extras}},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Describe a reviewed wheel for the web updater."
|
||||
)
|
||||
parser.add_argument("wheel", type=Path)
|
||||
parser.add_argument("upgrade_from", nargs="+")
|
||||
args = parser.parse_args()
|
||||
version_pattern = r"\d+\.\d+\.\d+(?:rc\d+)?"
|
||||
match = re.fullmatch(
|
||||
rf"coulobre_panel-({version_pattern})-py3-none-any\.whl",
|
||||
args.wheel.name,
|
||||
)
|
||||
if match is None or any(
|
||||
not re.fullmatch(version_pattern, item) for item in args.upgrade_from
|
||||
):
|
||||
parser.error("Use a Coulobre wheel and the tested installed versions.")
|
||||
with args.wheel.open("rb") as wheel:
|
||||
checksum = hashlib.file_digest(wheel, "sha256").hexdigest()
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"version": match[1],
|
||||
"upgrade_from": args.upgrade_from,
|
||||
"sha256": checksum,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user