From 377344e5917f36abc6547a4bce5421d50f6a47d5 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 22:31:20 +0100 Subject: [PATCH] Connect hosting workspaces to scoped services and backups --- .../systemd/coulobre-account-backup@.service | 1 + deploy/systemd/coulobre-operator-apply.socket | 14 + .../systemd/coulobre-operator-apply@.service | 17 ++ .../systemd/coulobre-operator-worker.service | 23 ++ docs/deployment.md | 44 +++ pyproject.toml | 1 + src/coulobre/account_backup.py | 22 +- src/coulobre/account_backup_request.py | 39 ++- src/coulobre/customer_backup_export.py | 74 +++++ .../hosting/account_administration.py | 188 ++++++++---- src/coulobre/hosting/account_backups.py | 49 ++- src/coulobre/hosting/backup_restores.py | 21 +- src/coulobre/hosting/customer_backup_views.py | 178 ++++++++++- src/coulobre/hosting/dns_publication.py | 2 + src/coulobre/hosting/domain_policies.py | 15 + src/coulobre/hosting/domain_services.py | 176 +++++++++++ src/coulobre/hosting/installation_views.py | 75 ++++- src/coulobre/hosting/invitations.py | 65 ++-- src/coulobre/hosting/mail_queue_views.py | 80 ++++- .../migrations/0061_domain_service_policy.py | 50 +++ .../0062_panel_themes_and_announcements.py | 96 ++++++ .../migrations/0063_operator_operations.py | 65 ++++ .../0064_customer_backup_exports.py | 17 ++ .../migrations/0065_mail_queue_operations.py | 62 ++++ .../migrations/0066_customer_restore_scope.py | 22 ++ src/coulobre/hosting/models.py | 76 +++++ src/coulobre/hosting/operator_tools.py | 166 ++++++++++ src/coulobre/hosting/panel_content.py | 289 ++++++++++++++++++ src/coulobre/hosting/php_settings.py | 22 +- src/coulobre/hosting/reseller_views.py | 2 +- src/coulobre/hosting/resource_requests.py | 3 + src/coulobre/hosting/tasks.py | 104 ++++++- .../templates/hosting/account_retirement.html | 2 +- .../templates/hosting/account_security.html | 1 + .../hosting/templates/hosting/base.html | 3 + .../templates/hosting/connected_nodes.html | 13 + .../templates/hosting/customer_backups.html | 24 +- .../templates/hosting/customer_restore.html | 25 ++ .../templates/hosting/directadmin_guide.html | 9 + .../templates/hosting/domain_workspace.html | 55 ++++ .../hosting/feature_configuration.html | 15 +- .../hosting/templates/hosting/mail_queue.html | 16 + .../templates/hosting/mail_queue_index.html | 8 + .../templates/hosting/operator_tools.html | 29 ++ .../templates/hosting/panel_content.html | 31 ++ .../templates/hosting/system_workspace.html | 33 +- .../hosting/templates/hosting/updates.html | 2 +- .../templates/hosting/workspace_form.html | 15 +- src/coulobre/hosting/test_customer_restore.py | 73 +++++ .../hosting/test_operator_workspaces.py | 91 ++++++ src/coulobre/hosting/test_workspaces.py | 60 +++- src/coulobre/hosting/urls.py | 67 +++- src/coulobre/hosting/views.py | 29 +- src/coulobre/hosting/workspaces.py | 83 ++++- src/coulobre/mail_node.py | 21 +- src/coulobre/mail_queue.py | 148 ++++++++- src/coulobre/operator_node.py | 180 +++++++++++ src/coulobre/settings.py | 1 + 58 files changed, 2920 insertions(+), 172 deletions(-) create mode 100644 deploy/systemd/coulobre-operator-apply.socket create mode 100644 deploy/systemd/coulobre-operator-apply@.service create mode 100644 deploy/systemd/coulobre-operator-worker.service create mode 100644 src/coulobre/customer_backup_export.py create mode 100644 src/coulobre/hosting/domain_policies.py create mode 100644 src/coulobre/hosting/domain_services.py create mode 100644 src/coulobre/hosting/migrations/0061_domain_service_policy.py create mode 100644 src/coulobre/hosting/migrations/0062_panel_themes_and_announcements.py create mode 100644 src/coulobre/hosting/migrations/0063_operator_operations.py create mode 100644 src/coulobre/hosting/migrations/0064_customer_backup_exports.py create mode 100644 src/coulobre/hosting/migrations/0065_mail_queue_operations.py create mode 100644 src/coulobre/hosting/migrations/0066_customer_restore_scope.py create mode 100644 src/coulobre/hosting/operator_tools.py create mode 100644 src/coulobre/hosting/panel_content.py create mode 100644 src/coulobre/hosting/templates/hosting/connected_nodes.html create mode 100644 src/coulobre/hosting/templates/hosting/customer_restore.html create mode 100644 src/coulobre/hosting/templates/hosting/directadmin_guide.html create mode 100644 src/coulobre/hosting/templates/hosting/domain_workspace.html create mode 100644 src/coulobre/hosting/templates/hosting/mail_queue_index.html create mode 100644 src/coulobre/hosting/templates/hosting/operator_tools.html create mode 100644 src/coulobre/hosting/templates/hosting/panel_content.html create mode 100644 src/coulobre/hosting/test_customer_restore.py create mode 100644 src/coulobre/hosting/test_operator_workspaces.py create mode 100644 src/coulobre/operator_node.py 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

-

Suspend managed services before retirement. Retirement removes customer and reseller access to this account and stops its backup schedule.

+

Suspend managed services before retirement. Retirement removes customer and manager access to this account and stops its backup schedule.

Keep names reserved preserves the suspended resources, DNS, and incoming mail.

Release names and retain data removes hosting configuration, certificates, keys, delivery, and DNS. Website files and mail are moved to node archives. Databases stay locked under their original identifiers.

Type the primary domain to confirm this preview.

