diff --git a/deploy/systemd/coulobre-account-backup@.service b/deploy/systemd/coulobre-account-backup@.service
index 737b868..12e6d59 100644
--- a/deploy/systemd/coulobre-account-backup@.service
+++ b/deploy/systemd/coulobre-account-backup@.service
@@ -19,3 +19,4 @@ NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
+ReadWritePaths=-/srv/coulobre/web -/var/lib/coulobre/web-node
diff --git a/deploy/systemd/coulobre-operator-apply.socket b/deploy/systemd/coulobre-operator-apply.socket
new file mode 100644
index 0000000..bb8bd4c
--- /dev/null
+++ b/deploy/systemd/coulobre-operator-apply.socket
@@ -0,0 +1,14 @@
+[Unit]
+Description=Coulobre operator action socket
+
+[Socket]
+ListenStream=/run/coulobre-operator-apply.sock
+SocketUser=root
+SocketGroup=coulobre-operator
+SocketMode=0660
+Accept=yes
+MaxConnections=1
+RemoveOnStop=true
+
+[Install]
+WantedBy=sockets.target
diff --git a/deploy/systemd/coulobre-operator-apply@.service b/deploy/systemd/coulobre-operator-apply@.service
new file mode 100644
index 0000000..38830c0
--- /dev/null
+++ b/deploy/systemd/coulobre-operator-apply@.service
@@ -0,0 +1,17 @@
+[Unit]
+Description=Coulobre allowlisted operator action
+CollectMode=inactive-or-failed
+
+[Service]
+Type=exec
+User=root
+EnvironmentFile=/etc/coulobre/panel.env
+StateDirectory=coulobre/operator
+StateDirectoryMode=0700
+ExecStart=/opt/coulobre/bin/coulobre-operator-node
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+RuntimeMaxSec=35min
+UMask=0077
+PrivateTmp=true
diff --git a/deploy/systemd/coulobre-operator-worker.service b/deploy/systemd/coulobre-operator-worker.service
new file mode 100644
index 0000000..bed036d
--- /dev/null
+++ b/deploy/systemd/coulobre-operator-worker.service
@@ -0,0 +1,23 @@
+[Unit]
+Description=Coulobre worker for local operator actions
+Wants=network-online.target
+After=network-online.target mariadb.service rabbitmq-server.service
+
+[Service]
+Type=exec
+User=coulobre-operator
+Group=coulobre-operator
+EnvironmentFile=/etc/coulobre/panel.env
+WorkingDirectory=/opt/coulobre
+UMask=0077
+ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-operator-actions --hostname=operator@%H --concurrency=1
+KillMode=mixed
+Restart=on-failure
+RestartSec=5s
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectHome=true
+ProtectSystem=strict
+
+[Install]
+WantedBy=multi-user.target
diff --git a/docs/deployment.md b/docs/deployment.md
index 4057fa8..63eebb1 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -2874,3 +2874,47 @@ On the panel, set `COULOBRE_DNS_REPLICATION_ADDRESSES` with the primary
then the secondary query IP, separated by a comma. Restart the panel
and select **Check replication** from a DNS zone to compare live
authoritative SOA serials.
+
+## Enable local operator actions
+
+The operator action worker handles allowlisted service reloads and restarts,
+MariaDB status reports, and reviewed server package updates. Install it on
+the panel host from the same release as the panel. The worker uses a dedicated
+system account and can contact the root-owned socket. Operators must have a
+verified second factor to request an action in the panel.
+
+```bash
+sudo adduser --system --group --no-create-home coulobre-operator
+sudo install -m 0644 deploy/systemd/coulobre-operator-apply.socket \
+ deploy/systemd/coulobre-operator-apply@.service \
+ deploy/systemd/coulobre-operator-worker.service /etc/systemd/system/
+sudo systemctl daemon-reload
+sudo systemctl enable --now coulobre-operator-apply.socket \
+ coulobre-operator-worker.service
+```
+
+To enable APT actions, set `COULOBRE_SERVER_PACKAGE_UPDATES=1` in
+`/etc/coulobre/panel.env`. Open **System → Updates → Server package updates**
+and request a preview. The receiver refreshes package indexes and records the
+proposed versions. Applying a preview requires confirmation and a fresh
+matching package plan. Use the job history and the host's package logs to
+review the result.
+
+## Customer backup exports and restores
+
+When the website, SFTP login and local account-backup worker are enabled,
+customers can request an archive for their selected hosting account. The
+latest completed export is available at `/backups/latest.zip` over SFTP. The
+worker writes the archive into the account's root-owned backup directory and
+assigns read access to the account's hosting login.
+
+The panel offers restore previews for components included in an eligible
+archive made by that customer. The selected website, database or mailbox
+must still belong to the account. A full website restore needs an empty
+document root, and database and mailbox destinations must be ready for
+restore. The worker reports progress and completion in **Backup & Restore**.
+
+For upgrades with local backups already enabled, install the current
+`coulobre-account-backup@.service` from the release before relying on SFTP
+exports. The unit needs write access to the managed web and web-node
+directories to publish the customer copy.
diff --git a/pyproject.toml b/pyproject.toml
index cda5670..77216f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -28,6 +28,7 @@ coulobre-directadmin = "coulobre.directadmin:main"
coulobre-dns-node = "coulobre.dns_node:main"
coulobre-firewall = "coulobre.firewall:main"
coulobre-mail-node = "coulobre.mail_node:main"
+coulobre-operator-node = "coulobre.operator_node:main"
coulobre-node-setup = "coulobre.node_setup:main"
coulobre-service-credentials = "coulobre.service_credentials:main"
coulobre-service-health = "coulobre.service_health:main"
diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py
index ed8a907..2dc51de 100644
--- a/src/coulobre/account_backup.py
+++ b/src/coulobre/account_backup.py
@@ -20,6 +20,7 @@ from .web_node import WebSite
BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
+SELECTIVE_MANIFEST_VERSION = 4
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
@@ -32,8 +33,13 @@ class AccountBackup:
databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
+ include_website: bool = True
def __post_init__(self):
+ if type(self.include_website) is not bool or (
+ not self.include_website and self.additional_websites
+ ):
+ raise ValueError("Choose whether to include the account websites.")
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
@@ -83,6 +89,9 @@ class AccountBackup:
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
+ if not self.include_website:
+ manifest["version"] = SELECTIVE_MANIFEST_VERSION
+ manifest["include_website"] = False
return manifest
@classmethod
@@ -94,13 +103,20 @@ class AccountBackup:
BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
+ SELECTIVE_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
+ if version == SELECTIVE_MANIFEST_VERSION:
+ fields.add("include_website")
+ if data.get("include_website") is not False:
+ raise ValueError("Expected a selective account backup.")
if version == MAIL_MANIFEST_VERSION or (
- version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data
+ version
+ in (MULTI_SITE_MANIFEST_VERSION, SELECTIVE_MANIFEST_VERSION)
+ and "mailboxes" in data
):
fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list):
@@ -124,10 +140,12 @@ class AccountBackup:
),
mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
+ data.get("include_website", True),
)
def components(self):
- yield self.website, "website.json", "website.tar.gz"
+ if self.include_website:
+ yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
diff --git a/src/coulobre/account_backup_request.py b/src/coulobre/account_backup_request.py
index c7eb16b..1b737ba 100644
--- a/src/coulobre/account_backup_request.py
+++ b/src/coulobre/account_backup_request.py
@@ -17,6 +17,7 @@ from .node_requests import serve_apply_request
REQUEST_VERSION = 1
REMOTE_MAIL_VERSION = 2
+CUSTOMER_EXPORT_VERSION = 3
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
BACKUP_TIMEOUT_SECONDS = 30 * 60
@@ -27,33 +28,53 @@ class AccountBackupRequest:
backup_id: UUID
backup: AccountBackup
remote_mail: bool = False
+ publish_to_customer: bool = False
@classmethod
def from_manifest(cls, data):
+ if not isinstance(data, dict) or type(data.get("version")) is not int:
+ raise ValueError("Expected a local account backup request.")
+ version = data["version"]
+ fields = {"version", "backup_id", "backup"}
+ if version == CUSTOMER_EXPORT_VERSION:
+ fields.add("remote_mail")
if (
- not isinstance(data, dict)
- or data.keys() != {"version", "backup_id", "backup"}
- or type(data["version"]) is not int
- or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
+ data.keys() != fields
+ or version
+ not in (
+ REQUEST_VERSION,
+ REMOTE_MAIL_VERSION,
+ CUSTOMER_EXPORT_VERSION,
+ )
or not isinstance(data["backup_id"], str)
+ or type(data.get("remote_mail", False)) is not bool
):
raise ValueError("Expected a local account backup request.")
backup_id = UUID(data["backup_id"])
if str(backup_id) != data["backup_id"]:
raise ValueError("Expected a canonical backup ID.")
backup = AccountBackup.from_manifest(data["backup"])
- remote_mail = data["version"] == REMOTE_MAIL_VERSION
+ remote_mail = version == REMOTE_MAIL_VERSION or data.get(
+ "remote_mail", False
+ )
if remote_mail and backup.mailboxes is None:
raise ValueError(
"Expected mailboxes in the remote backup request."
)
- return cls(backup_id, backup, remote_mail)
+ return cls(
+ backup_id, backup, remote_mail, version == CUSTOMER_EXPORT_VERSION
+ )
def manifest(self):
return {
"version": self.version,
"backup_id": str(self.backup_id),
"backup": self.backup.manifest(),
+ **(
+ {"remote_mail": self.remote_mail}
+ if self.publish_to_customer
+ else {}
+ ),
}
def identity(self):
@@ -65,6 +86,8 @@ class AccountBackupRequest:
@property
def version(self):
+ if self.publish_to_customer:
+ return CUSTOMER_EXPORT_VERSION
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
@@ -120,6 +143,10 @@ def create_requested_backup(request):
)
with locked_root_directory(BACKUP_DIRECTORY):
archive = ensure_requested_archive(request)
+ if request.publish_to_customer:
+ from .customer_backup_export import export_latest_backup
+
+ export_latest_backup(request.backup.website, archive)
return {"archive_bytes": archive.stat().st_size}
diff --git a/src/coulobre/customer_backup_export.py b/src/coulobre/customer_backup_export.py
new file mode 100644
index 0000000..c97ae4f
--- /dev/null
+++ b/src/coulobre/customer_backup_export.py
@@ -0,0 +1,74 @@
+import fcntl
+import os
+import shutil
+import stat
+from pathlib import Path
+from tempfile import NamedTemporaryFile
+
+from .node_files import check_root_file, require_root_directory
+from .web_node_apply import (
+ SitePaths,
+ check_reservation,
+ current_user,
+ locked_web_node,
+)
+
+
+def export_latest_backup(site, archive):
+ # A root-owned directory protects the published export.
+ with locked_web_node(fcntl.LOCK_EX):
+ check_reservation(site)
+ account = SitePaths.for_site(site).account
+ require_root_directory(account)
+ user = current_user(site.service_user)
+ if (
+ user is None
+ or user.pw_uid <= 0
+ or user.pw_gid <= 0
+ or user.pw_dir != str(account)
+ ):
+ raise ValueError("The hosting account has no matching SFTP login.")
+ destination = account / "backups"
+ try:
+ destination.mkdir(mode=0o700)
+ except FileExistsError:
+ pass
+ else:
+ os.chown(destination, 0, user.pw_gid, follow_symlinks=False)
+ destination.chmod(0o750)
+ info = destination.lstat()
+ if (
+ not stat.S_ISDIR(info.st_mode)
+ or info.st_uid != 0
+ or info.st_gid != user.pw_gid
+ or stat.S_IMODE(info.st_mode) != 0o750
+ or account.stat().st_dev != info.st_dev
+ ):
+ raise ValueError(
+ "The backup directory has unexpected ownership or permissions."
+ )
+ latest = destination / "latest.zip"
+ if os.path.lexists(latest):
+ info = latest.lstat()
+ if (
+ not stat.S_ISREG(info.st_mode)
+ or info.st_uid != user.pw_uid
+ or info.st_nlink != 1
+ ):
+ raise ValueError(
+ "The previous backup export has unexpected ownership "
+ "or type."
+ )
+ check_root_file(archive, mode=0o600)
+ with NamedTemporaryFile(dir=destination, delete=False) as staged:
+ temporary = Path(staged.name)
+ try:
+ with archive.open("rb") as source:
+ shutil.copyfileobj(source, staged, length=1024 * 1024)
+ staged.flush()
+ os.fchown(staged.fileno(), user.pw_uid, user.pw_gid)
+ os.fchmod(staged.fileno(), 0o400)
+ os.fsync(staged.fileno())
+ os.replace(temporary, latest)
+ finally:
+ temporary.unlink(missing_ok=True)
diff --git a/src/coulobre/hosting/account_administration.py b/src/coulobre/hosting/account_administration.py
index 91be61c..1c43830 100644
--- a/src/coulobre/hosting/account_administration.py
+++ b/src/coulobre/hosting/account_administration.py
@@ -12,6 +12,8 @@ from django.db import IntegrityError, transaction
from django.db.models import Count, Q
from django.shortcuts import redirect
from django.urls import reverse_lazy
+from django.utils.decorators import method_decorator
+from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, ListView
from coulobre.domain_names import canonical_domain
@@ -23,8 +25,18 @@ from .installation_features import (
default_dns_zones_allowed,
panel_feature_allowed,
)
-from .invitations import InviteLoginForm, queue_invitation
-from .models import Customer, HostingAccount, HostingPlan, Reseller
+from .invitations import (
+ InviteLoginForm,
+ queue_invitation,
+ render_welcome_message,
+)
+from .models import (
+ Customer,
+ DomainServicePolicy,
+ HostingAccount,
+ HostingPlan,
+ Reseller,
+)
from .reseller_accounts import (
create_reseller_account,
lock_resellers,
@@ -102,6 +114,9 @@ class ManagerOnboardingForm(InviteLoginForm):
return cleaned
+@method_decorator(
+ sensitive_post_parameters("initial_password"), name="dispatch"
+)
class ManagerOnboardingView(UserPassesTestMixin, FormView):
form_class = ManagerOnboardingForm
template_name = "hosting/workspace_form.html"
@@ -123,6 +138,22 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView):
def form_valid(self, form):
data = form.cleaned_data
+ if self.request.POST.get("action") == "preview":
+ defaults = zone_defaults()
+ preview = render_welcome_message(
+ username=data["username"],
+ welcome_message=data["welcome_message"],
+ setup_url="[Personal password setup link]",
+ account=HostingAccount(
+ primary_domain=data["primary_domain"],
+ hosting_plan=data["plan"],
+ ),
+ nameservers=defaults.nameservers if data["manage_dns"] else (),
+ mail_configured=data["manage_mail"],
+ )
+ return self.render_to_response(
+ self.get_context_data(form=form, welcome_preview=preview)
+ )
try:
with transaction.atomic():
user = form.save(commit=False)
@@ -139,6 +170,12 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView):
hosting_plan=data["plan"],
)
create_reseller_account(self.manager, account)
+ DomainServicePolicy.objects.create(
+ account=account,
+ domain=account.primary_domain,
+ dns_managed=data["manage_dns"],
+ mail_managed=data["manage_mail"],
+ )
defaults = zone_defaults()
setup_new_account(
account,
@@ -239,6 +276,9 @@ class OperatorLoginForm(UserCreationForm):
fields = ("username", "email")
+@method_decorator(
+ sensitive_post_parameters("password1", "password2"), name="dispatch"
+)
class OperatorCreateView(OperatorAuthorization, FormView):
form_class = OperatorLoginForm
template_name = "hosting/workspace_form.html"
@@ -274,7 +314,8 @@ class MoveHostingForm(forms.Form):
)
)
confirm = forms.BooleanField(
- label="I reviewed the destination and its hosting plan policy"
+ required=False,
+ label="I reviewed the destination and its hosting plan policy",
)
@@ -283,71 +324,96 @@ class MoveHostingView(OperatorAuthorization, FormView):
template_name = "hosting/workspace_form.html"
extra_context = {
"title": "Move hosting to another manager",
- "submit_label": "Move hosting account",
+ "submit_label": "Move hosting",
+ "move_preview_enabled": True,
}
def form_valid(self, form):
+ selected = form.cleaned_data["account"]
chosen = form.cleaned_data["manager"]
try:
with transaction.atomic():
- account = lock_hosting_account(
- form.cleaned_data["account"].pk, customer_id=None
- )
- require_open_account(account)
- if account.reseller_id == chosen.pk:
- raise ValidationError("Choose a different manager.")
- managers = lock_resellers(
- Reseller.objects.filter(
- pk__in=[chosen.pk, account.reseller_id]
- )
- ).select_related("user")
- destination = next(
- (
- manager
- for manager in managers
- if manager.pk == chosen.pk
- ),
- None,
- )
- if destination is None or not destination.user.is_active:
- raise ValidationError(
- "The destination is no longer available."
- )
- if (
- destination.hostingaccount_set.filter(
- retired_at__isnull=True
- ).count()
- >= destination.account_limit
- or not destination.hosting_plans.filter(
- pk=account.hosting_plan_id
- ).exists()
- ):
- raise ValidationError(
- "The destination must have room and allow this plan."
- )
- customer_id = account.customer_id
- if customer_id is not None:
- customer = Customer.objects.select_for_update().get(
- pk=customer_id
- )
- if (
- customer.hostingaccount_set.exclude(pk=account.pk)
- .filter(retired_at__isnull=True)
- .exists()
- ):
- raise ValidationError(
- "This customer has other active hosting accounts. "
- "Move them together when changing their manager."
- )
- customer.reseller = destination
- customer.save(update_fields=["reseller"])
- account.reseller = destination
- save_operator_account(
- account,
- self.request.user.get_username(),
- changed_fields=["reseller"],
- )
+ return self.review_or_move(form, selected, chosen)
except ValidationError as error:
form.add_error(None, ValidationError(error.messages))
return self.form_invalid(form)
+
+ def review_or_move(self, form, selected, chosen):
+ account = lock_hosting_account(selected.pk, customer_id=None)
+ require_open_account(account)
+ accounts = [account]
+ customer = None
+ if account.customer_id:
+ customer = Customer.objects.select_for_update().get(
+ pk=account.customer_id
+ )
+ account_ids = (
+ customer.hostingaccount_set.filter(retired_at__isnull=True)
+ .exclude(pk=account.pk)
+ .order_by("pk")
+ .values_list("pk", flat=True)
+ )
+ accounts.extend(
+ lock_hosting_account(pk, customer_id=customer.pk)
+ for pk in account_ids
+ )
+ if all(item.reseller_id == chosen.pk for item in accounts):
+ raise ValidationError("Choose a different manager.")
+ managers = lock_resellers(
+ Reseller.objects.filter(
+ pk__in={chosen.pk}
+ | {item.reseller_id for item in accounts if item.reseller_id}
+ )
+ ).select_related("user")
+ destination = next(
+ (manager for manager in managers if manager.pk == chosen.pk),
+ None,
+ )
+ if destination is None or not destination.user.is_active:
+ raise ValidationError("The destination is no longer available.")
+ moving = [item for item in accounts if item.reseller_id != chosen.pk]
+ allowed_plans = set(
+ destination.hosting_plans.values_list("pk", flat=True)
+ )
+ if destination.hostingaccount_set.count() + len(
+ moving
+ ) > destination.account_limit or any(
+ item.hosting_plan_id not in allowed_plans for item in moving
+ ):
+ raise ValidationError(
+ "The destination must have room and allow every hosting plan."
+ )
+ revision = [
+ destination.pk,
+ [
+ [item.pk, item.reseller_id, item.hosting_plan_id]
+ for item in accounts
+ ],
+ ]
+ if self.request.POST.get("action") != "move":
+ self.request.session["move_hosting_preview"] = revision
+ return self.render_to_response(
+ self.get_context_data(
+ form=form, moving=moving, destination=destination
+ )
+ )
+ if (
+ not form.cleaned_data["confirm"]
+ or self.request.session.pop("move_hosting_preview", None)
+ != revision
+ ):
+ raise ValidationError(
+ "Preview and confirm the transfer before moving hosting."
+ )
+ if customer:
+ customer.reseller = destination
+ customer.save(update_fields=["reseller"])
+ for item in moving:
+ item.reseller = destination
+ save_operator_account(
+ item,
+ self.request.user.get_username(),
+ changed_fields=["reseller"],
+ )
+ messages.success(self.request, "The hosting accounts were moved.")
return redirect(account)
diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py
index d6c4c70..8a0fbba 100644
--- a/src/coulobre/hosting/account_backups.py
+++ b/src/coulobre/hosting/account_backups.py
@@ -25,7 +25,13 @@ def mail_backups_enabled():
)
-def account_backup_manifest(account, *, include_mailboxes=False):
+def account_backup_manifest(
+ account,
+ *,
+ include_mailboxes=False,
+ include_website=True,
+ include_databases=True,
+):
mailboxes = None
if include_mailboxes:
requests = HostingMailbox.objects.filter(
@@ -34,32 +40,61 @@ def account_backup_manifest(account, *, include_mailboxes=False):
mailboxes = tuple(mailbox.spec for mailbox in requests)
return AccountBackup(
WebSite(account.pk, account.primary_domain),
- tuple(database.spec for database in account.databases.all()),
+ tuple(database.spec for database in account.databases.all())
+ if include_databases
+ else (),
mailboxes,
- tuple(site.spec for site in active_websites(account)),
+ tuple(site.spec for site in active_websites(account))
+ if include_website
+ else (),
+ include_website,
).manifest()
@transaction.atomic
def queue_account_backup(
- account_id, *, include_mailboxes=False, customer_id=None
+ account_id,
+ *,
+ include_mailboxes=False,
+ customer_id=None,
+ include_website=True,
+ include_databases=True,
):
account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
- _enqueue_backup(account, include_mailboxes=include_mailboxes)
+ if not any((include_mailboxes, include_website, include_databases)):
+ raise ValidationError("Select at least one backup component.")
+ _enqueue_backup(
+ account,
+ include_mailboxes=include_mailboxes,
+ include_website=include_website,
+ include_databases=include_databases,
+ export_customer_id=customer_id,
+ )
def _enqueue_backup(
- account, *, include_mailboxes, scheduled_for=None, offsite_destination=""
+ account,
+ *,
+ include_mailboxes,
+ scheduled_for=None,
+ offsite_destination="",
+ include_website=True,
+ include_databases=True,
+ export_customer_id=None,
):
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
job = account.backup_jobs.create(
manifest=account_backup_manifest(
- account, include_mailboxes=include_mailboxes
+ account,
+ include_mailboxes=include_mailboxes,
+ include_website=include_website,
+ include_databases=include_databases,
),
remote_mail=include_mailboxes
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for,
+ export_customer_id=export_customer_id,
)
if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create(
diff --git a/src/coulobre/hosting/backup_restores.py b/src/coulobre/hosting/backup_restores.py
index a213133..3755b24 100644
--- a/src/coulobre/hosting/backup_restores.py
+++ b/src/coulobre/hosting/backup_restores.py
@@ -76,11 +76,20 @@ def available_website_restore_targets(backup, current=None):
@transaction.atomic
def queue_website_restore(
- backup, *, restore_id, filename, replace, operator_username, site_key=None
+ backup,
+ *,
+ restore_id,
+ filename,
+ replace,
+ operator_username,
+ site_key=None,
+ customer_id=None,
):
- account = lock_hosting_account(backup.account_id, customer_id=None)
+ account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
backup.refresh_from_db()
+ if customer_id is not None and backup.export_customer_id != customer_id:
+ raise ValidationError("This backup is no longer available.")
backup.account = account
targets = available_website_restore_targets(backup)
site = targets.get(site_key or str(account.pk))
@@ -96,6 +105,7 @@ def queue_website_restore(
operator_username,
{
"filename": filename,
+ "requested_customer_id": customer_id,
"replace": replace,
"site_manifest": site.manifest()
if site.site_id is not None
@@ -110,11 +120,13 @@ def queue_website_restore(
@transaction.atomic
def queue_component_restore(
- backup, *, restore_id, kind, resource, operator_username
+ backup, *, restore_id, kind, resource, operator_username, customer_id=None
):
- account = lock_hosting_account(backup.account_id, customer_id=None)
+ account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
backup.refresh_from_db()
+ if customer_id is not None and backup.export_customer_id != customer_id:
+ raise ValidationError("This backup is no longer available.")
targets = available_restore_resources(
backup, kind, current_restore_resources(account, kind)
)
@@ -128,6 +140,7 @@ def queue_component_restore(
operator_username,
{
"kind": kind,
+ "requested_customer_id": customer_id,
"resource": resource,
"remote_mail": kind == RestoreKind.MAILBOX
and settings.REMOTE_MAILBOX_RESTORE,
diff --git a/src/coulobre/hosting/customer_backup_views.py b/src/coulobre/hosting/customer_backup_views.py
index 239717d..e0b4124 100644
--- a/src/coulobre/hosting/customer_backup_views.py
+++ b/src/coulobre/hosting/customer_backup_views.py
@@ -1,4 +1,5 @@
from django import forms
+from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import ValidationError
@@ -8,12 +9,28 @@ from django.utils.functional import cached_property
from django.views.generic import FormView
from .access import customer_for_user
+from .account_backup_forms import ComponentRestoreForm, WebsiteRestoreForm
from .account_backups import mail_backups_enabled, queue_account_backup
+from .backup_restores import (
+ available_restore_resources,
+ available_website_restore_targets,
+ current_restore_resources,
+ enabled_component_restores,
+ queue_component_restore,
+ queue_website_restore,
+)
from .installation_features import panel_feature_allowed
-from .models import HostingAccount
+from .models import ComponentRestoreJob, HostingAccount, WebsiteRestoreJob
+from .sftp import site_is_active
class CustomerBackupForm(forms.Form):
+ include_website = forms.BooleanField(
+ required=False, initial=True, label="Include websites"
+ )
+ include_databases = forms.BooleanField(
+ required=False, initial=True, label="Include databases"
+ )
include_mailboxes = forms.BooleanField(
required=False, label="Include mailboxes"
)
@@ -40,16 +57,71 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
form.fields["include_mailboxes"].disabled = not mail_backups_enabled()
return form
+ def can_export(self):
+ return (
+ panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
+ and settings.LOCAL_WEB_SFTP
+ and site_is_active(self.account)
+ )
+
def get_context_data(self, **kwargs):
+ backups = (
+ self.account.backup_jobs.filter(
+ export_customer_id=self.account.customer_id
+ )
+ .select_related("expiration")
+ .order_by("-requested_at")[:30]
+ )
+ kinds = enabled_component_restores()
+ current = {
+ kind: current_restore_resources(self.account, kind)
+ for kind in kinds
+ }
return super().get_context_data(
account=self.account,
- backups=self.account.backup_jobs.order_by("-requested_at")[:30],
- may_create=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"),
+ backups=[
+ (
+ backup,
+ [
+ *(
+ ["website"]
+ if settings.LOCAL_WEBSITE_RESTORE
+ and available_website_restore_targets(backup)
+ else []
+ ),
+ *(
+ kind
+ for kind, resources in current.items()
+ if available_restore_resources(
+ backup, kind, resources
+ )
+ ),
+ ],
+ )
+ for backup in backups
+ ],
+ may_create=self.can_export(),
+ restores=[
+ *self.website_restores(),
+ *self.component_restores(),
+ ],
**kwargs,
)
+ def website_restores(self):
+ return WebsiteRestoreJob.objects.filter(
+ backup__account=self.account,
+ requested_customer_id=self.account.customer_id,
+ ).order_by("-requested_at")[:15]
+
+ def component_restores(self):
+ return ComponentRestoreJob.objects.filter(
+ backup__account=self.account,
+ requested_customer_id=self.account.customer_id,
+ ).order_by("-requested_at")[:15]
+
def form_valid(self, form):
- if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
+ if not self.can_export():
raise Http404
customer = customer_for_user(self.request.user)
try:
@@ -57,6 +129,8 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
self.account.pk,
include_mailboxes=form.cleaned_data["include_mailboxes"],
customer_id=customer.pk,
+ include_website=form.cleaned_data["include_website"],
+ include_databases=form.cleaned_data["include_databases"],
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
@@ -65,3 +139,99 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
return self.form_invalid(form)
messages.success(self.request, "Backup requested.")
return redirect("panel:customer_backups", pk=self.account.pk)
+
+
+class CustomerRestoreView(CustomerBackupView):
+ template_name = "hosting/customer_restore.html"
+
+ @cached_property
+ def kind(self):
+ kind = self.kwargs["kind"]
+ if (
+ not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
+ or (kind == "website" and not settings.LOCAL_WEBSITE_RESTORE)
+ or (kind != "website" and kind not in enabled_component_restores())
+ ):
+ raise Http404
+ return kind
+
+ @cached_property
+ def backup(self):
+ backup = get_object_or_404(
+ self.account.backup_jobs.select_related("account", "expiration"),
+ pk=self.kwargs["backup_pk"],
+ export_customer_id=self.account.customer_id,
+ )
+ if not backup.archive_is_restorable:
+ raise Http404
+ return backup
+
+ @cached_property
+ def targets(self):
+ if self.kind == "website":
+ targets = available_website_restore_targets(self.backup)
+ else:
+ targets = available_restore_resources(
+ self.backup,
+ self.kind,
+ current_restore_resources(self.account, self.kind),
+ )
+ if not targets:
+ raise Http404
+ return targets
+
+ def get_form(self, form_class=None):
+ form_class = (
+ WebsiteRestoreForm
+ if self.kind == "website"
+ else ComponentRestoreForm
+ )
+ return form_class(targets=self.targets, **self.get_form_kwargs())
+
+ def get_context_data(self, **kwargs):
+ return FormView.get_context_data(
+ self,
+ account=self.account,
+ backup=self.backup,
+ kind=self.kind,
+ **kwargs,
+ )
+
+ def form_valid(self, form):
+ data = form.cleaned_data.copy()
+ revision = {
+ "backup": self.backup.pk,
+ "kind": self.kind,
+ "fields": data | {"restore_id": str(data["restore_id"])},
+ }
+ if self.request.POST.get("action") != "restore":
+ self.request.session["customer_restore_preview"] = revision
+ target = self.targets[data.get("site_key") or data["resource"]]
+ return self.render_to_response(
+ self.get_context_data(form=form, target=target, preview=data)
+ )
+ if (
+ self.request.session.pop("customer_restore_preview", None)
+ != revision
+ ):
+ form.add_error(None, "Review the destination before restoring.")
+ return self.form_invalid(form)
+ try:
+ common = {
+ "operator_username": self.request.user.get_username(),
+ "customer_id": self.account.customer_id,
+ }
+ if self.kind == "website":
+ data.pop("scope")
+ queue_website_restore(self.backup, **common, **data)
+ else:
+ queue_component_restore(
+ self.backup, kind=self.kind, **common, **data
+ )
+ except HostingAccount.DoesNotExist as error:
+ raise Http404 from error
+ except ValidationError as error:
+ form.add_error(None, error)
+ return self.form_invalid(form)
+ messages.success(self.request, "Restore requested.")
+ return redirect("panel:customer_backups", pk=self.account.pk)
diff --git a/src/coulobre/hosting/dns_publication.py b/src/coulobre/hosting/dns_publication.py
index 9835c40..0d4c9f0 100644
--- a/src/coulobre/hosting/dns_publication.py
+++ b/src/coulobre/hosting/dns_publication.py
@@ -6,6 +6,7 @@ from django.db.models import Q
from coulobre.dns_node import DNS_REQUEST_LIMIT
from .access import is_tenant, manages_account
+from .domain_policies import require_managed
from .models import DnsPublication, HostingDnsZone
from .node_client import encode_manifest
from .resource_requests import lock_hosting_account, require_open_account
@@ -33,6 +34,7 @@ def publish_for_account(account_id, zone_id, expected_serial, *, actor=None):
):
raise PermissionDenied
require_open_account(account)
+ require_managed(account, zone.domain, "dns_managed")
if str(zone.serial) != expected_serial:
raise ValueError(
"This zone changed before publication. "
diff --git a/src/coulobre/hosting/domain_policies.py b/src/coulobre/hosting/domain_policies.py
new file mode 100644
index 0000000..5a936cb
--- /dev/null
+++ b/src/coulobre/hosting/domain_policies.py
@@ -0,0 +1,15 @@
+from django.core.exceptions import ValidationError
+
+from .models import DomainServicePolicy
+
+
+def policy_for(account, domain):
+ policy = DomainServicePolicy.objects.filter(
+ account=account, domain=domain
+ ).first()
+ return policy or DomainServicePolicy(account=account, domain=domain)
+
+
+def require_managed(account, domain, field):
+ if not getattr(policy_for(account, domain), field):
+ raise ValidationError("This domain uses an external service provider.")
diff --git a/src/coulobre/hosting/domain_services.py b/src/coulobre/hosting/domain_services.py
new file mode 100644
index 0000000..f5b32b9
--- /dev/null
+++ b/src/coulobre/hosting/domain_services.py
@@ -0,0 +1,176 @@
+from django import forms
+from django.contrib import messages
+from django.core.exceptions import PermissionDenied, ValidationError
+from django.db import transaction
+from django.http import Http404
+from django.shortcuts import get_object_or_404, redirect, render
+from django.urls import reverse
+from django.views.decorators.cache import never_cache
+from django.views.decorators.http import require_http_methods
+
+from coulobre.domain_names import canonical_domain
+
+from .access import customer_for_user
+from .dns_forms import zone_record_rows
+from .domain_policies import policy_for
+from .independent_websites import account_websites
+from .installation_features import panel_feature_allowed
+from .models import DomainServicePolicy, HostingAccount
+from .resource_requests import lock_hosting_account, require_open_account
+from .sftp import site_is_active
+
+DNS_PUBLISHING = "LOCAL_DNS_PUBLISHING"
+MAIL_PROVISIONING = "LOCAL_MAILBOX_PROVISIONING"
+
+
+class DomainServicesForm(forms.Form):
+ dns_managed = forms.BooleanField(
+ required=False, label="Manage DNS in Coulobre"
+ )
+ mail_managed = forms.BooleanField(
+ required=False, label="Manage email in Coulobre"
+ )
+
+ def clean(self):
+ cleaned = super().clean()
+ for field, feature in (
+ ("dns_managed", DNS_PUBLISHING),
+ ("mail_managed", MAIL_PROVISIONING),
+ ):
+ if (
+ cleaned.get(field)
+ and field in self.changed_data
+ and not panel_feature_allowed(feature)
+ ):
+ self.add_error(
+ field, "This managed service needs setup on the server."
+ )
+ return cleaned
+
+
+def allowed_domains(account):
+ domains = {account.primary_domain}
+ domains.update(
+ account_websites(account)
+ .filter(retired_at__isnull=True)
+ .values_list("reservation__domain", flat=True)
+ )
+ domains.update(
+ account.website_domains.filter(alias__isnull=False).values_list(
+ "domain", flat=True
+ )
+ )
+ return sorted(domains)
+
+
+@transaction.atomic
+def save_domain_policy(account_id, domain, customer_id, choices):
+ account = lock_hosting_account(account_id, customer_id=customer_id)
+ require_open_account(account)
+ if domain not in allowed_domains(account):
+ raise Http404
+ DomainServicePolicy.objects.update_or_create(
+ account=account, domain=domain, defaults=choices
+ )
+
+
+@never_cache
+@require_http_methods(("GET", "HEAD", "POST"))
+def domain_workspace(request, pk, page):
+ if page not in {"domains", "dns", "php", "files", "forwarders", "replies"}:
+ raise Http404
+ customer = customer_for_user(request.user)
+ if customer is None:
+ raise PermissionDenied
+ account = get_object_or_404(
+ HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
+ )
+ domains = allowed_domains(account)
+ try:
+ domain = canonical_domain(
+ request.GET.get("domain", account.primary_domain)
+ )
+ except ValueError as error:
+ raise Http404 from error
+ if domain not in domains:
+ raise Http404
+ policy = policy_for(account, domain)
+ initial = {
+ field: getattr(policy, field)
+ for field in ("dns_managed", "mail_managed")
+ }
+ form = DomainServicesForm(
+ request.POST if request.method == "POST" else None, initial=initial
+ )
+ destination = reverse(
+ "panel:domain_workspace",
+ args=[account.pk, page],
+ query={"domain": domain},
+ )
+ if request.method == "POST":
+ if page != "domains":
+ raise PermissionDenied
+ if form.is_valid():
+ try:
+ save_domain_policy(
+ account.pk, domain, customer.pk, form.cleaned_data
+ )
+ except HostingAccount.DoesNotExist as error:
+ raise Http404 from error
+ except ValidationError as error:
+ form.add_error(None, error)
+ else:
+ messages.success(request, "Domain service preferences saved.")
+ return redirect(destination)
+
+ website = (
+ account_websites(account)
+ .filter(
+ reservation__domain=domain,
+ activated=True,
+ retired_at__isnull=True,
+ suspended=False,
+ )
+ .first()
+ )
+ primary = domain == account.primary_domain and site_is_active(account)
+ zone = (
+ account.dns_zones.filter(domain=domain).first()
+ if page == "dns"
+ else None
+ )
+ mail_domain = (
+ account.mail_domains.filter(domain=domain).first()
+ if page in {"forwarders", "replies"}
+ else None
+ )
+ titles = {
+ "domains": "Domains",
+ "dns": "DNS Editor",
+ "php": "PHP Settings",
+ "files": "File Manager",
+ "forwarders": "Forwarders",
+ "replies": "Automatic replies",
+ }
+ return render(
+ request,
+ "hosting/domain_workspace.html",
+ {
+ "title": titles[page],
+ "page": page,
+ "account": account,
+ "domains": domains,
+ "domain": domain,
+ "form": form,
+ "policy": policy,
+ "zone": zone,
+ "records": zone_record_rows(zone.spec) if zone else (),
+ "mail_domain": mail_domain,
+ "website": website,
+ "primary": primary,
+ "can_add_site": panel_feature_allowed("LOCAL_WEB_ACTIVATION"),
+ "may_edit_dns": bool(
+ zone and zone.delegate_dns and policy.dns_managed
+ ),
+ },
+ )
diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py
index 254b8ce..744e6a9 100644
--- a/src/coulobre/hosting/installation_views.py
+++ b/src/coulobre/hosting/installation_views.py
@@ -1,12 +1,14 @@
from importlib.metadata import PackageNotFoundError, version
from django import forms
+from django.conf import settings
from django.contrib import messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db import transaction
from django.db.models import F
-from django.urls import reverse_lazy
+from django.http import Http404
+from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView
@@ -47,14 +49,45 @@ class InstallationView(LoginRequiredMixin, TemplateView):
)
+OPERATOR_FEATURE_SECTIONS = {
+ "general": ("General", ()),
+ "server": (
+ "Server",
+ (
+ "LOCAL_WEB_ACTIVATION",
+ "WEB_FILE_MANAGER",
+ "WEBSITE_JOBS",
+ "LOCAL_DNS_PUBLISHING",
+ "DEFAULT_DNS_ZONES",
+ ),
+ ),
+ "security": ("Security", ("LOCAL_WEB_HTTPS",)),
+ "email": (
+ "Email",
+ ("LOCAL_MAILBOX_PROVISIONING", "MANAGE_MAIL_DNS", "ROUNDCUBE_URL"),
+ ),
+ "database": (
+ "Database",
+ ("LOCAL_DATABASE_PROVISIONING", "PHPMYADMIN_URL"),
+ ),
+ "backups": (
+ "Backups",
+ ("LOCAL_ACCOUNT_BACKUPS", "OFFSITE_BACKUP_DESTINATIONS"),
+ ),
+}
+
+
class FeatureConfigurationForm(forms.Form):
revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
- def __init__(self, *args, policy, **kwargs):
+ def __init__(self, *args, policy, section=None, **kwargs):
super().__init__(*args, **kwargs)
self.initial["revision"] = policy.saved.revision
self.configured_features = [
- feature for feature in FEATURES if feature.configured
+ feature
+ for feature in FEATURES
+ if (section is None or feature.setting in section)
+ and feature.configured
]
for feature in self.configured_features:
self.fields[feature.setting] = forms.BooleanField(
@@ -98,7 +131,11 @@ def check_features(form, changed):
)
if (
feature.setting == "DEFAULT_DNS_ZONES"
- and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING")
+ and not form.cleaned_data.get(
+ "LOCAL_DNS_PUBLISHING",
+ settings.LOCAL_DNS_PUBLISHING
+ and "LOCAL_DNS_PUBLISHING" not in FeaturePolicy().disabled,
+ )
):
form.add_error(feature.setting, "Enable DNS publishing first.")
@@ -115,7 +152,35 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView):
)
def get_form_kwargs(self):
- return {**super().get_form_kwargs(), "policy": FeaturePolicy()}
+ section = self.kwargs.get("section")
+ if section is not None and section not in OPERATOR_FEATURE_SECTIONS:
+ raise Http404
+ return super().get_form_kwargs() | {
+ "policy": FeaturePolicy(),
+ "section": (
+ OPERATOR_FEATURE_SECTIONS[section][1]
+ if section is not None
+ else None
+ ),
+ }
+
+ def get_context_data(self, **kwargs):
+ section = self.kwargs.get("section")
+ return super().get_context_data(
+ selected_section=section,
+ settings_tabs=tuple(
+ (key, label)
+ for key, (label, _) in OPERATOR_FEATURE_SECTIONS.items()
+ )
+ if section
+ else (),
+ **kwargs,
+ )
+
+ def get_success_url(self):
+ if "section" in self.kwargs:
+ return reverse("panel:operator_settings", kwargs=self.kwargs)
+ return super().get_success_url()
def form_valid(self, form):
revision = form.cleaned_data["revision"]
diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py
index ca35aa1..5d35ba0 100644
--- a/src/coulobre/hosting/invitations.py
+++ b/src/coulobre/hosting/invitations.py
@@ -179,29 +179,18 @@ def deliver_invitation(invitation_id, revision):
if account
else None
)
- message = render_to_string(
- "hosting/panel_invitation.txt",
- {
- "username": user.get_username(),
- "welcome_message": invitation.welcome_message,
- "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()
- ),
- },
+ message = render_welcome_message(
+ username=user.get_username(),
+ welcome_message=invitation.welcome_message,
+ setup_url=origin + path,
+ account=account,
+ nameservers=zone.nameservers if zone else (),
+ mail_configured=bool(
+ account
+ and account.mail_domains.filter(
+ domain=account.primary_domain
+ ).exists()
+ ),
)
try:
sent = send_mail(
@@ -215,6 +204,36 @@ def deliver_invitation(invitation_id, revision):
pending.update(delivery=PanelInvitation.Delivery.SENT)
+def render_welcome_message(
+ *,
+ username,
+ welcome_message,
+ setup_url,
+ account,
+ nameservers,
+ mail_configured,
+):
+ return render_to_string(
+ "hosting/panel_invitation.txt",
+ {
+ "username": username,
+ "welcome_message": welcome_message,
+ "setup_url": setup_url,
+ "panel_url": settings.PASSWORD_RESET_ORIGIN.rstrip("/") + "/",
+ "account": account,
+ "nameservers": nameservers,
+ "website_records": (
+ website_records(account.primary_domain, wildcard=False)
+ if account and not nameservers
+ else ()
+ ),
+ "imap_host": settings.MAIL_IMAP_HOST,
+ "submission_host": settings.MAIL_SUBMISSION_HOST,
+ "mail_configured": mail_configured,
+ },
+ )
+
+
class AcceptInvitation(PasswordResetConfirmView):
template_name = "hosting/accept_invitation.html"
token_generator = invitation_token
diff --git a/src/coulobre/hosting/mail_queue_views.py b/src/coulobre/hosting/mail_queue_views.py
index c857c67..ee85f91 100644
--- a/src/coulobre/hosting/mail_queue_views.py
+++ b/src/coulobre/hosting/mail_queue_views.py
@@ -1,18 +1,23 @@
from datetime import timedelta
+from django import forms
from django.contrib.auth.mixins import PermissionRequiredMixin
+from django.core.exceptions import PermissionDenied
from django.db import transaction
-from django.http import Http404
+from django.http import Http404, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
-from django.views.generic import TemplateView
+from django.views.decorators.http import require_POST
+from django.views.generic import ListView, TemplateView
+
+from coulobre.mail_queue import QUEUE_ACTIONS, MailQueueAction
from .access import OperatorOnlyMixin
from .installation_features import panel_feature_allowed
-from .models import HostingMailDomain
-from .tasks import refresh_mail_queue
+from .models import HostingMailDomain, MailQueueOperation
+from .tasks import refresh_mail_queue, run_mail_queue_operation
@method_decorator(never_cache, name="dispatch")
@@ -35,7 +40,11 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
def get_context_data(self, **kwargs):
return super().get_context_data(
- mail_domain=self.get_domain(), **kwargs
+ mail_domain=(domain := self.get_domain()),
+ operations=MailQueueOperation.objects.filter(
+ domain=domain
+ ).order_by("-pk")[:10],
+ **kwargs,
)
def post(self, request, *args, **kwargs):
@@ -54,3 +63,64 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
)
)
return redirect("panel:mail_queue", pk=domain.pk)
+
+
+class MailQueueActionForm(forms.Form):
+ queue_id = forms.CharField(max_length=32)
+ arrival = forms.IntegerField(min_value=1, max_value=2**53 - 1)
+ action = forms.ChoiceField(
+ choices=[(key, key.capitalize()) for key in QUEUE_ACTIONS]
+ )
+
+
+@require_POST
+def mail_queue_action(request, pk):
+ if not request.user.is_superuser or not request.user.is_verified():
+ raise PermissionDenied
+ if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
+ raise Http404
+ form = MailQueueActionForm(request.POST)
+ if not form.is_valid():
+ return HttpResponseBadRequest("Choose a queue entry and action.")
+ data = form.cleaned_data
+ try:
+ with transaction.atomic():
+ domain = get_object_or_404(
+ HostingMailDomain.objects.select_for_update(),
+ pk=pk,
+ account__retired_at__isnull=True,
+ )
+ if not any(
+ entry.get("queue_id") == data["queue_id"]
+ and entry.get("arrival") == data["arrival"]
+ for entry in domain.queue_report.get("entries", [])
+ ):
+ return HttpResponseBadRequest(
+ "Refresh the queue before requesting an action."
+ )
+ spec = MailQueueAction(domain.domain, **data)
+ if not MailQueueOperation.objects.filter(
+ domain=domain, queue_id=spec.queue_id, finished_at__isnull=True
+ ).exists():
+ job = MailQueueOperation.objects.create(
+ domain=domain, actor=request.user, **data
+ )
+ transaction.on_commit(
+ lambda: run_mail_queue_operation.delay(job.pk)
+ )
+ except ValueError:
+ return HttpResponseBadRequest("Choose a queue entry and action.")
+ return redirect("panel:mail_queue", pk=pk)
+
+
+class MailQueueIndex(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
+ permission_required = MailQueueView.permission_required
+ model = HostingMailDomain
+ context_object_name = "domains"
+ template_name = "hosting/mail_queue_index.html"
+ paginate_by = 40
+
+ def get_queryset(self):
+ return HostingMailDomain.objects.filter(
+ account__retired_at__isnull=True
+ ).order_by("domain")
diff --git a/src/coulobre/hosting/migrations/0061_domain_service_policy.py b/src/coulobre/hosting/migrations/0061_domain_service_policy.py
new file mode 100644
index 0000000..3cc8576
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0061_domain_service_policy.py
@@ -0,0 +1,50 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:11
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import coulobre.hosting.fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0060_welcome_message"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="DomainServicePolicy",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "domain",
+ coulobre.hosting.fields.DomainNameField(max_length=253),
+ ),
+ ("dns_managed", models.BooleanField(default=True)),
+ ("mail_managed", models.BooleanField(default=True)),
+ (
+ "account",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="hosting.hostingaccount",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("account", "domain"),
+ name="hosting_unique_domain_service_policy",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/migrations/0062_panel_themes_and_announcements.py b/src/coulobre/hosting/migrations/0062_panel_themes_and_announcements.py
new file mode 100644
index 0000000..bbf1f33
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0062_panel_themes_and_announcements.py
@@ -0,0 +1,96 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:14
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0061_domain_service_policy"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PanelTheme",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=80, unique=True)),
+ ("colors", models.JSONField()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="PanelAnnouncement",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "audience",
+ models.CharField(
+ choices=[
+ ("all", "All users"),
+ ("managers", "Managers"),
+ ],
+ max_length=8,
+ ),
+ ),
+ ("subject", models.CharField(max_length=140)),
+ ("body", models.TextField(max_length=4000)),
+ ("published_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "author",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="UserTheme",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "theme",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="hosting.paneltheme",
+ ),
+ ),
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/src/coulobre/hosting/migrations/0063_operator_operations.py b/src/coulobre/hosting/migrations/0063_operator_operations.py
new file mode 100644
index 0000000..4b53fc9
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0063_operator_operations.py
@@ -0,0 +1,65 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:16
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0062_panel_themes_and_announcements"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OperatorOperation",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "requested_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ (
+ "last_dispatched_at",
+ models.DateTimeField(blank=True, null=True),
+ ),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("problem", models.TextField(blank=True)),
+ ("action", models.CharField(max_length=24)),
+ ("target", models.CharField(blank=True, max_length=20)),
+ ("plan", models.CharField(blank=True, max_length=64)),
+ ("result", models.JSONField(default=dict)),
+ (
+ "actor",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "source",
+ models.OneToOneField(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="hosting.operatoroperation",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/migrations/0064_customer_backup_exports.py b/src/coulobre/hosting/migrations/0064_customer_backup_exports.py
new file mode 100644
index 0000000..f1d3e05
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0064_customer_backup_exports.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0063_operator_operations"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="accountbackupjob",
+ name="export_customer_id",
+ field=models.PositiveBigIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/src/coulobre/hosting/migrations/0065_mail_queue_operations.py b/src/coulobre/hosting/migrations/0065_mail_queue_operations.py
new file mode 100644
index 0000000..daee4ba
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0065_mail_queue_operations.py
@@ -0,0 +1,62 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:20
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0064_customer_backup_exports"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="MailQueueOperation",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "requested_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ (
+ "last_dispatched_at",
+ models.DateTimeField(blank=True, null=True),
+ ),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("problem", models.TextField(blank=True)),
+ ("queue_id", models.CharField(max_length=32)),
+ ("arrival", models.PositiveBigIntegerField()),
+ ("action", models.CharField(max_length=8)),
+ (
+ "actor",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "domain",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="hosting.hostingmaildomain",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ ]
diff --git a/src/coulobre/hosting/migrations/0066_customer_restore_scope.py b/src/coulobre/hosting/migrations/0066_customer_restore_scope.py
new file mode 100644
index 0000000..4981b69
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0066_customer_restore_scope.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.19 on 2026-11-23 21:28
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0065_mail_queue_operations"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="componentrestorejob",
+ name="requested_customer_id",
+ field=models.PositiveBigIntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="websiterestorejob",
+ name="requested_customer_id",
+ field=models.PositiveBigIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index 4f8e008..93d9321 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -672,6 +672,21 @@ class HostingDnsZone(models.Model):
)
+class DomainServicePolicy(models.Model):
+ account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
+ domain = DomainNameField(max_length=253)
+ dns_managed = models.BooleanField(default=True)
+ mail_managed = models.BooleanField(default=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=("account", "domain"),
+ name="hosting_unique_domain_service_policy",
+ )
+ ]
+
+
class WebsiteUsage(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="website_usage"
@@ -813,6 +828,29 @@ class ProvisioningJob(models.Model):
return "running" if self.started_at else "queued"
+class OperatorOperation(ProvisioningJob):
+ actor = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
+ )
+ action = models.CharField(max_length=24)
+ target = models.CharField(max_length=20, blank=True)
+ plan = models.CharField(max_length=64, blank=True)
+ source = models.OneToOneField(
+ "self", on_delete=models.SET_NULL, null=True, blank=True
+ )
+ result = models.JSONField(default=dict)
+
+
+class MailQueueOperation(ProvisioningJob):
+ domain = models.ForeignKey(HostingMailDomain, on_delete=models.CASCADE)
+ actor = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
+ )
+ queue_id = models.CharField(max_length=32)
+ arrival = models.PositiveBigIntegerField()
+ action = models.CharField(max_length=8)
+
+
class AccountRetirement(models.Model):
class Policy(models.TextChoices):
HOLD = "hold", "Keep names reserved"
@@ -1098,6 +1136,7 @@ class AccountBackupJob(ProvisioningJob):
)
manifest = models.JSONField()
remote_mail = models.BooleanField(default=False)
+ export_customer_id = models.PositiveBigIntegerField(null=True, blank=True)
scheduled_for = models.DateTimeField(null=True, blank=True)
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
retention_protected = models.BooleanField(default=False)
@@ -1193,6 +1232,9 @@ class WebsiteRestoreJob(ProvisioningJob):
filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True)
replace = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
+ requested_customer_id = models.PositiveBigIntegerField(
+ null=True, blank=True
+ )
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@@ -1213,6 +1255,9 @@ class ComponentRestoreJob(ProvisioningJob):
resource = models.CharField(max_length=254)
remote_mail = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
+ requested_customer_id = models.PositiveBigIntegerField(
+ null=True, blank=True
+ )
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@@ -1364,6 +1409,37 @@ class PanelRecoveryCode(models.Model):
]
+class PanelTheme(models.Model):
+ name = models.CharField(max_length=80, unique=True)
+ colors = models.JSONField()
+
+ def __str__(self):
+ return self.name
+
+
+class UserTheme(models.Model):
+ user = models.OneToOneField(
+ settings.AUTH_USER_MODEL, on_delete=models.CASCADE
+ )
+ theme = models.ForeignKey(
+ PanelTheme, on_delete=models.SET_NULL, null=True, blank=True
+ )
+
+
+class PanelAnnouncement(models.Model):
+ class Audience(models.TextChoices):
+ ALL = "all", "All users"
+ MANAGERS = "managers", "Managers"
+
+ author = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
+ )
+ audience = models.CharField(max_length=8, choices=Audience.choices)
+ subject = models.CharField(max_length=140)
+ body = models.TextField(max_length=4000)
+ published_at = models.DateTimeField(auto_now_add=True)
+
+
class PanelAccountSecurity(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
diff --git a/src/coulobre/hosting/operator_tools.py b/src/coulobre/hosting/operator_tools.py
new file mode 100644
index 0000000..9d2adf1
--- /dev/null
+++ b/src/coulobre/hosting/operator_tools.py
@@ -0,0 +1,166 @@
+from datetime import timedelta
+from pathlib import Path
+
+from django import forms
+from django.contrib import messages
+from django.db import transaction
+from django.shortcuts import redirect
+from django.utils import timezone
+from django.views.generic import FormView, TemplateView
+
+from coulobre.operator_node import SERVICES, SOCKET, OperatorRequest
+
+from .account_administration import OperatorAuthorization
+from .models import OperatorOperation
+from .tasks import run_operator_operation
+from .update_views import inspect_linked_nodes
+
+TOOL_ACTIONS = {
+ "packages": (
+ "Server package updates",
+ ("package-preview", "package-upgrade"),
+ ),
+ "services": ("System services", ("reload", "restart")),
+ "database": ("Database monitor", ("database-report",)),
+}
+ACTION_LABELS = {
+ "package-preview": "Review available updates",
+ "package-upgrade": "Apply reviewed updates",
+ "reload": "Reload",
+ "restart": "Restart",
+ "database-report": "Collect MariaDB status",
+}
+
+
+class OperatorToolForm(forms.Form):
+ action = forms.ChoiceField()
+ preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput)
+ target = forms.ChoiceField(
+ required=False,
+ choices=[
+ ("", "Select a service"),
+ *[(key, label) for key, label in SERVICES.items()],
+ ],
+ )
+ confirm = forms.BooleanField(
+ required=False, label="I reviewed the change and want to apply it"
+ )
+
+ def __init__(self, *args, actions, preview, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.preview = preview
+ self.initial["preview_id"] = preview.pk if preview else None
+ self.fields["action"].choices = [
+ (action, ACTION_LABELS[action]) for action in actions
+ ]
+ if "reload" not in actions:
+ self.fields.pop("target")
+ if actions == ("database-report",):
+ self.fields.pop("confirm")
+
+ def clean(self):
+ data = super().clean()
+ if self.errors:
+ return data
+ action = data["action"]
+ if action in {"reload", "restart", "package-upgrade"} and not data.get(
+ "confirm"
+ ):
+ self.add_error(
+ "confirm", "Confirm this change before applying it."
+ )
+ plan = ""
+ if action == "package-upgrade":
+ if (
+ self.preview is None
+ or data.get("preview_id") != self.preview.pk
+ ):
+ raise forms.ValidationError(
+ "Collect and review a current package update preview."
+ )
+ plan = self.preview.result.get("fingerprint", "")
+ try:
+ self.spec = OperatorRequest(action, data.get("target", ""), plan)
+ except ValueError as error:
+ raise forms.ValidationError(str(error)) from error
+ return data
+
+
+class OperatorToolsView(OperatorAuthorization, FormView):
+ form_class = OperatorToolForm
+ template_name = "hosting/operator_tools.html"
+ page = "services"
+
+ def preview(self):
+ return (
+ OperatorOperation.objects.filter(
+ action="package-preview",
+ actor=self.request.user,
+ problem="",
+ finished_at__gte=timezone.now() - timedelta(minutes=15),
+ )
+ .order_by("-pk")
+ .first()
+ )
+
+ def get_form_kwargs(self):
+ return super().get_form_kwargs() | {
+ "actions": TOOL_ACTIONS[self.page][1],
+ "preview": self.preview() if self.page == "packages" else None,
+ }
+
+ def get_context_data(self, **kwargs):
+ title, actions = TOOL_ACTIONS[self.page]
+ return super().get_context_data(
+ title=title,
+ page=self.page,
+ available=Path(SOCKET).is_socket(),
+ jobs=OperatorOperation.objects.filter(action__in=actions).order_by(
+ "-pk"
+ )[:20],
+ **kwargs,
+ )
+
+ @transaction.atomic
+ def form_valid(self, form):
+ if not Path(SOCKET).is_socket():
+ form.add_error(
+ None,
+ "Enable the local operator service before requesting "
+ "an operation.",
+ )
+ return self.form_invalid(form)
+ spec = form.spec
+ if form.preview is not None and spec.action == "package-upgrade":
+ OperatorOperation.objects.select_for_update().get(
+ pk=form.preview.pk
+ )
+ recent = OperatorOperation.objects.filter(
+ source=form.preview
+ ).exists()
+ if recent:
+ form.add_error(
+ None,
+ "Collect a new preview before starting another "
+ "package update.",
+ )
+ return self.form_invalid(form)
+ job = OperatorOperation.objects.create(
+ actor=self.request.user,
+ action=spec.action,
+ target=spec.target,
+ plan=spec.plan,
+ source=form.preview if spec.action == "package-upgrade" else None,
+ )
+ transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
+ messages.success(self.request, "Host operation queued.")
+ return redirect(self.request.path)
+
+
+class ConnectedNodesView(OperatorAuthorization, TemplateView):
+ template_name = "hosting/connected_nodes.html"
+
+ def get_context_data(self, **kwargs):
+ return super().get_context_data(
+ topology=inspect_linked_nodes(), **kwargs
+ )
diff --git a/src/coulobre/hosting/panel_content.py b/src/coulobre/hosting/panel_content.py
new file mode 100644
index 0000000..4d811ec
--- /dev/null
+++ b/src/coulobre/hosting/panel_content.py
@@ -0,0 +1,289 @@
+import re
+
+from django import forms
+from django.contrib import messages
+from django.contrib.auth.mixins import LoginRequiredMixin
+from django.core.exceptions import PermissionDenied, ValidationError
+from django.http import HttpResponse
+from django.shortcuts import redirect
+from django.urls import reverse_lazy
+from django.views.decorators.cache import never_cache
+from django.views.decorators.http import require_safe
+from django.views.generic import FormView, TemplateView
+
+from .access import reseller_for_user
+from .account_administration import OperatorAuthorization
+from .models import PanelAnnouncement, PanelTheme, UserTheme
+
+COLOR_TOKENS = frozenset(
+ [
+ "page",
+ "surface",
+ "ink",
+ "muted",
+ "line",
+ "sidebar",
+ "sidebar-text",
+ "accent",
+ "accent-hover",
+ "focus",
+ "sidebar-gradient",
+ "control-line",
+ "control-hover",
+ "table-heading",
+ "table-heading-text",
+ "notice-bg",
+ "notice-line",
+ "button-text",
+ "code-bg",
+ "code-text",
+ ]
+)
+THEME_BLOCK = re.compile(
+ r'\s*(:root(?:\[data-appearance="dark"\])?)\s*\{([^{}]+)\}'
+)
+THEME_COLOR = re.compile(r"\s*--([a-z-]+)\s*:\s*(#[0-9a-fA-F]{3,8})\s*;\s*")
+
+
+def color_tokens(source):
+ blocks = {}
+ offset = 0
+ while source[offset:].strip():
+ block = THEME_BLOCK.match(source, offset)
+ if block is None or block[1] in blocks:
+ raise ValidationError(
+ "Use one :root block and an optional dark :root block."
+ )
+ offset = block.end()
+ tokens = {}
+ values = block[2]
+ position = 0
+ while values[position:].strip():
+ color = THEME_COLOR.match(values, position)
+ if (
+ color is None
+ or color[1] not in COLOR_TOKENS
+ or len(color[2]) not in {4, 5, 7, 9}
+ or color[1] in tokens
+ ):
+ raise ValidationError(
+ "Use supported color variables with hexadecimal values."
+ )
+ tokens[color[1]] = color[2]
+ position = color.end()
+ if not tokens:
+ raise ValidationError(
+ "Add at least one color variable to each block."
+ )
+ blocks[block[1]] = tokens
+ if ":root" not in blocks:
+ raise ValidationError("Provide a :root block for the default colors.")
+ return blocks
+
+
+def render_colors(blocks):
+ return "\n".join(
+ f"{selector} {{ "
+ + " ".join(f"--{name}: {value};" for name, value in tokens.items())
+ + " }"
+ for selector, tokens in blocks.items()
+ )
+
+
+class ThemeUploadForm(forms.ModelForm):
+ stylesheet = forms.FileField(
+ label="Theme stylesheet",
+ help_text="Upload a CSS file with Coulobre color variables.",
+ )
+
+ class Meta:
+ model = PanelTheme
+ fields = ["name", "stylesheet"]
+
+ def clean_stylesheet(self):
+ uploaded = self.cleaned_data["stylesheet"]
+ if uploaded.size > 32768:
+ raise ValidationError("Theme stylesheets can be at most 32 KiB.")
+ try:
+ return color_tokens(uploaded.read().decode("utf-8"))
+ except UnicodeError as error:
+ raise ValidationError("Use a UTF-8 stylesheet.") from error
+
+
+THEME_PREVIEW = "coulobre_theme_preview"
+
+
+class ThemeManagementView(OperatorAuthorization, FormView):
+ form_class = ThemeUploadForm
+ template_name = "hosting/panel_content.html"
+ extra_context = {
+ "title": "Themes",
+ "submit_label": "Preview theme",
+ "upload": True,
+ }
+ success_url = reverse_lazy("panel:theme_management")
+
+ def get_context_data(self, **kwargs):
+ return super().get_context_data(
+ themes=PanelTheme.objects.order_by("name"), **kwargs
+ )
+
+ def form_valid(self, form):
+ self.request.session[THEME_PREVIEW] = {
+ "name": form.cleaned_data["name"],
+ "colors": form.cleaned_data["stylesheet"],
+ }
+ return self.render_to_response(
+ self.get_context_data(
+ form=self.form_class(),
+ theme_preview=form.cleaned_data["name"],
+ )
+ )
+
+ def post(self, request, *args, **kwargs):
+ if request.POST.get("action") != "install":
+ return super().post(request, *args, **kwargs)
+ preview = request.session.pop(THEME_PREVIEW, None)
+ if preview is None:
+ messages.error(request, "Preview a theme before adding it.")
+ else:
+ _, created = PanelTheme.objects.get_or_create(
+ name=preview["name"], defaults={"colors": preview["colors"]}
+ )
+ if created:
+ messages.success(
+ request, "Theme added. Users can select it in My account."
+ )
+ else:
+ messages.error(
+ request, "A theme with this name already exists."
+ )
+ return redirect(self.success_url)
+
+
+@require_safe
+@never_cache
+def preview_stylesheet(request):
+ if (
+ not request.user.is_superuser
+ or not request.user.is_verified()
+ or getattr(request, "impersonation", None)
+ ):
+ raise PermissionDenied
+ preview = request.session.get(THEME_PREVIEW)
+ return HttpResponse(
+ render_colors(preview["colors"]) if preview else "",
+ content_type="text/css; charset=utf-8",
+ headers={"X-Content-Type-Options": "nosniff"},
+ )
+
+
+class ThemeSelectionForm(forms.Form):
+ theme = forms.ModelChoiceField(
+ queryset=PanelTheme.objects.all(),
+ required=False,
+ empty_label="Installation default",
+ )
+
+
+class ThemeSelectionView(LoginRequiredMixin, FormView):
+ form_class = ThemeSelectionForm
+ template_name = "hosting/panel_content.html"
+ extra_context = {"title": "Choose a theme", "submit_label": "Apply theme"}
+ success_url = reverse_lazy("panel:account_security")
+
+ def get_initial(self):
+ return {
+ "theme": UserTheme.objects.filter(user=self.request.user)
+ .values_list("theme_id", flat=True)
+ .first()
+ }
+
+ def form_valid(self, form):
+ UserTheme.objects.update_or_create(
+ user=self.request.user,
+ defaults={"theme": form.cleaned_data["theme"]},
+ )
+ return super().form_valid(form)
+
+
+@require_safe
+@never_cache
+def user_stylesheet(request):
+ colors = None
+ if request.user.is_authenticated and not getattr(
+ request, "impersonation", None
+ ):
+ colors = (
+ UserTheme.objects.filter(user=request.user)
+ .values_list("theme__colors", flat=True)
+ .first()
+ )
+ return HttpResponse(
+ render_colors(colors) if colors else "",
+ content_type="text/css; charset=utf-8",
+ headers={"X-Content-Type-Options": "nosniff"},
+ )
+
+
+class AnnouncementForm(forms.ModelForm):
+ class Meta:
+ model = PanelAnnouncement
+ fields = ["audience", "subject", "body"]
+ widgets = {"body": forms.Textarea(attrs={"rows": 6})}
+
+
+class AnnouncementView(OperatorAuthorization, FormView):
+ form_class = AnnouncementForm
+ template_name = "hosting/panel_content.html"
+ extra_context = {
+ "title": "Message users",
+ "submit_label": "Publish announcement",
+ "preview_required": True,
+ }
+ success_url = reverse_lazy("panel:announcements")
+
+ def form_valid(self, form):
+ if self.request.POST.get("action") != "publish":
+ return self.render_to_response(
+ self.get_context_data(form=form, preview=form.cleaned_data)
+ )
+ if (
+ self.request.session.pop("announcement_preview", None)
+ != form.cleaned_data
+ ):
+ form.add_error(None, "Review a preview of this message first.")
+ return self.form_invalid(form)
+ announcement = form.save(commit=False)
+ announcement.author = self.request.user
+ announcement.save()
+ messages.success(self.request, "Announcement published.")
+ return super().form_valid(form)
+
+ def get_context_data(self, **kwargs):
+ if kwargs.get("preview"):
+ self.request.session["announcement_preview"] = kwargs["preview"]
+ return super().get_context_data(**kwargs)
+
+
+def panel_announcements(request):
+ if not request.user.is_authenticated or getattr(
+ request, "impersonation", None
+ ):
+ return {}
+ audience = [PanelAnnouncement.Audience.ALL]
+ if reseller_for_user(request.user) is not None:
+ audience.append(PanelAnnouncement.Audience.MANAGERS)
+ announcements = PanelAnnouncement.objects.filter(
+ audience__in=audience
+ ).order_by("-published_at")[:3]
+ return {
+ "panel_announcements": announcements,
+ "has_user_theme": UserTheme.objects.filter(
+ user=request.user, theme__isnull=False
+ ).exists(),
+ }
+
+
+class DirectAdminGuideView(OperatorAuthorization, TemplateView):
+ template_name = "hosting/directadmin_guide.html"
diff --git a/src/coulobre/hosting/php_settings.py b/src/coulobre/hosting/php_settings.py
index 438483f..77802dc 100644
--- a/src/coulobre/hosting/php_settings.py
+++ b/src/coulobre/hosting/php_settings.py
@@ -110,8 +110,10 @@ def plan_php_versions(account):
@transaction.atomic
-def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
- account = lock_hosting_account(account_id, customer_id=None)
+def queue_site_php_settings(
+ account_id, php_settings, *, use_plan=False, customer_id=None
+):
+ account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
if not site_is_active(account):
raise ValidationError(
@@ -119,6 +121,22 @@ def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
)
if use_plan:
php_settings = plan_php_settings(account)
+ elif customer_id is not None:
+ require_active_services(account)
+ limits = plan_php_settings(account).manifest()
+ values = php_settings.manifest()
+ for key, limit in limits.items():
+ value = values[key]
+ if value is not None and (limit is None or value > limit):
+ raise ValidationError(
+ "Keep PHP limits within the account's hosting plan."
+ )
+ if value is None:
+ values[key] = limit
+ try:
+ php_settings = PhpPoolSettings.from_manifest(values)
+ except PhpPoolSettingsError as error:
+ raise ValidationError(str(error)) from error
changes = {
"domain": account.primary_domain,
diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py
index 7ee823f..b557c3d 100644
--- a/src/coulobre/hosting/reseller_views.py
+++ b/src/coulobre/hosting/reseller_views.py
@@ -45,7 +45,7 @@ class ResellerPolicyForm(forms.ModelForm):
help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.",
"hosting_plans": (
- "Plans available when a reseller creates an account."
+ "Plans available when a manager creates an account."
),
}
diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py
index 5034572..b078fda 100644
--- a/src/coulobre/hosting/resource_requests.py
+++ b/src/coulobre/hosting/resource_requests.py
@@ -4,6 +4,7 @@ from django.db.models import F
from coulobre.mail_node import MailboxSpec
+from .domain_policies import require_managed
from .models import (
DatabaseProvisioning,
HostingAccount,
@@ -60,6 +61,7 @@ def create_mailbox_request(
):
account = lock_hosting_account(account_id, customer_id)
require_open_account(account)
+ require_managed(account, account.primary_domain, "mail_managed")
try:
spec = MailboxSpec(account.primary_domain, local_part)
except ValueError as error:
@@ -106,6 +108,7 @@ def queue_mailbox_provisioning(mailbox):
account = lock_hosting_account(
mailbox.mail_domain.account_id, customer_id=None
)
+ require_managed(account, mailbox.mail_domain.domain, "mail_managed")
require_active_services(account)
return MailboxProvisioning.objects.queue(mailbox=mailbox)
diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py
index cd879f9..411d70a 100644
--- a/src/coulobre/hosting/tasks.py
+++ b/src/coulobre/hosting/tasks.py
@@ -46,6 +46,7 @@ from .models import (
ComponentRestoreJob,
DatabaseProvisioning,
DnsPublication,
+ HostingAccount,
HostingMailDomain,
IndependentWebsite,
MailboxProvisioning,
@@ -97,6 +98,7 @@ from .offsite_backups import (
)
from .password_reset import send_customer_reset_email
from .php_settings import plan_php_versions
+from .resource_requests import lock_hosting_account
from .service_changes import apply_service_change
from .sftp import site_is_active
from .sign_in_limits import current_window
@@ -836,9 +838,17 @@ def apply_account_backup(job):
raise ValueError(
"Enable local mailbox backups before trying again."
)
+ if (
+ job.export_customer_id is not None
+ and job.export_customer_id != job.account.customer_id
+ ):
+ raise ValueError("The hosting account's customer assignment changed.")
size = create_local_account_backup(
AccountBackupRequest(
- job.backup_id, backup, remote_mail=job.remote_mail
+ job.backup_id,
+ backup,
+ remote_mail=job.remote_mail,
+ publish_to_customer=job.export_customer_id is not None,
)
)
return {"archive_bytes": size}
@@ -899,7 +909,28 @@ def restore_website(job_id):
)
+def with_customer_restore_scope(job, apply):
+ customer_id = job.requested_customer_id
+ if customer_id is None:
+ return apply(job)
+ with transaction.atomic():
+ try:
+ account = lock_hosting_account(job.backup.account_id, customer_id)
+ except HostingAccount.DoesNotExist:
+ raise ValueError(
+ "The hosting account assignment changed."
+ ) from None
+ if account.retired_at is not None:
+ raise ValueError("The hosting account is retired.")
+ job.backup.account = account
+ return apply(job)
+
+
def apply_website_restore(job):
+ return with_customer_restore_scope(job, restore_website_target)
+
+
+def restore_website_target(job):
account = job.backup.account
site = (
WebSite.from_manifest(job.site_manifest)
@@ -938,6 +969,10 @@ def restore_backup_component(job_id):
def apply_component_restore(job):
+ return with_customer_restore_scope(job, restore_component_target)
+
+
+def restore_component_target(job):
backup = job.backup
resources = available_restore_resources(
backup, job.kind, current_restore_resources(backup.account, job.kind)
@@ -1081,7 +1116,7 @@ def refresh_mail_queue(domain_id, requested_at):
return
try:
report = apply_on_local_node(
- MailQueueRequest(domain.domain),
+ MailQueueRequest(domain.domain, detailed=True),
"/run/coulobre-mail-apply.sock",
"mail node",
"queue summary",
@@ -1097,7 +1132,11 @@ def refresh_mail_queue(domain_id, requested_at):
or type(report["partial"]) is not bool
):
raise ValueError
- snapshot = {"counts": counts, "partial": report["partial"]}
+ snapshot = {
+ "counts": counts,
+ "partial": report["partial"],
+ "entries": report.get("entries", []),
+ }
except (KeyError, TypeError, ValueError, OSError):
snapshot = {"error": "Could not read the queue from the mail node."}
HostingMailDomain.objects.filter(
@@ -1222,3 +1261,62 @@ def collect_mailbox_usage(mailbox_id, requested_at):
except (KeyError, OSError, ValueError):
used = None
mailboxes.update(usage_bytes=used, usage_observed_at=timezone.now())
+
+
+@shared_task(queue="coulobre-operator-actions")
+def run_operator_operation(job_id):
+ from coulobre.operator_node import SOCKET, OperatorRequest
+
+ from .models import OperatorOperation
+ from .node_client import apply_on_local_node
+
+ def apply(job):
+ spec = OperatorRequest(job.action, job.target, job.plan)
+ result = apply_on_local_node(
+ spec, SOCKET, "operator service", "host operation", timeout=32 * 60
+ )
+ for key in (*spec.manifest(), "state", "problem"):
+ result.pop(key, None)
+ return {"result": result}
+
+ run_provisioning_job(
+ OperatorOperation.objects.all(),
+ job_id,
+ apply,
+ "The operator service did not report a result. "
+ "Check the service journal.",
+ lease=timedelta(minutes=35),
+ )
+
+
+@shared_task(queue="coulobre-mailbox-provisioning")
+def run_mail_queue_operation(job_id):
+ from coulobre.mail_queue import MailQueueAction
+
+ from .models import MailQueueOperation
+ from .node_client import apply_on_local_node
+
+ def apply(job):
+ if (
+ not settings.LOCAL_MAILBOX_PROVISIONING
+ or job.domain.account.retired_at is not None
+ ):
+ raise ValueError("The mail domain is no longer available.")
+ request = MailQueueAction(
+ job.domain.domain, job.queue_id, job.arrival, job.action
+ )
+ apply_on_local_node(
+ request,
+ "/run/coulobre-mail-apply.sock",
+ "mail node",
+ "queue action",
+ timeout=60,
+ )
+
+ run_provisioning_job(
+ MailQueueOperation.objects.select_related("domain__account"),
+ job_id,
+ apply,
+ "The mail node did not confirm the queue action.",
+ lease=timedelta(minutes=3),
+ )
diff --git a/src/coulobre/hosting/templates/hosting/account_retirement.html b/src/coulobre/hosting/templates/hosting/account_retirement.html
index 8108e60..bdcc215 100644
--- a/src/coulobre/hosting/templates/hosting/account_retirement.html
+++ b/src/coulobre/hosting/templates/hosting/account_retirement.html
@@ -66,7 +66,7 @@
Retention and name release
+ {% for entry in mail_domain.queue_report.entries %}
{{ entry.queue_id }} {{ entry.queue|capfirst }}
+
+ {% if entry.queue == 'deferred' %}{% endif %}
+ {% if entry.queue == 'hold' %}
+ {% elif entry.queue == 'active' or entry.queue == 'deferred' %}{% endif %}
+
+ {% for job in operations %}
Mail Queue
+ {% for domain in domains %}
{% include "hosting/pagination.html" %}{{ title }}
{{ message }}
{% endfor %} +Enable the operator service on the host to run these operations.
{% endif %} +{{ job.problem }}
{% endif %} + {% if job.action == 'package-preview' and job.result.fingerprint %} +{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.
+{{ package }}MariaDB {{ job.result.version }} · Slow query logging {{ job.result.slow_logging|yesno:"enabled,disabled" }}
+No operations yet.
{% endfor %} +{{ message }}
{% endfor %} + {% if theme_preview %} +This service needs setup.
{% endif %} + {% if section == 'statistics' %} +| Hosting account | Disk use | Traffic | Domains | Databases | Mailboxes |
|---|---|---|---|---|---|
| {{ account.primary_domain }} | {% if storage is not None %}{{ storage|filesizeformat }}{% else %}Unavailable{% endif %} | {% if traffic is not None %}{{ traffic|filesizeformat }}{% else %}Unavailable{% endif %} | {{ account.domain_count|default:"1" }} | {{ account.database_count }} | {{ account.mailbox_count }} |
| No hosting accounts are available. | |||||
| Domain | Task | Status | Next run (UTC) |
|---|---|---|---|
| {{ job.domain }} | {% if target %}{{ job.name }}{% else %}{{ job.name }}{% endif %} | {{ job.enabled|yesno:"Enabled,Paused" }} | {{ job.next_run_at|date:"j M Y H:i"|default:"—" }} |
| No scheduled tasks for these accounts. | |||
Website logs need a configured collector.
{% endif %} + {% endif %} + {% include "hosting/pagination.html" %}{{ message }}
{% endfor %} {% if form.errors %}The message includes an invitation link for choosing a password and setup details for the new hosting account. Your welcome text appears before the setup details.
+{{ welcome_preview }}