diff --git a/src/coulobre/hosting/templates/hosting/account_security.html b/src/coulobre/hosting/templates/hosting/account_security.html index 1e152fb..af44131 100644 --- a/src/coulobre/hosting/templates/hosting/account_security.html +++ b/src/coulobre/hosting/templates/hosting/account_security.html @@ -13,6 +13,7 @@ {% if not email_available %}

Email changes require configured panel email delivery.

{% endif %}
Change password + Choose theme {% if email_available %}Change email address{% endif %} {% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app {% if factor_enabled %}Generate recovery codes{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index e6025a7..231abdc 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -7,6 +7,8 @@ {% if custom_panel_theme %}{% endif %} + {% if has_user_theme %}{% endif %} + {% block extra_styles %}{% endblock %} @@ -79,6 +81,7 @@
{% endif %} + {% for announcement in panel_announcements %}
{{ announcement.subject }}{{ announcement.body|linebreaks }}
{% endfor %} {% block content %}{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/connected_nodes.html b/src/coulobre/hosting/templates/hosting/connected_nodes.html new file mode 100644 index 0000000..a119866 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/connected_nodes.html @@ -0,0 +1,13 @@ +{% extends "hosting/base.html" %} +{% block title %}Connected nodes · Coulobre Panel{% endblock %} +{% block content %} +

Connected nodes

Service health
+ {% if topology.problem %}

{{ topology.problem }}

{% endif %} +
+
+ + {% for node in topology.nodes %} + {% empty %}{% endfor %} +
RoleHostReleaseState
{{ node.role|upper }}{{ node.host }}{{ node.release|default:"Unknown" }}{{ node.state|capfirst }}
No linked mail or DNS receivers reported.
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/customer_backups.html b/src/coulobre/hosting/templates/hosting/customer_backups.html index 49af019..855b0a7 100644 --- a/src/coulobre/hosting/templates/hosting/customer_backups.html +++ b/src/coulobre/hosting/templates/hosting/customer_backups.html @@ -1,19 +1,35 @@ {% extends "hosting/base.html" %} -{% block title %}Backup & Restore · Coulobre Panel{% endblock %} +{% block title %}Backup & Restore · Coulobre Panel
+

Recent restores

+ +
+{% endblock %} {% block content %}

Backup & Restore

{{ account.primary_domain }}

{% for message in messages %}

{{ message }}

{% endfor %} {% if may_create %}
-

Create a backup

+

Create a backup

Download the latest completed customer backup over SFTP at /backups/latest.zip.

{% csrf_token %}{{ form.as_div }}
- {% endif %} + {% else %}

Customer backups require an active website, SFTP and the local backup service.

{% endif %}

Recent backups

+
+

Recent restores

+ +
{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/customer_restore.html b/src/coulobre/hosting/templates/hosting/customer_restore.html new file mode 100644 index 0000000..fdc62a4 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_restore.html @@ -0,0 +1,25 @@ +{% extends "hosting/base.html" %} +{% block title %}Restore {{ kind }} · Coulobre Panel{% endblock %} +{% block content %} + ← Backup & Restore +

Restore {{ kind }}

{{ account.primary_domain }} · Backup from {{ backup.requested_at|date:"j M Y H:i" }} UTC

+
+ {% if kind == 'website' %}

An entire website needs an empty document root. A single file needs an existing parent directory.

+ {% elif kind == 'database' %}

Choose an empty database and keep its applications disconnected during the restore.

+ {% else %}

Choose an unused mailbox and pause delivery and client access during the restore.

{% endif %} +
+ {% csrf_token %}{{ form.as_div }} + {% if preview %} +
+

Review destination

+

{% if kind == "website" %}{{ target.domain }}{% elif kind == "database" %}{{ target.name }}{% else %}{{ target.address }}{% endif %}

+ {% if preview.filename %}

{{ preview.filename }}{% if preview.replace %} · Replace the current file{% endif %}

{% endif %} +
+ {% endif %} +
+ + {% if preview %}{% endif %} +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/directadmin_guide.html b/src/coulobre/hosting/templates/hosting/directadmin_guide.html new file mode 100644 index 0000000..05b42e4 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/directadmin_guide.html @@ -0,0 +1,9 @@ +{% extends "hosting/base.html" %} +{% block title %}DirectAdmin import · Coulobre Panel{% endblock %} +{% block content %} +

DirectAdmin import

+
+

Use a DirectAdmin account archive. Inspect it and review the planned account, website, database, mail and DNS changes before importing.

+ Open the import guide +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/domain_workspace.html b/src/coulobre/hosting/templates/hosting/domain_workspace.html new file mode 100644 index 0000000..0ac827a --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/domain_workspace.html @@ -0,0 +1,55 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} +
+

{{ title }}

{{ account.primary_domain }}

+ {% if page == 'domains' and can_add_site %}Add domain{% endif %} +
+ {% for message in messages %}

{{ message }}

{% endfor %} +
+
+ + + +
+
+ {% if page == 'domains' %} +
+
{% csrf_token %}{{ form.as_div }}
+
+ {% elif page == 'dns' %} + {% if zone %} +
+

DNS records

{% if may_edit_dns %}Edit zone{% endif %}
+
+ {% for record in records %}{% endfor %} +
NameTypeValue
{{ record.name }}{{ record.type }}{{ record.value }}
+
+ {% else %}

This domain has no saved Coulobre DNS zone.

{% endif %} + {% if not policy.dns_managed %}

Make DNS changes at the domain's authoritative DNS provider.

{% endif %} + {% elif page == 'php' or page == 'files' %} +
+ {% if primary %} + {% if page == 'php' %}Select PHP version + Edit PHP limits + {% else %}Browse files{% endif %} + {% elif website %} + {% if page == 'php' %}Select PHP version + {% else %}Browse files{% endif %} + {% else %}

Select an active website for this action.

{% endif %} +
+ {% elif mail_domain and policy.mail_managed %} +
+ {% if page == 'forwarders' %} +

Forwarders and catch-all

Manage forwarders
+ {% else %} + + {% endif %} +
+ {% else %}

This domain has no managed email accounts.

{% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html index 429dc89..4eef2c4 100644 --- a/src/coulobre/hosting/templates/hosting/feature_configuration.html +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -2,7 +2,19 @@ {% block title %}Configure features · Coulobre Panel{% endblock %} {% block content %} ← About Coulobre -

Configure features

+

{% if settings_tabs %}Operator Settings{% else %}Configure features{% endif %}

+ {% if settings_tabs %} + + {% endif %} + {% for message in messages %}

{{ message }}

{% endfor %} + {% if selected_section == 'general' %} +
+

Installation

+ About Coulobre +
+ {% else %}

Choose which configured features the panel can use for new requests. Existing sites, mailboxes, scheduled tasks and backups keep running.

@@ -24,4 +36,5 @@
+ {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/mail_queue.html b/src/coulobre/hosting/templates/hosting/mail_queue.html index a5f99f9..36d2fcf 100644 --- a/src/coulobre/hosting/templates/hosting/mail_queue.html +++ b/src/coulobre/hosting/templates/hosting/mail_queue.html @@ -22,4 +22,20 @@ {% endif %} + {% if mail_domain.queue_report.entries and request.user.is_superuser and request.user.is_verified %} +
+ {% endif %} + {% if operations %}
{% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/mail_queue_index.html b/src/coulobre/hosting/templates/hosting/mail_queue_index.html new file mode 100644 index 0000000..cf1e746 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mail_queue_index.html @@ -0,0 +1,8 @@ +{% extends "hosting/base.html" %} +{% block content %} +

Mail Queue

+
{% include "hosting/pagination.html" %}
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/operator_tools.html b/src/coulobre/hosting/templates/hosting/operator_tools.html new file mode 100644 index 0000000..e761e9f --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/operator_tools.html @@ -0,0 +1,29 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} +

{{ title }}

+
+ {% if page == 'packages' %}Coulobre updates + {% elif page == 'services' %}Service health{% endif %} +
+ {% for message in messages %}

{{ message }}

{% endfor %} +
+ {% if available %}
{% csrf_token %}{{ form.as_div }}
+ {% else %}

Enable the operator service on the host to run these operations.

{% endif %} +
+
+

Operation history

+ {% for job in jobs %} +
{{ job.requested_at|date:"j M Y H:i" }} · {{ job.action }}{% if job.target %} · {{ job.target }}{% endif %} · {{ job.state|capfirst }} + {% if job.problem %}

{{ job.problem }}

{% endif %} + {% if job.action == 'package-preview' and job.result.fingerprint %} +

{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.

+
    {% for package in job.result.packages %}
  • {{ package }}
  • {% endfor %}
+ {% elif job.action == 'database-report' and job.result.version %} +

MariaDB {{ job.result.version }} · Slow query logging {{ job.result.slow_logging|yesno:"enabled,disabled" }}

+
{% for key, value in job.result.counters.items %}
{{ key }}
{{ value }}
{% endfor %}
+ {% endif %} +
+ {% empty %}

No operations yet.

{% endfor %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/panel_content.html b/src/coulobre/hosting/templates/hosting/panel_content.html new file mode 100644 index 0000000..1dcafb8 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/panel_content.html @@ -0,0 +1,31 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block extra_styles %}{% if theme_preview %}{% endif %}{% endblock %} +{% block content %} +

{{ title }}

+ {% for message in messages %}

{{ message }}

{% endfor %} + {% if theme_preview %} +
+

Previewing {{ theme_preview }}

+
+ {% csrf_token %} + Close preview +
+
+ {% endif %} + {% if preview %}

{{ preview.subject }}

{{ preview.body|linebreaks }}
{% endif %} +
+
+ {% csrf_token %}{{ form.as_div }} +
+ {% if preview_required %}{% endif %} + {% if not preview_required or preview %}{% endif %} +
+
+
+ {% if themes %} +
+ +
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/system_workspace.html b/src/coulobre/hosting/templates/hosting/system_workspace.html index 561f3e2..de3067d 100644 --- a/src/coulobre/hosting/templates/hosting/system_workspace.html +++ b/src/coulobre/hosting/templates/hosting/system_workspace.html @@ -1,16 +1,29 @@ {% extends "hosting/base.html" %} {% block title %}{{ title }} · Coulobre Panel{% endblock %} {% block content %} -

{{ title }}

+

{{ title }}

{% if section == 'statistics' %}

Traffic for {{ month }}. Usage is based on available measurements.

{% endif %}
- - {% if not target %}

This service needs setup.

{% endif %} + {% if section == 'statistics' %} +
+ + {% for account, storage, traffic in rows %} + + {% empty %}{% endfor %} +
Hosting accountDisk useTrafficDomainsDatabasesMailboxes
{{ 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.
+ {% elif section == 'tasks' %} +
+ + {% for job in tasks %} + + {% empty %}{% endfor %} +
DomainTaskStatusNext 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.
+ {% else %} + + {% if not target %}

Website logs need a configured collector.

{% endif %} + {% endif %} + {% include "hosting/pagination.html" %}
{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/updates.html b/src/coulobre/hosting/templates/hosting/updates.html index 0f8ebd9..5381c97 100644 --- a/src/coulobre/hosting/templates/hosting/updates.html +++ b/src/coulobre/hosting/templates/hosting/updates.html @@ -4,7 +4,7 @@ {% block content %}

Updates

Installed version {{ installed_version|default:"unknown" }}

- Refresh status +
{% for message in messages %}

{{ message }}

{% endfor %} {% if form.errors %}
{{ form.errors }}
{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/workspace_form.html b/src/coulobre/hosting/templates/hosting/workspace_form.html index f3ce334..e53d68e 100644 --- a/src/coulobre/hosting/templates/hosting/workspace_form.html +++ b/src/coulobre/hosting/templates/hosting/workspace_form.html @@ -6,14 +6,21 @@
{% csrf_token %} {{ form.as_div }} - {% if invitation_preview %} -
+ {% if welcome_preview %} +
Welcome email preview -

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 }}
{% endif %} + {% if moving %} +
+

Move to {{ destination }}

+
    {% for item in moving %}
  • {{ item.primary_domain }} · {{ item.hosting_plan }} · from {{ item.reseller|default:"Unassigned" }}
  • {% endfor %}
+
+ {% endif %}
- + {% if invitation_preview or move_preview_enabled %}{% endif %} + {% if not move_preview_enabled or moving %}{% endif %} Cancel
diff --git a/src/coulobre/hosting/test_customer_restore.py b/src/coulobre/hosting/test_customer_restore.py new file mode 100644 index 0000000..d81dc0c --- /dev/null +++ b/src/coulobre/hosting/test_customer_restore.py @@ -0,0 +1,73 @@ +from unittest.mock import patch +from uuid import uuid4 + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.account_backup import AccountBackup +from coulobre.web_node import WebSite + +from .models import ( + AccountBackupJob, + ComponentRestoreJob, + Customer, + HostingAccount, + HostingDatabase, +) +from .tasks import restore_backup_component + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DATABASE_RESTORE=True) +class CustomerRestoreTests(TestCase): + def test_restore_requires_its_customers_backup_and_current_assignment( + self, + ): + users = get_user_model().objects + customer = Customer.objects.create(user=users.create_user("customer")) + other = Customer.objects.create(user=users.create_user("other")) + account = HostingAccount.objects.create( + name="Shop", primary_domain="shop.example.test", customer=customer + ) + database = HostingDatabase.objects.create( + account=account, suffix="cms" + ) + archive = AccountBackup( + WebSite(account.pk, account.primary_domain), (database.spec,) + ) + backup = AccountBackupJob.objects.create( + account=account, + manifest=archive.manifest(), + finished_at=timezone.now(), + export_customer_id=customer.pk, + ) + url = reverse( + "panel:customer_restore", args=[account.pk, backup.pk, "database"] + ) + self.client.force_login(other.user) + self.assertEqual(self.client.get(url).status_code, 404) + self.client.force_login(customer.user) + data = {"restore_id": str(uuid4()), "resource": database.suffix} + self.assertContains( + self.client.post(url, data | {"action": "restore"}), + "Review the destination before restoring.", + ) + self.assertContains( + self.client.post(url, data | {"action": "preview"}), + database.spec.name, + ) + self.assertFalse(ComponentRestoreJob.objects.exists()) + self.assertRedirects( + self.client.post(url, data | {"action": "restore"}), + reverse("panel:customer_backups", args=[account.pk]), + ) + job = ComponentRestoreJob.objects.get() + HostingAccount.objects.filter(pk=account.pk).update(customer=other) + with patch( + "coulobre.hosting.tasks.restore_local_component" + ) as restore: + restore_backup_component(job.pk) + restore.assert_not_called() + job.refresh_from_db() + self.assertEqual(job.state, "failed") diff --git a/src/coulobre/hosting/test_operator_workspaces.py b/src/coulobre/hosting/test_operator_workspaces.py new file mode 100644 index 0000000..dbc32d1 --- /dev/null +++ b/src/coulobre/hosting/test_operator_workspaces.py @@ -0,0 +1,91 @@ +import json +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import SimpleTestCase, TestCase +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from coulobre.mail_queue import MailQueueAction, change_queue_entry +from coulobre.operator_node import OperatorRequest, packages + +from .models import PanelTheme + + +class OperatorRequestTests(SimpleTestCase): + def test_unknown_services_and_changed_package_plans_are_rejected(self): + with self.assertRaises(ValueError): + OperatorRequest("restart", "ssh.service") + with ( + patch("coulobre.operator_node.locked_root_directory"), + patch( + "coulobre.operator_node.apt_plan", + return_value={"fingerprint": "0" * 64}, + ), + patch("coulobre.operator_node.command") as command, + self.assertRaisesMessage(ValueError, "The package plan changed"), + ): + packages(OperatorRequest("package-upgrade", plan="f" * 64)) + command.assert_not_called() + + def test_mail_action_requires_entire_recipient_scope_and_fresh_arrival( + self, + ): + message = { + "queue_id": "Ab12345", + "queue_name": "deferred", + "arrival_time": 1710000000, + "recipients": [ + {"address": "alice@example.test"}, + {"address": "bob@different.test"}, + ], + } + request = MailQueueAction( + "example.test", message["queue_id"], 1710000000, "flush" + ) + with ( + patch( + "coulobre.mail_queue.read_queue", + side_effect=lambda consume: consume([json.dumps(message)]), + ), + patch("coulobre.mail_queue.subprocess.run") as command, + ): + with self.assertRaises(ValueError): + change_queue_entry(request) + message["recipients"].pop() + message["arrival_time"] += 1 + with self.assertRaises(ValueError): + change_queue_entry(request) + command.assert_not_called() + + +class ThemePreviewTests(TestCase): + def test_theme_preview_uses_validated_css_and_requires_confirmation(self): + operator = get_user_model().objects.create_superuser("operator") + self.client.force_login(operator) + session = self.client.session + device = TOTPDevice.objects.create(user=operator, name="test") + session["otp_device_id"] = device.persistent_id + session.save() + url = reverse("panel:theme_management") + hostile = SimpleUploadedFile( + "custom.css", b":root { --accent: url(https://example.test); }" + ) + response = self.client.post( + url, {"name": "Test theme", "stylesheet": hostile} + ) + self.assertContains(response, "hexadecimal values") + stylesheet = SimpleUploadedFile( + "custom.css", b":root { --accent: #123456; }" + ) + response = self.client.post( + url, {"name": "Test theme", "stylesheet": stylesheet} + ) + self.assertContains(response, "Previewing Test theme") + self.assertFalse(PanelTheme.objects.exists()) + self.assertContains( + self.client.get(reverse("panel:preview_stylesheet")), "#123456" + ) + self.assertRedirects(self.client.post(url, {"action": "install"}), url) + self.assertEqual(PanelTheme.objects.get().name, "Test theme") diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py index b02839b..a8b3e92 100644 --- a/src/coulobre/hosting/test_workspaces.py +++ b/src/coulobre/hosting/test_workspaces.py @@ -60,17 +60,19 @@ class WorkspaceTests(TestCase): dns = reverse("panel:customer_workspace", args=["dns"]) self.assertRedirects( self.client.get(dns, {"account": second.pk}), - second.get_absolute_url() + "#domains-dns", + reverse("panel:domain_workspace", args=[second.pk, "dns"]), ) self.assertRedirects( - self.client.get(dns), second.get_absolute_url() + "#domains-dns" + self.client.get(dns), + reverse("panel:domain_workspace", args=[second.pk, "dns"]), ) self.assertEqual( self.client.get(dns, {"account": foreign.pk}).status_code, 404 ) HostingAccount.objects.filter(pk=second.pk).update(customer=None) self.assertRedirects( - self.client.get(dns), first.get_absolute_url() + "#domains-dns" + self.client.get(dns), + reverse("panel:domain_workspace", args=[first.pk, "dns"]), ) def test_manager_creates_login_and_hosting_under_its_own_policy(self): @@ -120,3 +122,55 @@ class WorkspaceTests(TestCase): self.assertFalse( get_user_model().objects.filter(username="overflow").exists() ) + + def test_transfer_preserves_every_active_account_in_the_customer_scope( + self, + ): + users = get_user_model().objects + operator = users.create_superuser("operator") + manager = Reseller.objects.create(user=users.create_user("source")) + destination = Reseller.objects.create( + user=users.create_user("destination"), account_limit=2 + ) + customer = Customer.objects.create( + user=users.create_user("customer"), reseller=manager + ) + plan = HostingPlan.objects.create(name="Small") + destination.hosting_plans.add(plan) + accounts = [ + HostingAccount.objects.create( + name=label, + primary_domain=f"{label}.example.test", + customer=customer, + reseller=manager, + hosting_plan=plan, + ) + for label in ("first", "second") + ] + from django_otp.plugins.otp_totp.models import TOTPDevice + + device = TOTPDevice.objects.create(user=operator, name="test") + self.client.force_login(operator) + session = self.client.session + session["otp_device_id"] = device.persistent_id + session.save() + url = reverse("panel:move_accounts") + data = {"account": accounts[0].pk, "manager": destination.pk} + self.assertContains( + self.client.post(url, data | {"action": "move", "confirm": "on"}), + "Preview and confirm", + ) + preview = self.client.post(url, data | {"action": "preview"}) + for account in accounts: + self.assertContains(preview, account.primary_domain) + response = self.client.post( + url, data | {"action": "move", "confirm": "on"} + ) + self.assertRedirects(response, accounts[0].get_absolute_url()) + customer.refresh_from_db() + self.assertEqual(customer.reseller_id, destination.pk) + self.assertEqual(destination.hostingaccount_set.count(), 2) + self.client.force_login(manager.user) + self.assertEqual( + self.client.get(accounts[0].get_absolute_url()).status_code, 404 + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index cac1d1c..0091d82 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -21,9 +21,10 @@ from .account_security import ( ) from .backup_restores import RestoreKind from .credential_views import DatabaseCredentialView, MailboxCredentialView -from .customer_backup_views import CustomerBackupView +from .customer_backup_views import CustomerBackupView, CustomerRestoreView from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView +from .domain_services import domain_workspace from .health_views import ServiceHealthView from .independent_website_views import ( IndependentWebsiteCreate, @@ -34,7 +35,16 @@ from .installation_views import FeatureConfigurationView, InstallationView from .invitations import AcceptInvitation, ManageInvitation from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_policy_views import MailRoutingEditor, MailVacationEditor -from .mail_queue_views import MailQueueView +from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action +from .operator_tools import ConnectedNodesView, OperatorToolsView +from .panel_content import ( + AnnouncementView, + DirectAdminGuideView, + ThemeManagementView, + ThemeSelectionView, + preview_stylesheet, + user_stylesheet, +) from .panel_roles import AssignPanelRoleView, switch_panel_role from .password_reset import ( CustomerPasswordResetView, @@ -75,6 +85,49 @@ from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), + path( + "mail-domains//queue/change/", + mail_queue_action, + name="mail_queue_action", + ), + path( + "system/nodes/", ConnectedNodesView.as_view(), name="connected_nodes" + ), + path( + "service-health/actions/", + OperatorToolsView.as_view(page="services"), + name="operator_service_actions", + ), + path( + "updates/server-packages/", + OperatorToolsView.as_view(page="packages"), + name="server_updates", + ), + path( + "server/database/", + OperatorToolsView.as_view(page="database"), + name="database_monitor", + ), + path("themes/", ThemeManagementView.as_view(), name="theme_management"), + path( + "my-account/theme/", + ThemeSelectionView.as_view(), + name="theme_selection", + ), + path("themes/preview.css", preview_stylesheet, name="preview_stylesheet"), + path("user-theme.css", user_stylesheet, name="user_stylesheet"), + path("announcements/", AnnouncementView.as_view(), name="announcements"), + path( + "imports/directadmin/", + DirectAdminGuideView.as_view(), + name="directadmin_guide", + ), + path( + "accounts//domains//", + domain_workspace, + name="domain_workspace", + ), path( "hosting//", customer_workspace, name="customer_workspace" ), @@ -99,6 +152,11 @@ urlpatterns = [ CustomerBackupView.as_view(), name="customer_backups", ), + path( + "hosting//backups//restore//", + CustomerRestoreView.as_view(), + name="customer_restore", + ), 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"), @@ -127,6 +185,11 @@ urlpatterns = [ FeatureConfigurationView.as_view(), name="feature_configuration", ), + path( + "settings//", + FeatureConfigurationView.as_view(), + name="operator_settings", + ), path("account/role/", switch_panel_role, name="switch_panel_role"), path( "logins/assign-role/", diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index a633d1a..30762be 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -77,6 +77,7 @@ from .dns_forms import ( zone_record_rows, ) from .dns_publication import queue_dns_publication +from .domain_policies import require_managed from .health_views import STALE_AFTER from .impersonation import ( CUSTOMER_WRITE_PERMISSIONS, @@ -1058,9 +1059,7 @@ class SiteStorageLimitEdit( return redirect(self.account) -class SitePhpSettingsEdit( - OperatorOnlyMixin, PermissionRequiredMixin, FormView -): +class SitePhpSettingsEdit(PermissionRequiredMixin, FormView): permission_required = CHANGE_SITE_PHP_SETTINGS form_class = SitePhpSettingsForm template_name = "hosting/site_php_settings_form.html" @@ -1070,14 +1069,21 @@ class SitePhpSettingsEdit( raise Http404 return super().dispatch(request, *args, **kwargs) + def has_permission(self): + user = self.request.user + return customer_for_user(user) is not None or ( + reseller_for_user(user) is None and super().has_permission() + ) + @cached_property def account(self): - return get_object_or_404( - HostingAccount.objects.select_related( - "hosting_plan", "php_settings_job" - ), - pk=self.kwargs["pk"], - ) + accounts = HostingAccount.objects.select_related( + "hosting_plan", "php_settings_job" + ).filter(retired_at__isnull=True) + customer = customer_for_user(self.request.user) + if customer is not None: + accounts = accounts.filter(customer=customer) + return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_initial(self): job = getattr(self.account, "php_settings_job", None) @@ -1099,6 +1105,9 @@ class SitePhpSettingsEdit( self.account.pk, None if use_plan else settings_from_form(form.cleaned_data), use_plan=use_plan, + customer_id=self.account.customer_id + if customer_for_user(self.request.user) is not None + else None, ) except HostingAccount.DoesNotExist: raise Http404 from None @@ -2210,6 +2219,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): self.account.pk, customer_id=None ) require_open_account(account) + require_managed(account, account.primary_domain, "dns_managed") zone = HostingDnsZone.objects.create( account=account, domain=account.primary_domain, @@ -2332,6 +2342,7 @@ class DnsZoneEdit(DnsZoneEditor): self.account.pk, customer_id=None ) require_open_account(account) + require_managed(account, self.zone.domain, "dns_managed") self.check_managed_mail_records(values) zones = HostingDnsZone.objects.filter( pk=self.zone.pk, serial=serial diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 14b10d1..073d2f7 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -1,14 +1,17 @@ from django.conf import settings from django.core.exceptions import PermissionDenied +from django.core.paginator import Paginator +from django.db.models import Count from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse +from django.utils import timezone from django.views.decorators.cache import never_cache from django.views.decorators.http import require_safe from .access import customer_for_user, reseller_for_user from .installation_features import panel_feature_allowed -from .models import HostingAccount +from .models import HostingAccount, WebsiteScheduledJob CUSTOMER_ACCOUNT = "coulobre_active_hosting_account" @@ -87,6 +90,8 @@ def customer_workspace(request, page): return redirect("panel:accounts") if page == "overview": return redirect(account) + if page in {"domains", "dns", "php", "files", "forwarders", "replies"}: + return redirect("panel:domain_workspace", pk=account.pk, page=page) _, destination, fragment = pages[page] return redirect( reverse( @@ -117,12 +122,60 @@ def system_workspace(request, page): or reseller_for_user(request.user) is not None or request.user.has_perm("hosting.view_websiteusage") ) + counts = { + "domain_count": Count("website_domains", distinct=True), + "database_count": Count("databases", distinct=True), + "mailbox_count": Count("mail_domains__mailboxes", distinct=True), + } + pagination = Paginator( + accounts.annotate(**counts).prefetch_related("website_usage"), 25 + ) + page_obj = pagination.get_page(request.GET.get("page")) + month = timezone.now().strftime("%Y-%m") + rows = [] + for account in page_obj.object_list: + snapshots = [ + row.report + for row in account.website_usage.all() + if row.observed_at + ] + storage = [ + row["storage_bytes"] + for row in snapshots + if row.get("storage_bytes") is not None + ] + traffic = [ + row["traffic_bytes"] + for row in snapshots + if row.get("month") == month + and row.get("traffic_bytes") is not None + ] + rows.append( + ( + account, + sum(storage) if storage else None, + sum(traffic) if traffic else None, + ) + ) + tasks = () + task_accounts = set(account.pk for account, _, _ in rows) + if page == "tasks": + tasks = ( + WebsiteScheduledJob.objects.filter(account_id__in=task_accounts) + .select_related("account") + .order_by("domain", "name")[:250] + ) return render( request, "hosting/system_workspace.html", { "title": title, - "accounts": accounts, + "section": page, + "rows": rows, + "tasks": tasks, + "month": month, + "page_obj": page_obj, + "is_paginated": pagination.num_pages > 1, "target": f"panel:{target}" if may_open else None, }, ) @@ -185,7 +238,7 @@ def groups_for(request, *, customer, manager): ("view_hostingaccount", "accounts", "Hosting accounts"), ("view_customer", "all_users", "Show All Users"), ("view_reseller", "resellers", "Managers"), - ("add_reseller", "reseller_create", "Add New Reseller"), + ("add_reseller", "reseller_create", "Add Manager"), ("view_hostingplan", "hosting_plans", "Hosting plans"), ): if user.has_perm(f"hosting.{permission}"): @@ -193,22 +246,42 @@ def groups_for(request, *, customer, manager): server, admin_tools = [], [] if user.has_perm("hosting.view_webprovisioningplan"): server.append(link("plans", "Web provisioning")) + if user.has_perm("hosting.view_hostingmaildomain") and user.has_perm( + "hosting.view_hostingaccount" + ): + admin_tools.append(link("mail_queue_index", "Mail Queue")) if user.has_perm("hosting.view_servicehealth"): admin_tools.append(link("service_health", "System Services")) if user.is_superuser: accounts.extend( ( link("operator_create", "Add New Operator"), - link("reseller_profiles", "Reseller Packages"), + link("reseller_profiles", "Manager Packages"), link("move_accounts", "Move Users"), ) ) server.extend( ( - link("feature_configuration", "Operator Settings"), + link("operator_settings", "Operator Settings", "general"), link("dns_defaults", "DNS Settings"), ) ) + if user.is_superuser: + admin_tools.extend( + ( + link("theme_management", "Themes"), + link("announcements", "Message"), + link("directadmin_guide", "Import"), + ) + ) + if user.is_superuser: + server.append(link("connected_nodes", "Connected Nodes")) + admin_tools.extend( + ( + link("operator_service_actions", "Service actions"), + link("database_monitor", "DB Monitor"), + ) + ) groups = [ ("Account Manager", accounts), ("Server Manager", server), diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index e7e9973..4f40fe4 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -167,10 +167,18 @@ class MailboxSigningRequest: def parse_mailbox_request(data): from .mail_policy import OPERATIONS, parse_mail_policy - from .mail_queue import MailQueueRequest + from .mail_queue import MailQueueAction, MailQueueRequest - if isinstance(data, dict) and data.get("operation") == "inspect_queue": + if isinstance(data, dict) and data.get("operation") in { + "inspect_queue", + "inspect_queue_entries", + }: return MailQueueRequest.from_manifest(data) + if ( + isinstance(data, dict) + and data.get("operation") == "change_queue_entry" + ): + return MailQueueAction.from_manifest(data) if isinstance(data, dict) and data.get("operation") in OPERATIONS: return parse_mail_policy(data) return parse_retirement( @@ -203,10 +211,17 @@ def mailbox_request_identity(spec): def apply_mailbox_request(request): from .mail_policy import MailRouting, MailVacation - from .mail_queue import MailQueueRequest, inspect_queue + from .mail_queue import ( + MailQueueAction, + MailQueueRequest, + change_queue_entry, + inspect_queue, + ) if isinstance(request, MailQueueRequest): return inspect_queue(request) + if isinstance(request, MailQueueAction): + return change_queue_entry(request) if isinstance(request, MailboxUsageRequest): return inspect_mailbox_usage(request.mailbox) if isinstance(request, MailRouting): diff --git a/src/coulobre/mail_queue.py b/src/coulobre/mail_queue.py index eafe1c5..e840f1f 100644 --- a/src/coulobre/mail_queue.py +++ b/src/coulobre/mail_queue.py @@ -1,35 +1,118 @@ import json +import re import subprocess from dataclasses import dataclass from .domain_names import canonical_domain MAX_QUEUE_ROWS = 20000 +QUEUE_ID = re.compile(r"[A-Za-z0-9]{5,32}") +QUEUE_ACTIONS = { + "flush": ("/usr/sbin/postqueue", "-i"), + "hold": ("/usr/sbin/postsuper", "-h"), + "release": ("/usr/sbin/postsuper", "-H"), +} QUEUE_NAMES = ("active", "deferred", "hold", "incoming", "maildrop") @dataclass(frozen=True) class MailQueueRequest: domain: str + detailed: bool = False def __post_init__(self): object.__setattr__(self, "domain", canonical_domain(self.domain)) def manifest(self): - return {"operation": "inspect_queue", "domain": self.domain} + operation = ( + "inspect_queue_entries" if self.detailed else "inspect_queue" + ) + return {"operation": operation, "domain": self.domain} @classmethod def from_manifest(cls, data): if data.keys() != {"operation", "domain"}: raise ValueError("Expected a mail queue request.") - return cls(data["domain"]) + return cls( + data["domain"], data["operation"] == "inspect_queue_entries" + ) -def summarize_queue(lines, domain): +@dataclass(frozen=True) +class MailQueueAction: + domain: str + queue_id: str + arrival: int + action: str + + def __post_init__(self): + object.__setattr__(self, "domain", canonical_domain(self.domain)) + if not isinstance(self.queue_id, str) or not QUEUE_ID.fullmatch( + self.queue_id + ): + raise ValueError("Choose a valid mail queue entry.") + if ( + self.action not in QUEUE_ACTIONS + or type(self.arrival) is not int + or not 0 < self.arrival < 2**53 + ): + raise ValueError("Choose an available queue action.") + + def manifest(self): + return { + "operation": "change_queue_entry", + "domain": self.domain, + "queue_id": self.queue_id, + "arrival": self.arrival, + "action": self.action, + } + + @classmethod + def from_manifest(cls, data): + if data.keys() != { + "operation", + "domain", + "queue_id", + "arrival", + "action", + }: + raise ValueError("Expected a mail queue action.") + return cls( + data["domain"], data["queue_id"], data["arrival"], data["action"] + ) + + +def visible_entry(message, domain): + recipients = [ + item["address"].rpartition("@")[2].lower() + for item in message["recipients"] + ] + queue_id = message.get("queue_id", "") + arrival = message.get("arrival_time") + if not recipients or any(item != domain for item in recipients): + return None + if ( + not QUEUE_ID.fullmatch(queue_id) + or type(arrival) is not int + or not 0 < arrival < 2**53 + ): + return None + return { + "queue_id": queue_id, + "arrival": arrival, + "queue": message["queue_name"], + } + + +def summarize_queue(lines, domain, *, detailed=False): counts = dict.fromkeys(QUEUE_NAMES, 0) + report = {"counts": counts, "partial": False} + if detailed: + report["entries"] = [] for index, line in enumerate(lines): if index == MAX_QUEUE_ROWS: - return {"counts": counts, "partial": True} + report["partial"] = True + return report if len(line) > 1024 * 1024: raise ValueError("Postfix returned an oversized queue entry.") message = json.loads(line) @@ -43,10 +126,22 @@ def summarize_queue(lines, domain): for address in addresses ): counts[queue] += 1 - return {"counts": counts, "partial": False} + if detailed and len(report["entries"]) < 100: + entry = visible_entry(message, domain) + if entry: + report["entries"].append(entry) + return report def inspect_queue(request): + return read_queue( + lambda lines: summarize_queue( + lines, request.domain, detailed=request.detailed + ) + ) + + +def read_queue(consume): with subprocess.Popen( ["/usr/sbin/postqueue", "-j"], stdin=subprocess.DEVNULL, @@ -56,7 +151,7 @@ def inspect_queue(request): ) as process: try: lines = iter(lambda: process.stdout.readline(1024 * 1024 + 1), b"") - result = summarize_queue(lines, request.domain) + result = consume(lines) if not result["partial"] and process.wait(timeout=5): raise ValueError("Postfix could not read the mail queue.") return result @@ -67,3 +162,44 @@ def inspect_queue(request): finally: if process.poll() is None: process.kill() + + +def change_queue_entry(request): + def find_entry(lines): + for index, line in enumerate(lines): + if index == MAX_QUEUE_ROWS or len(line) > 1024 * 1024: + break + message = json.loads(line) + if message.get("queue_id") == request.queue_id: + return { + "entry": visible_entry(message, request.domain), + "partial": True, + } + return {"entry": None, "partial": True} + + entry = read_queue(find_entry)["entry"] + if entry is None or entry["arrival"] != request.arrival: + raise ValueError("The queue entry changed or is outside this domain.") + expected = { + "flush": ("deferred",), + "hold": ("active", "deferred"), + "release": ("hold",), + } + if entry["queue"] not in expected[request.action]: + raise ValueError( + "This action is unavailable for the entry's current queue." + ) + try: + subprocess.run( + [*QUEUE_ACTIONS[request.action], request.queue_id], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + timeout=25, + env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"}, + ) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + raise ValueError( + "Postfix could not complete the queue action." + ) from error diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py new file mode 100644 index 0000000..ba6c196 --- /dev/null +++ b/src/coulobre/operator_node.py @@ -0,0 +1,180 @@ +import hashlib +import os +import re +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from .node_files import locked_root_directory +from .node_requests import serve_apply_request + +SOCKET = "/run/coulobre-operator-apply.sock" +STATE = Path("/var/lib/coulobre/operator") +SERVICES = { + "apache": "apache2.service", + "dns": "named.service", + "smtp": "postfix.service", + "imap": "dovecot.service", + "spam": "rspamd.service", +} +ACTIONS = ( + "package-preview", + "package-upgrade", + "reload", + "restart", + "database-report", +) +APT = "/usr/bin/apt-get" + + +@dataclass(frozen=True) +class OperatorRequest: + action: str + target: str = "" + plan: str = "" + + def __post_init__(self): + if self.action not in ACTIONS: + raise ValueError("Choose a supported operator action.") + if self.action in {"reload", "restart"}: + if self.target not in SERVICES: + raise ValueError("Choose a managed service.") + elif self.target: + raise ValueError("This operation does not use a service target.") + if self.action == "package-upgrade": + if not re.fullmatch(r"[a-f0-9]{64}", self.plan): + raise ValueError("Review the package plan before applying it.") + elif self.plan: + raise ValueError("This operation does not use a package plan.") + + @classmethod + def from_manifest(cls, payload): + if ( + not isinstance(payload, dict) + or payload.keys() != {"version", "action", "target", "plan"} + or type(payload["version"]) is not int + or payload["version"] != 1 + or any( + not isinstance(payload[key], str) + for key in ("action", "target", "plan") + ) + ): + raise ValueError("Expected an operator request.") + return cls(payload["action"], payload["target"], payload["plan"]) + + def manifest(self): + return { + "version": 1, + "action": self.action, + "target": self.target, + "plan": self.plan, + } + + +def command(*args, timeout=90): + try: + result = subprocess.run( + args, + stdin=subprocess.DEVNULL, + capture_output=True, + timeout=timeout, + check=False, + env={ + "PATH": "/usr/sbin:/usr/bin", + "LC_ALL": "C", + "DEBIAN_FRONTEND": "noninteractive", + }, + ) + except subprocess.TimeoutExpired: + raise ValueError( + "The host operation timed out. Review the service journal." + ) from None + if result.returncode: + raise ValueError( + "The host operation failed. Review the service journal." + ) + return result.stdout.decode("utf-8", errors="replace") + + +def apt_plan(): + output = command(APT, "--simulate", "--no-remove", "upgrade") + lines = [line for line in output.splitlines() if line.startswith("Inst ")] + digest = hashlib.sha256("\n".join(lines).encode()).hexdigest() + return { + "fingerprint": digest, + "packages": [line[:240] for line in lines[:90]], + "count": len(lines), + } + + +def packages(request): + with locked_root_directory(STATE): + if request.action == "package-preview": + command(APT, "update", timeout=180) + return apt_plan() + plan = apt_plan() + if request.plan != plan["fingerprint"]: + raise ValueError( + "The package plan changed. Collect and review a new preview." + ) + if plan["count"]: + command( + APT, + "-o", + "Dpkg::Options::=--force-confold", + "--yes", + "--no-remove", + "upgrade", + timeout=1500, + ) + report = apt_plan() + return {"upgrades_remaining": report["count"]} + + +def database_report(): + query = ( + "SELECT @@version, @@slow_query_log; SHOW GLOBAL STATUS WHERE " + "Variable_name IN ('Threads_connected','Slow_queries','Uptime');" + ) + output = command( + "/usr/bin/mariadb", + "--batch", + "--skip-column-names", + "--protocol=socket", + "--execute", + query, + ) + rows = [row.split("\t") for row in output.splitlines()] + if not rows or any(len(row) != 2 for row in rows): + raise ValueError("MariaDB returned an invalid status report.") + version, slow_log = rows[0] + counters = {key: value for key, value in rows[1:] if value.isdecimal()} + return { + "version": version[:80], + "slow_logging": slow_log == "1", + "counters": counters, + } + + +def apply_request(request): + if os.geteuid() != 0: + raise ValueError("Run operator actions as root on the host.") + if request.action.startswith("package-"): + if os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") != "1": + raise ValueError( + "Enable server package updates in the host configuration." + ) + return packages(request) + if request.action == "database-report": + return database_report() + with locked_root_directory(STATE): + service = SERVICES[request.target] + command("/usr/bin/systemctl", request.action, service) + command("/usr/bin/systemctl", "is-active", "--quiet", service) + return {"active": True} + + +def main(): + return serve_apply_request( + 1, OperatorRequest.from_manifest, apply_request, include_result=True + ) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index c38d540..cbd7dc7 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -111,6 +111,7 @@ TEMPLATES = [ "django.contrib.messages.context_processors.messages", "coulobre.hosting.access.panel_access", "coulobre.hosting.themes.panel_appearance", + "coulobre.hosting.panel_content.panel_announcements", ], }, },