From 5bddcd5512c38da6dec0575ad8273dff1d64e073 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:27:02 +0100 Subject: [PATCH] Complete operator and customer workflows for Coulobre 0.12 --- README.md | 2 +- deploy/panel_installer/engine.py | 9 + docs/deployment.md | 106 ++++-- docs/development.md | 40 +-- pyproject.toml | 3 +- src/coulobre/hosting/access.py | 18 +- .../hosting/account_administration.py | 17 + src/coulobre/hosting/account_metrics.py | 92 +++++ src/coulobre/hosting/admin.py | 3 +- src/coulobre/hosting/certificate_views.py | 91 ++++- src/coulobre/hosting/dns_forms.py | 2 +- src/coulobre/hosting/dns_topology_views.py | 106 ++++++ src/coulobre/hosting/domain_services.py | 54 ++- .../hosting/independent_website_views.py | 56 ++- src/coulobre/hosting/independent_websites.py | 46 ++- src/coulobre/hosting/mail_policies.py | 7 + src/coulobre/hosting/mail_policy_views.py | 66 +++- .../hosting/migrations/0074_system_backups.py | 82 +++++ .../0075_independent_php_settings.py | 44 +++ .../migrations/0076_http_template_changes.py | 17 + .../migrations/0077_acme_preferences.py | 17 + .../hosting/migrations/0078_manager_labels.py | 57 ++++ src/coulobre/hosting/models.py | 41 ++- src/coulobre/hosting/operator_backups.py | 175 ++++++++++ src/coulobre/hosting/operator_tools.py | 100 ++++++ src/coulobre/hosting/php_settings.py | 32 +- src/coulobre/hosting/reseller_accounts.py | 4 +- src/coulobre/hosting/reseller_onboarding.py | 23 ++ .../hosting/reseller_onboarding_views.py | 90 ++++- src/coulobre/hosting/reseller_profiles.py | 2 +- src/coulobre/hosting/reseller_views.py | 12 +- src/coulobre/hosting/resource_requests.py | 19 +- src/coulobre/hosting/system_backup_views.py | 123 +++++++ src/coulobre/hosting/tasks.py | 54 ++- .../templates/hosting/account_detail.html | 10 +- .../hosting/account_metrics_cells.html | 5 + .../hosting/templates/hosting/all_users.html | 8 +- .../hosting/customer_certificates.html | 6 +- .../templates/hosting/customer_list.html | 6 +- .../templates/hosting/dns_defaults_form.html | 4 + .../templates/hosting/dns_topology.html | 20 ++ .../templates/hosting/domain_workspace.html | 42 ++- .../templates/hosting/http_defaults.html | 27 ++ .../hosting/independent_websites.html | 3 +- .../templates/hosting/mail_policy_form.html | 6 +- .../templates/hosting/mailbox_form.html | 2 +- .../templates/hosting/operator_backups.html | 34 ++ .../hosting/operator_certificates.html | 12 + .../templates/hosting/reseller_detail.html | 4 +- .../hosting/site_php_settings_form.html | 4 +- .../templates/hosting/system_backup.html | 30 ++ .../templates/hosting/system_workspace.html | 6 +- .../hosting/workspace_navigation.html | 2 +- .../hosting/test_database_provisioning.py | 2 + src/coulobre/hosting/test_resellers.py | 4 +- src/coulobre/hosting/test_website_files.py | 2 + src/coulobre/hosting/test_website_jobs.py | 2 + src/coulobre/hosting/urls.py | 46 ++- src/coulobre/hosting/views.py | 79 ++++- src/coulobre/hosting/website_file_views.py | 10 +- src/coulobre/hosting/website_job_views.py | 10 +- src/coulobre/hosting/workspaces.py | 129 +++++-- src/coulobre/http_defaults.py | 150 ++++++++ src/coulobre/local_update.py | 3 + src/coulobre/mail_node_vacation.py | 32 +- src/coulobre/mail_policy.py | 37 +- src/coulobre/operator_node.py | 41 ++- src/coulobre/server_tls.py | 91 +++++ src/coulobre/settings.py | 9 + src/coulobre/system_backup.py | 322 ++++++++++++++++++ src/coulobre/web_certificates.py | 47 ++- src/coulobre/web_node_tls.py | 32 +- 72 files changed, 2674 insertions(+), 215 deletions(-) create mode 100644 src/coulobre/hosting/account_metrics.py create mode 100644 src/coulobre/hosting/dns_topology_views.py create mode 100644 src/coulobre/hosting/migrations/0074_system_backups.py create mode 100644 src/coulobre/hosting/migrations/0075_independent_php_settings.py create mode 100644 src/coulobre/hosting/migrations/0076_http_template_changes.py create mode 100644 src/coulobre/hosting/migrations/0077_acme_preferences.py create mode 100644 src/coulobre/hosting/migrations/0078_manager_labels.py create mode 100644 src/coulobre/hosting/operator_backups.py create mode 100644 src/coulobre/hosting/system_backup_views.py create mode 100644 src/coulobre/hosting/templates/hosting/account_metrics_cells.html create mode 100644 src/coulobre/hosting/templates/hosting/dns_topology.html create mode 100644 src/coulobre/hosting/templates/hosting/http_defaults.html create mode 100644 src/coulobre/hosting/templates/hosting/operator_backups.html create mode 100644 src/coulobre/hosting/templates/hosting/system_backup.html create mode 100644 src/coulobre/http_defaults.py create mode 100644 src/coulobre/server_tls.py create mode 100644 src/coulobre/system_backup.py diff --git a/README.md b/README.md index cf1b12d..01a32b1 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Coulobre Panel is an open-source web hosting control panel for hosting providers -and resellers. The project is in early development. +and managers. The project is in early development. The web panel gives operators a workspace to manage hosting accounts, request Apache configuration previews, and follow their progress. Administrators diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index dc8dbd0..1383d47 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -872,6 +872,15 @@ class Installer: HEALTH_TIMER, ): install_unit(unit) + workers.append( + install_worker( + "coulobre-operator", + "coulobre-operator", + "coulobre-operator-apply", + "coulobre-operator-worker.service", + ) + ) + workers.append("coulobre-operator-apply.socket") install_unit("coulobre-update.socket") install_unit("coulobre-update@.service") workers.append("coulobre-update.socket") diff --git a/docs/deployment.md b/docs/deployment.md index 36a3019..14daf48 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -275,7 +275,7 @@ service using its reachable address. ## Protect panel sign-in The HTTPS deployment requires a second factor for administrators, staff, -resellers, and other operator logins. Existing unverified privileged sessions +managers, and other operator logins. Existing unverified privileged sessions return to sign-in after the upgrade. Apply the database migrations before restarting the panel, worker, and scheduler. @@ -1067,7 +1067,7 @@ together before enabling additional sites. The file manager connects to the web node on the same server as the panel. It supports the document root of the primary site and each active -independent site. Customers and their assigned resellers can open **Files**. +independent site. Customers can open **Files** for their websites. Operators need both **Can view hosting account** and **Can manage website files**. File operations are unavailable through impersonation. @@ -1128,7 +1128,7 @@ If you lower a limit, the oldest enabled jobs retain their places until the account removes or pauses jobs. Add `website-jobs` to the local service health list if you monitor this worker from the panel. -Customers and their assigned resellers can open **Scheduled jobs** from the +Customers can open **Scheduled jobs** from the account page. Operators need both **Can view hosting account** and **Can manage scheduled website jobs**. Pick the primary or an active independent website. Use five cron fields in UTC. For example, `*/15 * * * *` runs every @@ -1943,7 +1943,7 @@ Each request captures the reviewed SOA serial and records. You can edit the zone while it publishes. Publish the newer revision after the current request finishes. Use **Retry publishing** if the current revision failed. -To let the customer and the assigned reseller edit a zone's records, enable +To let the customer edit a zone's records, enable **Delegate record editing** on that zone. They can also publish the zone when Coulobre publishing is enabled. The operator controls the authoritative nameservers, SOA responsible name, and automatic mail DNS setting. In @@ -2072,7 +2072,7 @@ automatic mail and repeat responses to the same sender within seven days. After changing either panel flag, run `panel_manage migrate --noinput`. Restart `coulobre-panel`, `coulobre-worker`, `coulobre-beat`, and -`coulobre-mailbox-provisioner`. Customers and resellers can manage the +`coulobre-mailbox-provisioner`. Customers can manage the settings for their own accounts. Operators need view permissions for the account and mailboxes and change permission for the mail domain or mailbox. @@ -2557,44 +2557,38 @@ changes, `COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1`. Set `coulobre-panel`. These flags route mailbox credential requests to the remote receiver, while databases still use the local credential service. -## Manage resellers +## Set up manager access -Open **Resellers** to add a reseller login or change an existing reseller's +Open **Managers** to add a manager login or change an existing manager's panel access, account limit, and allowed hosting plans. The detail page shows allocated accounts and audit history. Viewing account names and plan details requires the corresponding hosting account and hosting plan permissions. -The account limit and allowed plans apply when a reseller creates a hosting +The account limit and allowed plans apply when a manager creates a hosting account. Reducing the limit or removing a plan takes effect on the next self-service creation request. Existing accounts still count toward the limit and retain their assigned plans. Operators can assign and move accounts from the hosting account form. Use the audit history to review -changes to reseller policy and account assignments made through the panel. +changes to manager policy and account assignments made through the panel. -### Onboard customers and delegate provisioning +### Onboard customers -A reseller can open an unassigned hosting account in their own portfolio and -select **Add customer login**. Enter a new username and password, and add an -email address to support customer password recovery. Share the initial -credentials with the customer through a trusted channel. An existing -customer created by the same reseller can be added with **Link existing -customer**. The operator controls changes to existing assignments and to -customer sign-in status. The reseller's **Customers** page lists their own -logins. +Managers can open **My users** to create a customer login and its first +hosting account together. Choose an allowed hosting plan and give the +customer's email address to send a welcome email with a link to set their +password. Preview the email before creating the account. To add a login +for an existing unassigned hosting account, open the account and choose +**Add customer login** or **Link existing customer**. -Enable **Manage databases and mailboxes** on the reseller policy to let that -reseller request and provision both resources for their hosting accounts. -New requests use the account's existing database and mailbox limits and -mailbox storage quota. A deployment must enable the relevant provisioner -before the reseller can queue work. The panel shows provisioning status, -while service credentials and deployment manifests follow their existing -permissions. Both local and separate mail receivers use the same panel -permission. +Managers handle customer onboarding and hosting assignments in their +portfolio. Customers manage their own website files, databases, mailboxes, +and other hosting resources in the customer workspace. Operators can +move customers and their assigned active hosting accounts between +managers using the customer page, subject to the destination manager's +available plans and remaining account allowance. -The operator's reseller detail page records customer creation and linking, -resource requests, provisioning attempts queued or retried, and changes to -the reseller policy. Customer sign-in and operator support access use the -same workflows as operator-created accounts. +The operator's manager detail page records customer and account +assignments, policy changes, and historical provisioning activity. ## Suspend and resume hosting services @@ -2634,7 +2628,7 @@ pending service, backup, restore, and credential operations. Open **Retire accou website and aliases, certificate requests, SSH key fingerprints, databases, mailboxes, DNS zones, and backup archives. An operator with **Can retire hosting accounts** confirms the primary domain shown in the preview. -Retirement detaches the customer's and reseller's access to this hosting +Retirement detaches the customer's and manager's access to this hosting account. It stops the account's backup schedule and automatic archive expiry. - **Keep names reserved** leaves the suspended resources in place and keeps @@ -2838,7 +2832,7 @@ sudo systemctl enable --now coulobre-website-usage.socket Set `COULOBRE_WEBSITE_USAGE=1` in /etc/coulobre/panel.env, then restart coulobre-panel and coulobre-provisioner. Grant operators who troubleshoot -websites the **Can view website usage** permission. Customers and resellers +websites the **Can view website usage** permission. Customers and managers can see usage for their assigned accounts. ## Set up a managed secondary DNS server @@ -2959,3 +2953,51 @@ SQL export** to request a logical dump. Retrieve the latest completed export over the account's primary SFTP login from `/backups/database-.sql.gz`. The export includes one selected database. + +## Recover a dedicated Coulobre server + +Set `COULOBRE_SYSTEM_BACKUPS=1` in the operator worker's environment and +restart the workers and scheduler to enable manual and scheduled runs under +**Admin Tools → System Backup**. The server retains seven archives by default. +Set `COULOBRE_SYSTEM_BACKUP_KEEP` to a value from 1 to 30 to change retention. + +Each archive is written under `/var/lib/coulobre/system-backups` with root-only +permissions. It contains the local service configuration and hosting files +listed in the recovery manifest, the site's managed account data and a dump +of the dedicated server's MariaDB instance. Store the matching JSON record +alongside each archive. Protect any copies as carefully as the original +server credentials. Back up linked receivers separately on their hosts. + +Stage a selected archive outside the running services using the same +Coulobre release and MariaDB series. + +```bash +sudo /opt/coulobre/bin/coulobre-system-backup stage BACKUP_UUID +``` + +The command verifies the saved SHA-256 and creates a private staging +directory alongside the archive. The staging directory contains service +configuration, hosted files, the MariaDB dump and a list of symlinks and +hardlinks. Review the manifest and links before restoring them to a +dedicated replacement host. Reconcile recorded Coulobre user and group IDs +and file ownership before bringing mounted or hosted directories online. +The staging command leaves the running installation alone. + +On the replacement host, provision the matching service versions and keep +public listeners and writers stopped during the restore. Restore the +database into the replacement MariaDB instance using its local root socket. +Restore the reviewed service files and links from staging and validate +Apache, PHP-FPM, DNS and mail configuration before enabling their +listeners. Verify representative sites, mailboxes and backup restores +before changing production DNS. + +## Enable DNS-01 for wildcard website certificates + +An operator can make wildcard requests available by providing executable, +root-controlled Certbot authentication and cleanup hooks at +`/etc/coulobre/acme-dns/auth` and `/etc/coulobre/acme-dns/cleanup`. Configure +those hooks for the authoritative DNS provider. Set +`COULOBRE_ACME_DNS_01=1` in the panel environment to expose this choice under +**SSL Certificates → ACME settings**. Hostnames come from the selected +hosting account. Configure DNS authorization and renewal on the web node. +Ordinary website certificates use the installed HTTP-01 webroot. diff --git a/docs/development.md b/docs/development.md index c0e2f6d..eaf7fe1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -49,23 +49,24 @@ requests of that type. Changing the plan's storage limit applies to new mailbox requests. Use **Change storage limit** for an individual mailbox. [Change a mailbox storage limit](#change-a-mailbox-storage-limit) -## Give a reseller access to assigned accounts +## Give a manager access to assigned accounts -In `/admin/`, create a normal user and add a **Reseller** record for that user. -Then open a hosting account in Coulobre Panel and select the reseller when -editing the account. Existing accounts start with no reseller assigned. +In `/admin/`, create a normal user and add a **Manager** record for that user. +Then open a hosting account in Coulobre Panel and select the manager when +editing the account. Existing accounts start with no manager assigned. -The reseller can sign in to Coulobre Panel to see their assigned accounts, -each account's hosting plan, and its web provisioning previews. +Managers can sign in to Coulobre Panel to see their assigned hosting accounts +and plans. They can also onboard customers and assign an allowed hosting plan +to an existing account. -To let the reseller add accounts, set a positive account limit and select the -available hosting plans in the reseller's admin record. The reseller's account +To let the manager add accounts, set a positive account limit and select the +available hosting plans in the manager's admin record. The manager's account list shows their allowance. The limit applies to self-service creation, and -operator assignments also count toward the allowance. New reseller accounts -automatically belong to that reseller and require an allowed plan. A limit of -zero keeps the reseller's access read-only. +operator assignments also count toward the allowance. New hosting accounts +automatically belong to the manager and require an allowed plan. A limit of +zero blocks creation of additional hosting accounts. -Platform operators manage existing accounts, assignments, reseller allowances, +Platform operators manage existing accounts, assignments, manager allowances, and node deployment files. The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a @@ -74,12 +75,13 @@ different file. Keep `COULOBRE_DEBUG` for local development. ## Give a customer access to hosting accounts In Coulobre Panel, open **Customers** and select **Add customer**. Enter a -username and initial password. Select the customer when adding or editing a +username and email address to send a password setup link, or set an +initial password manually. Select the customer when adding or editing a hosting account. Repeat the assignment for each hosting account the customer should be able to access. To give an existing user customer access, add a **Customer** record for that user in `/admin/`. -The customer can sign in to Coulobre Panel with that username and password. +The customer signs in after setting or receiving their password. Their account list shows only the hosting accounts assigned to them. Each account page shows its hosting plan, database requests, DNS zones, and mailbox requests. Customers can request databases and mailboxes for their own accounts @@ -145,7 +147,7 @@ such as `wordpress`. The panel derives the full database name from the account ID and suffix, so two accounts can each request a database named `wordpress`. The account page shows the requested databases. Operators can download a -versioned deployment manifest containing the account ID and suffix. Resellers +versioned deployment manifest containing the account ID and suffix. Managers can view the requested database names on their own assigned accounts. The manifest describes the database to provision on a MariaDB node. @@ -279,7 +281,7 @@ for other records. The panel increments the SOA serial when the zone data changes. Changing the account's primary domain preserves its existing DNS zones. Select **Download manifest** in the DNS table and copy the file to the -hosting server or a separate DNS node. Resellers can see the configured +hosting server or a separate DNS node. Managers can see the configured domains and serials for their assigned accounts. Operators with the appropriate permissions can add and edit zones and download manifests. The panel exports version 2 for zones containing MX or TXT records and @@ -419,7 +421,7 @@ Existing mailbox requests keep their addresses when the primary domain changes. The **Mailbox requests** table shows the email addresses. Operators can download a versioned manifest that contains the domain and local part. -Resellers can see mailbox requests on their assigned accounts. +Managers can see mailbox requests on their assigned accounts. Version 2 adds `quota_mib` for mailboxes with a storage limit. Version 1 manifests continue to apply with no Coulobre storage limit. @@ -843,7 +845,7 @@ and registrar delegation for the operator. Create a separate hosting account or model aliases explicitly for additional web domains. Review mail forwarding, catch-all and vacation settings, custom IMAP keywords and subscriptions, webmail preferences, scheduled -tasks, reseller assignments, FTP users, certificates, source credentials, +tasks, manager assignments, FTP users, certificates, source credentials, and the system mailbox in a nested home archive. Reissue TLS certificates and rotate access using the provisioned Coulobre credentials. Verify the website, database rows, mailbox folders, and published zone before cutover. @@ -1073,7 +1075,7 @@ With local web activation enabled, an operator with **Can add site storage usage** can select **Measure website storage** on the hosting account. Reload the page to see the result and timestamp. The account shows the most recent successful result even if a later attempt fails. Customers and -resellers can see measurements on their assigned accounts. +managers can see measurements on their assigned accounts. ### Apply a website storage limit diff --git a/pyproject.toml b/pyproject.toml index e0f977b..07b1e91 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "coulobre-panel" -version = "0.11.1rc1" +version = "0.12.0rc1" description = "A web hosting control panel for hosting providers and resellers." readme = "README.md" requires-python = ">=3.12" @@ -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-system-backup = "coulobre.system_backup:main" coulobre-operator-node = "coulobre.operator_node:main" coulobre-node-setup = "coulobre.node_setup:main" coulobre-service-credentials = "coulobre.service_credentials:main" diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index f4ede66..16e8952 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -50,18 +50,31 @@ def can_manage_hosting(user, permissions): ) +def owns_customer_operations(user, account): + customer = customer_for_user(user) + if customer is not None: + return account.customer_id == customer.pk + return not is_tenant(user) and account.customer_id is None + + def panel_access(request): customer = customer_for_user(request.user) is not None reseller = not customer and reseller_for_user(request.user) is not None - from .workspaces import CUSTOMER_ACCOUNT, groups_for, workspace_accounts + from .workspaces import ( + CUSTOMER_ACCOUNT, + active_navigation, + groups_for, + workspace_accounts, + ) operator = request.user.is_authenticated and not (customer or reseller) groups = groups_for(request, customer=customer, manager=reseller) + active_link = active_navigation(request, customer=customer) current = next( ( label for label, links in groups - if any(url == request.path for url, _ in links) + if any(url == active_link for url, _ in links) ), "", ) @@ -82,6 +95,7 @@ def panel_access(request): "is_operator": operator, "navigation_groups": groups, "open_workspace_group": current, + "active_navigation_link": active_link, "workspace_accounts": available if len(available) > 1 else [], "workspace_selected": selected, } diff --git a/src/coulobre/hosting/account_administration.py b/src/coulobre/hosting/account_administration.py index 1c43830..7edbb66 100644 --- a/src/coulobre/hosting/account_administration.py +++ b/src/coulobre/hosting/account_administration.py @@ -19,6 +19,7 @@ from django.views.generic import FormView, ListView from coulobre.domain_names import canonical_domain from .access import OperatorOnlyMixin, reseller_for_user +from .account_metrics import customer_metrics from .account_setup import setup_new_account from .dns_defaults import zone_defaults from .installation_features import ( @@ -262,6 +263,22 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView): .order_by("username") ) + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + profiles = [ + getattr(user, "hosting_customer", None) + for user in context["logins"] + ] + measurements = customer_metrics( + [profile.pk for profile in profiles if profile], + operator=self.request.user, + ) + context["login_rows"] = [ + (login, measurements.get(profile.pk) if profile else None) + for login, profile in zip(context["logins"], profiles, strict=True) + ] + return context + class OperatorAuthorization(UserPassesTestMixin): def test_func(self): diff --git a/src/coulobre/hosting/account_metrics.py b/src/coulobre/hosting/account_metrics.py new file mode 100644 index 0000000..1f6ebab --- /dev/null +++ b/src/coulobre/hosting/account_metrics.py @@ -0,0 +1,92 @@ +from collections import defaultdict + +from django.db.models import Count +from django.utils import timezone + +from .models import ( + HostingAccount, + HostingDatabase, + HostingMailbox, + WebsiteDomain, + WebsiteUsage, +) + + +def account_metrics(accounts, *, databases=True, mailboxes=True): + accounts = list(accounts) + metrics = { + account.pk: { + "domains": 1, + "databases": 0 if databases else None, + "mailboxes": 0 if mailboxes else None, + "storage": None, + "traffic": None, + } + for account in accounts + } + if not metrics: + return metrics + counts = ( + (WebsiteDomain, "account_id", "domains", True), + (HostingDatabase, "account_id", "databases", databases), + (HostingMailbox, "mail_domain__account_id", "mailboxes", mailboxes), + ) + for model, field, key, enabled in counts: + if enabled: + for row in ( + model.objects.filter(**{f"{field}__in": metrics}) + .values(field) + .annotate(total=Count("pk")) + .order_by() + ): + metrics[row[field]][key] = row["total"] + month = timezone.now().strftime("%Y-%m") + for item in WebsiteUsage.objects.filter( + account_id__in=metrics, observed_at__isnull=False + ).values("account_id", "report"): + report = item["report"] + result = metrics[item["account_id"]] + if type(report.get("storage_bytes")) is int: + result["storage"] = (result["storage"] or 0) + report[ + "storage_bytes" + ] + if ( + report.get("month") == month + and type(report.get("traffic_bytes")) is int + ): + result["traffic"] = (result["traffic"] or 0) + report[ + "traffic_bytes" + ] + return metrics + + +def customer_metrics(customers, *, manager=None, operator=None): + accounts = HostingAccount.objects.filter( + retired_at__isnull=True, + customer_id__in=customers, + ) + if manager: + accounts = accounts.filter(reseller=manager) + if operator and not operator.has_perm("hosting.view_hostingaccount"): + return {} + accounts = list(accounts.only("id", "customer_id")) + measurements = account_metrics( + accounts, + databases=not operator + or operator.has_perm("hosting.view_hostingdatabase"), + mailboxes=not operator + or operator.has_perm("hosting.view_hostingmailbox"), + ) + rows = defaultdict(list) + for account in accounts: + rows[account.customer_id].append(measurements[account.pk]) + result = {} + for customer, values in rows.items(): + totals = {} + for key in ("domains", "databases", "mailboxes", "storage", "traffic"): + numbers = [ + value[key] for value in values if value[key] is not None + ] + totals[key] = sum(numbers) if numbers else None + result[customer] = totals + return result diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index ecc2877..8b6b134 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -79,10 +79,11 @@ class HostingPlanAdmin(admin.ModelAdmin): @admin.register(Reseller) class ResellerAdmin(admin.ModelAdmin): - list_display = ("user", "account_limit", "manage_resources") + list_display = ("user", "account_limit") list_select_related = ("user",) search_fields = ("user__username",) filter_horizontal = ("hosting_plans",) + exclude = ("manage_resources",) def get_exclude(self, request, obj=None): excluded = list(super().get_exclude(request, obj) or ()) diff --git a/src/coulobre/hosting/certificate_views.py b/src/coulobre/hosting/certificate_views.py index ed724c2..c9ccbf8 100644 --- a/src/coulobre/hosting/certificate_views.py +++ b/src/coulobre/hosting/certificate_views.py @@ -1,5 +1,7 @@ from datetime import timedelta +from pathlib import Path +from django import forms from django.conf import settings from django.core.exceptions import PermissionDenied, ValidationError from django.core.paginator import Paginator @@ -10,9 +12,10 @@ from django.urls import reverse from django.utils import timezone from django.views.decorators.cache import never_cache from django.views.decorators.debug import sensitive_variables -from django.views.decorators.http import require_http_methods, require_safe +from django.views.decorators.http import require_http_methods from coulobre.domain_names import canonical_domain +from coulobre.operator_node import SOCKET from coulobre.web_certificates import ACTIONS from coulobre.web_node import WebSite @@ -20,11 +23,31 @@ from .access import customer_for_user from .certificate_uploads import CertificateUploadForm, seal_upload from .independent_websites import active_websites from .installation_features import panel_feature_allowed -from .models import HostingAccount, WebsiteCertificateJob +from .models import HostingAccount, OperatorOperation, WebsiteCertificateJob from .resource_requests import lock_hosting_account, require_active_services from .sftp import site_is_active +class AcmePreferencesForm(forms.Form): + email = forms.EmailField( + required=False, + label="ACME registration contact", + max_length=254, + help_text="Leave blank to use the web node's existing registration.", + ) + wildcard = forms.BooleanField( + required=False, + label="Include a wildcard name", + help_text="Use the web node's configured DNS-01 hooks.", + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields[ + "wildcard" + ].disabled = not settings.WEBSITE_WILDCARD_CERTIFICATES + + def account_certificate_sites(account): sites = [ website.spec @@ -37,7 +60,14 @@ def account_certificate_sites(account): @transaction.atomic def queue_certificate( - account, site, actor, action, customer_id, *, encrypted_upload="" + account, + site, + actor, + action, + customer_id, + *, + encrypted_upload="", + acme=None, ): account = lock_hosting_account(account.pk, customer_id) require_active_services(account) @@ -46,13 +76,10 @@ def queue_certificate( recent = account.certificate_jobs.filter(site=site.manifest()) if recent.filter(finished_at__isnull=True).exists(): raise ValidationError("Wait for the current certificate operation.") - if ( - action == "reissue" - and recent.filter( - action=action, - requested_at__gte=timezone.now() - timedelta(hours=12), - ).exists() - ): + if (action == "reissue" or acme) and recent.filter( + action__in=("reissue", "issue"), + requested_at__gte=timezone.now() - timedelta(hours=12), + ).exists(): raise ValidationError( "Wait 12 hours before requesting another reissue." ) @@ -63,6 +90,7 @@ def queue_certificate( requested_customer_id=customer_id, action=action, encrypted_upload=encrypted_upload, + acme=acme or {}, ) @@ -100,7 +128,17 @@ def customer_certificates(request, pk): request.POST if is_upload else None, request.FILES if is_upload else None, ) - if request.method == "POST" and (not is_upload or upload_form.is_valid()): + is_acme = ( + request.method == "POST" + and tab == "acme" + and request.POST.get("action") in {"issue", "reissue"} + ) + acme_form = AcmePreferencesForm(request.POST if is_acme else None) + if ( + request.method == "POST" + and (not is_upload or upload_form.is_valid()) + and (not is_acme or acme_form.is_valid()) + ): if not site or not enabled: raise Http404 action = request.POST.get("action") @@ -119,6 +157,7 @@ def customer_certificates(request, pk): action, customer.pk, encrypted_upload=encrypted_upload, + acme=acme_form.cleaned_data if is_acme else None, ) except HostingAccount.DoesNotExist: raise Http404 from None @@ -151,6 +190,7 @@ def customer_certificates(request, pk): "tab": tab, "certificate": certificate, "upload_form": upload_form, + "acme_form": acme_form, "history": history, "enabled": enabled, "problem": problem, @@ -160,13 +200,35 @@ def customer_certificates(request, pk): @never_cache -@require_safe +@require_http_methods(("GET", "HEAD", "POST")) def operator_certificates(request): if not (request.user.is_superuser and request.user.is_verified()): raise PermissionDenied mode = request.GET.get("tab", "websites") if mode not in {"websites", "server"}: raise Http404 + latest = OperatorOperation.objects.filter(action="server-tls").order_by( + "-pk" + ) + if request.method == "POST": + if mode != "server" or not Path(SOCKET).is_socket(): + raise Http404 + from .tasks import run_operator_operation + + with transaction.atomic(): + type(request.user).objects.select_for_update().get( + pk=request.user.pk + ) + if not latest.filter(finished_at__isnull=True).exists(): + job = OperatorOperation.objects.create( + actor=request.user, action="server-tls" + ) + transaction.on_commit( + lambda: run_operator_operation.delay(job.pk) + ) + return redirect( + reverse("panel:operator_certificates", query={"tab": "server"}) + ) accounts = HostingAccount.objects.filter(retired_at__isnull=True).order_by( "primary_domain" ) @@ -196,6 +258,11 @@ def operator_certificates(request): "page_obj": page_obj, "is_paginated": page_obj.has_other_pages, "panel_origin": settings.PASSWORD_RESET_ORIGIN, + "tls_job": latest.first(), + "tls_available": Path(SOCKET).is_socket(), + "tls_result": latest.filter( + finished_at__isnull=False, problem="" + ).first(), "imap_host": settings.MAIL_IMAP_HOST, "submission_host": settings.MAIL_SUBMISSION_HOST, }, diff --git a/src/coulobre/hosting/dns_forms.py b/src/coulobre/hosting/dns_forms.py index d8a746a..fafcbd2 100644 --- a/src/coulobre/hosting/dns_forms.py +++ b/src/coulobre/hosting/dns_forms.py @@ -201,7 +201,7 @@ class DnsZoneForm(forms.Form): ) delegate_dns = forms.BooleanField( label="Delegate record editing", - help_text="Allow the customer and assigned reseller to edit records.", + help_text="Allow customers to edit this Coulobre-managed zone.", required=False, ) diff --git a/src/coulobre/hosting/dns_topology_views.py b/src/coulobre/hosting/dns_topology_views.py new file mode 100644 index 0000000..c73dd4a --- /dev/null +++ b/src/coulobre/hosting/dns_topology_views.py @@ -0,0 +1,106 @@ +from django import forms +from django.conf import settings +from django.core.exceptions import ValidationError +from django.http import Http404 +from django.shortcuts import redirect +from django.urls import reverse +from django.views.generic import FormView + +from .account_administration import OperatorAuthorization +from .domain_policies import policy_for +from .domain_services import ( + DomainServicesForm, + allowed_domains, + save_domain_policy, +) +from .models import HostingAccount +from .update_views import inspect_linked_nodes + + +class OperatorDomainServicesForm(DomainServicesForm): + account = forms.ModelChoiceField( + queryset=HostingAccount.objects.filter( + retired_at__isnull=True + ).order_by("primary_domain") + ) + domain = forms.CharField(max_length=253) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.order_fields(["account", "domain", "dns_managed", "mail_managed"]) + + def clean(self): + data = super().clean() + account = data.get("account") + domain = data.get("domain") + if account and domain: + from coulobre.domain_names import canonical_domain + + try: + domain = canonical_domain(domain) + except ValueError as error: + self.add_error("domain", str(error)) + else: + if domain not in allowed_domains(account): + self.add_error( + "domain", + "Choose a domain assigned to the hosting account.", + ) + data["domain"] = domain + return data + + +class DnsTopologyView(OperatorAuthorization, FormView): + form_class = OperatorDomainServicesForm + template_name = "hosting/dns_topology.html" + + def get_initial(self): + selected = self.request.GET.get("account") + domain = self.request.GET.get("domain") + if selected is None or domain is None: + return {} + if ( + not selected.isascii() + or not selected.isdecimal() + or len(selected) > 18 + ): + raise Http404 + account = HostingAccount.objects.filter( + pk=int(selected), retired_at__isnull=True + ).first() + if account is None or domain not in allowed_domains(account): + raise Http404 + policy = policy_for(account, domain) + return { + "account": account.pk, + "domain": domain, + "dns_managed": policy.dns_managed, + "mail_managed": policy.mail_managed, + } + + def get_context_data(self, **kwargs): + return super().get_context_data( + topology=inspect_linked_nodes(), + local_dns=settings.LOCAL_DNS_PUBLISHING, + local_mail=settings.LOCAL_MAILBOX_PROVISIONING, + **kwargs, + ) + + def form_valid(self, form): + data = form.cleaned_data + account = data["account"] + domain = data["domain"] + choices = {key: data[key] for key in ("dns_managed", "mail_managed")} + try: + save_domain_policy(account.pk, domain, None, choices) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect( + reverse( + "panel:dns_topology", + query={"account": account.pk, "domain": domain}, + ) + ) diff --git a/src/coulobre/hosting/domain_services.py b/src/coulobre/hosting/domain_services.py index f5b32b9..3104c1a 100644 --- a/src/coulobre/hosting/domain_services.py +++ b/src/coulobre/hosting/domain_services.py @@ -11,6 +11,8 @@ from django.views.decorators.http import require_http_methods from coulobre.domain_names import canonical_domain from .access import customer_for_user +from .account_setup import website_records +from .dns_defaults import zone_defaults from .dns_forms import zone_record_rows from .domain_policies import policy_for from .independent_websites import account_websites @@ -60,6 +62,8 @@ def allowed_domains(account): "domain", flat=True ) ) + domains.update(account.mail_domains.values_list("domain", flat=True)) + domains.update(account.dns_zones.values_list("domain", flat=True)) return sorted(domains) @@ -69,6 +73,19 @@ def save_domain_policy(account_id, domain, customer_id, choices): require_open_account(account) if domain not in allowed_domains(account): raise Http404 + previous = policy_for(account, domain) + if ( + previous.mail_managed + and not choices["mail_managed"] + and account.mail_domains.filter( + domain=domain, + mailboxes__provisioning__finished_at__isnull=False, + mailboxes__provisioning__problem="", + ).exists() + ): + raise ValidationError( + "Move the managed mailboxes before switching to external email." + ) DomainServicePolicy.objects.update_or_create( account=account, domain=domain, defaults=choices ) @@ -77,7 +94,16 @@ def save_domain_policy(account_id, domain, customer_id, 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"}: + if page not in { + "domains", + "dns", + "php", + "files", + "email", + "forwarders", + "replies", + "spam", + }: raise Http404 customer = customer_for_user(request.user) if customer is None: @@ -141,7 +167,7 @@ def domain_workspace(request, pk, page): ) mail_domain = ( account.mail_domains.filter(domain=domain).first() - if page in {"forwarders", "replies"} + if page in {"dns", "email", "forwarders", "replies", "spam"} else None ) titles = { @@ -149,9 +175,15 @@ def domain_workspace(request, pk, page): "dns": "DNS Editor", "php": "PHP Settings", "files": "File Manager", + "email": "Email Accounts", + "spam": "Spam protection", "forwarders": "Forwarders", "replies": "Automatic replies", } + from .mail_policies import mail_policy_available + from .roundcube import roundcube_available + + defaults = zone_defaults() if page == "dns" else None return render( request, "hosting/domain_workspace.html", @@ -165,7 +197,25 @@ def domain_workspace(request, pk, page): "policy": policy, "zone": zone, "records": zone_record_rows(zone.spec) if zone else (), + "external_website_records": website_records( + domain, + www=defaults.include_www, + wildcard=defaults.include_wildcard, + addresses=defaults.addresses, + ) + if page == "dns" and not policy.dns_managed + else (), + "zone_defaults": defaults, "mail_domain": mail_domain, + "mail_enabled": panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" + ), + "can_edit_routing": mail_policy_available("routing"), + "can_edit_mailbox": mail_policy_available("vacation"), + "roundcube_enabled": roundcube_available(request), + "mailboxes": mail_domain.mailboxes.select_related("provisioning") + if mail_domain + else (), "website": website, "primary": primary, "can_add_site": panel_feature_allowed("LOCAL_WEB_ACTIVATION"), diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py index fa2c27d..8ef14be 100644 --- a/src/coulobre/hosting/independent_website_views.py +++ b/src/coulobre/hosting/independent_website_views.py @@ -21,6 +21,11 @@ from .independent_websites import ( ) from .installation_features import panel_feature_allowed from .models import HostingAccount, IndependentWebsite, WebsiteDomain +from .php_settings import ( + SitePhpSettingsForm, + plan_php_settings, + settings_from_form, +) class WebsiteCreateForm(forms.Form): @@ -136,8 +141,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor): operation = Operation(self.kwargs["operation"]) except ValueError: raise Http404 from None - if operation == Operation.HTTPS and not panel_feature_allowed( - "LOCAL_WEB_HTTPS" + if operation == Operation.SETTINGS or ( + operation == Operation.HTTPS + and not panel_feature_allowed("LOCAL_WEB_HTTPS") ): raise Http404 return operation @@ -187,6 +193,52 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor): return redirect(self.account) +class IndependentWebsitePhpSettings(IndependentWebsiteEditor): + form_class = SitePhpSettingsForm + template_name = "hosting/site_php_settings_form.html" + + @cached_property + def website(self): + return get_object_or_404( + account_websites(self.account), + pk=self.kwargs["site_pk"], + activated=True, + retired_at__isnull=True, + ) + + def get_initial(self): + return ( + self.website.applied_php_settings + or plan_php_settings(self.account).manifest() + ) + + def get_context_data(self, **kwargs): + return super().get_context_data( + site_domain=self.website.reservation.domain, + plan_settings=plan_php_settings(self.account), + **kwargs, + ) + + def form_valid(self, form): + try: + queue_website_operation( + self.account.pk, + self.website.pk, + Operation.SETTINGS, + "", + self.request.user, + php_settings=None + if form.cleaned_data["use_plan"] + else settings_from_form(form.cleaned_data), + ) + except (HostingAccount.DoesNotExist, IndependentWebsite.DoesNotExist): + raise Http404 from None + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.account) + + class IndependentWebsiteManifest( OperatorOnlyMixin, PermissionRequiredMixin, View ): diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py index e142f86..1945175 100644 --- a/src/coulobre/hosting/independent_websites.py +++ b/src/coulobre/hosting/independent_websites.py @@ -16,8 +16,10 @@ from .node_client import ( apply_on_local_node, enable_local_https, set_local_site_storage_limit, + update_local_php_settings, update_local_php_version, ) +from .php_settings import limit_customer_php_settings, plan_php_settings from .resource_requests import lock_hosting_account, require_active_services Operation = IndependentWebsite.Operation @@ -54,7 +56,7 @@ def website_actions(website): return (Operation.ACTIVATE, Operation.RETIRE) if website.suspended: return (Operation.RESUME, Operation.RETIRE) - actions = (Operation.PHP, Operation.SUSPEND) + actions = (Operation.PHP, Operation.SETTINGS, Operation.SUSPEND) if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled: actions += (Operation.HTTPS,) return actions @@ -101,7 +103,15 @@ def create_website(account_id, domain, version, actor): @transaction.atomic -def queue_website_operation(account_id, site_id, operation, version, actor): +def queue_website_operation( + account_id, + site_id, + operation, + version, + actor, + *, + php_settings=None, +): account = lock_hosting_account(account_id, customer_id=None) check_actor(account, actor) require_active_services(account) @@ -127,9 +137,19 @@ def queue_website_operation(account_id, site_id, operation, version, actor): ).exists() ): raise ValidationError("Wait for the backup or restore to finish.") + customer = customer_for_user(actor) + if operation == Operation.SETTINGS: + if php_settings is None: + php_settings = plan_php_settings(account) + elif customer is not None: + php_settings = limit_customer_php_settings(account, php_settings) IndependentWebsite.objects.requeue( IndependentWebsite.objects.filter(pk=website.pk), operation=operation, + requested_customer_id=customer.pk if customer else None, + requested_php_settings=php_settings.manifest() + if php_settings + else None, requested_php_version=( version if operation in (Operation.ACTIVATE, Operation.PHP) @@ -143,6 +163,10 @@ def apply_website_operation(website): site = website.spec operation = website.operation account = website.reservation.account + if website.requested_customer_id is not None and ( + account.customer_id != website.requested_customer_id + ): + raise ValueError("The hosting account's customer assignment changed.") try: require_active_services(account) except ValidationError as error: @@ -156,7 +180,7 @@ def apply_website_operation(website): raise ValueError(" ".join(error.messages)) from None if operation == Operation.ACTIVATE: plan = account.hosting_plan - _, version = activate_local_site( + options, version = activate_local_site( site, plan.get_php_settings() if plan else PhpPoolSettings(), (requested,) if requested else allowed_versions(account), @@ -167,10 +191,26 @@ def apply_website_operation(website): return { "activated": True, "php_version": version, + "applied_php_settings": options.manifest() + if isinstance(options, PhpPoolSettings) + else None, "storage_limit_mib": limit, } if operation == Operation.PHP: return {"php_version": update_local_php_version(site, requested)} + if operation == Operation.SETTINGS: + requested_settings = PhpPoolSettings.from_manifest( + website.requested_php_settings + ) + if website.requested_customer_id is not None: + try: + requested_settings = limit_customer_php_settings( + account, requested_settings + ) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + applied = update_local_php_settings(site, requested_settings) + return {"applied_php_settings": applied.manifest()} if operation == Operation.HTTPS: if not settings.LOCAL_WEB_HTTPS: raise ValueError("Enable the website HTTPS worker first.") diff --git a/src/coulobre/hosting/mail_policies.py b/src/coulobre/hosting/mail_policies.py index 39f5e22..88e6533 100644 --- a/src/coulobre/hosting/mail_policies.py +++ b/src/coulobre/hosting/mail_policies.py @@ -5,6 +5,7 @@ from django.db import transaction from coulobre.mail_policy import MailRouting, parse_mail_policy from .access import is_tenant, manages_account +from .domain_policies import require_managed from .models import HostingMailDomain from .node_client import apply_on_local_node from .resource_requests import lock_hosting_account, require_active_services @@ -24,6 +25,12 @@ def policy_account(resource): def validate_policy(resource, spec, account): require_active_services(account) + domain = ( + resource.domain + if isinstance(resource, HostingMailDomain) + else resource.mail_domain.domain + ) + require_managed(account, domain, "mail_managed") if isinstance(spec, MailRouting): validate_routing(resource, spec, account.hosting_plan) else: diff --git a/src/coulobre/hosting/mail_policy_views.py b/src/coulobre/hosting/mail_policy_views.py index 2e8c29b..46b6dd3 100644 --- a/src/coulobre/hosting/mail_policy_views.py +++ b/src/coulobre/hosting/mail_policy_views.py @@ -1,8 +1,9 @@ +from dataclasses import replace from datetime import UTC from django import forms from django.contrib.auth.mixins import PermissionRequiredMixin -from django.core.exceptions import ValidationError +from django.core.exceptions import PermissionDenied, ValidationError from django.http import Http404 from django.shortcuts import redirect from django.utils import timezone @@ -19,7 +20,12 @@ from coulobre.mail_policy import ( parse_mail_policy, ) -from .access import TenantScopeMixin, can_manage_hosting, reseller_for_user +from .access import ( + TenantScopeMixin, + can_manage_hosting, + owns_customer_operations, + reseller_for_user, +) from .mail_policies import ( mail_policy_available, policy_account, @@ -57,9 +63,10 @@ def mail_policy_enabled(request, kind): class MailPolicyForm(forms.Form): revision = forms.CharField(required=False, widget=forms.HiddenInput) - def __init__(self, *args, resource, **kwargs): + def __init__(self, *args, resource, policy=None, **kwargs): super().__init__(*args, **kwargs) self.resource = resource + self.policy = policy def clean(self): cleaned = super().clean() @@ -162,10 +169,38 @@ class MailVacationForm(MailPolicyForm): return MailVacation( self.resource.spec, repeat_days=cleaned.get("repeat_days") or DEFAULT_REPEAT_DAYS, + move_spam=self.policy.move_spam if self.policy else False, + junk_senders=self.policy.junk_senders if self.policy else (), **values, ) +class MailSpamForm(MailPolicyForm): + move_spam = forms.BooleanField( + required=False, label="Move messages tagged as spam to Junk" + ) + junk_senders = forms.CharField( + required=False, + max_length=5500, + label="Senders to move to Junk", + help_text="Enter up to 20 full sender addresses, one per line.", + widget=forms.Textarea(attrs={"rows": 5}), + ) + + def make_spec(self, cleaned): + policy = self.policy or MailVacation(self.resource.spec, enabled=False) + senders = tuple( + line.strip() + for line in cleaned["junk_senders"].splitlines() + if line.strip() + ) + return replace( + policy, + move_spam=cleaned["move_spam"], + junk_senders=senders, + ) + + @method_decorator(never_cache, name="dispatch") class MailPolicyEditor( TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView @@ -195,10 +230,19 @@ class MailPolicyEditor( if not mail_policy_available(self.kind): raise Http404 self.object = self.get_object() + if not owns_customer_operations( + self.request.user, policy_account(self.object) + ): + raise PermissionDenied self.job = getattr(self.object, self.kind, None) def get_form_kwargs(self): - return super().get_form_kwargs() | {"resource": self.object} + return super().get_form_kwargs() | { + "resource": self.object, + "policy": parse_mail_policy(self.job.manifest) + if self.job + else None, + } def get_initial(self): initial = {"revision": policy_revision(self.job)} @@ -277,3 +321,17 @@ class MailVacationEditor(MailPolicyEditor): kind = "vacation" target = "mailbox" title = "Automatic replies" + + +class MailSpamEditor(MailVacationEditor): + form_class = MailSpamForm + title = "Spam protection" + extra_context = {"spam_editor": True} + + def get_initial(self): + initial = super().get_initial() + if self.job: + spec = parse_mail_policy(self.job.manifest) + initial["move_spam"] = spec.move_spam + initial["junk_senders"] = "\n".join(spec.junk_senders) + return initial diff --git a/src/coulobre/hosting/migrations/0074_system_backups.py b/src/coulobre/hosting/migrations/0074_system_backups.py new file mode 100644 index 0000000..16c6120 --- /dev/null +++ b/src/coulobre/hosting/migrations/0074_system_backups.py @@ -0,0 +1,82 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:08 + +import uuid + +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", "0073_folder_sftp_login"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="SystemBackupSchedule", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("enabled", models.BooleanField(default=False)), + ("time", models.TimeField(null=True)), + ("next_run_at", models.DateTimeField(null=True)), + ], + ), + migrations.CreateModel( + name="SystemBackupJob", + 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)), + ( + "identifier", + models.UUIDField( + default=uuid.uuid4, editable=False, unique=True + ), + ), + ( + "scheduled_for", + models.DateTimeField(null=True, unique=True), + ), + ("report", models.JSONField(default=dict)), + ( + "actor", + models.ForeignKey( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/migrations/0075_independent_php_settings.py b/src/coulobre/hosting/migrations/0075_independent_php_settings.py new file mode 100644 index 0000000..8904596 --- /dev/null +++ b/src/coulobre/hosting/migrations/0075_independent_php_settings.py @@ -0,0 +1,44 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:09 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0074_system_backups"), + ] + + operations = [ + migrations.AddField( + model_name="independentwebsite", + name="applied_php_settings", + field=models.JSONField(blank=True, null=True), + ), + migrations.AddField( + model_name="independentwebsite", + name="requested_customer_id", + field=models.PositiveBigIntegerField(blank=True, null=True), + ), + migrations.AddField( + model_name="independentwebsite", + name="requested_php_settings", + field=models.JSONField(blank=True, null=True), + ), + migrations.AlterField( + model_name="independentwebsite", + name="operation", + field=models.CharField( + choices=[ + ("activate", "Provision website"), + ("php", "Change PHP series"), + ("settings", "Change PHP settings"), + ("https", "Enable HTTPS"), + ("suspend", "Suspend website"), + ("resume", "Resume website"), + ("retire", "Retire website"), + ], + default="activate", + max_length=8, + ), + ), + ] diff --git a/src/coulobre/hosting/migrations/0076_http_template_changes.py b/src/coulobre/hosting/migrations/0076_http_template_changes.py new file mode 100644 index 0000000..598b6ab --- /dev/null +++ b/src/coulobre/hosting/migrations/0076_http_template_changes.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:12 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0075_independent_php_settings"), + ] + + operations = [ + migrations.AddField( + model_name="operatoroperation", + name="parameters", + field=models.JSONField(default=dict), + ), + ] diff --git a/src/coulobre/hosting/migrations/0077_acme_preferences.py b/src/coulobre/hosting/migrations/0077_acme_preferences.py new file mode 100644 index 0000000..6387f37 --- /dev/null +++ b/src/coulobre/hosting/migrations/0077_acme_preferences.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0076_http_template_changes"), + ] + + operations = [ + migrations.AddField( + model_name="websitecertificatejob", + name="acme", + field=models.JSONField(default=dict), + ), + ] diff --git a/src/coulobre/hosting/migrations/0078_manager_labels.py b/src/coulobre/hosting/migrations/0078_manager_labels.py new file mode 100644 index 0000000..d6bafe7 --- /dev/null +++ b/src/coulobre/hosting/migrations/0078_manager_labels.py @@ -0,0 +1,57 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:24 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0077_acme_preferences"), + ] + + operations = [ + migrations.AlterModelOptions( + name="reseller", + options={ + "verbose_name": "manager", + "verbose_name_plural": "managers", + }, + ), + migrations.AlterModelOptions( + name="resellerprofile", + options={ + "ordering": ("name",), + "verbose_name": "manager profile", + "verbose_name_plural": "manager profiles", + }, + ), + migrations.AlterField( + model_name="hostingaccount", + name="reseller", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.PROTECT, + to="hosting.reseller", + verbose_name="manager", + ), + ), + migrations.AlterField( + model_name="resellerauditevent", + name="action", + field=models.CharField( + choices=[ + ("create", "Created manager"), + ("update", "Updated manager"), + ("assign", "Assigned hosting account"), + ("unassign", "Unassigned hosting account"), + ("plan", "Changed hosting account plan"), + ("cust_add", "Created customer login"), + ("cust_lnk", "Linked customer login"), + ("request", "Requested hosting resource"), + ("deploy", "Queued resource provisioning"), + ], + max_length=8, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index ec65b8d..77a99ce 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -64,6 +64,10 @@ class Reseller(models.Model): ) hosting_plans = models.ManyToManyField("HostingPlan", blank=True) + class Meta: + verbose_name = "manager" + verbose_name_plural = "managers" + def __str__(self): return self.user.get_username() @@ -85,6 +89,8 @@ class ResellerProfile(models.Model): class Meta: ordering = ("name",) + verbose_name = "manager profile" + verbose_name_plural = "manager profiles" def __str__(self): return self.name @@ -99,8 +105,8 @@ class ResellerProfile(models.Model): class ResellerAuditEvent(models.Model): class Action(models.TextChoices): - CREATE = "create", "Created reseller" - UPDATE = "update", "Updated reseller" + CREATE = "create", "Created manager" + UPDATE = "update", "Updated manager" ASSIGN = "assign", "Assigned hosting account" UNASSIGN = "unassign", "Unassigned hosting account" PLAN = "plan", "Changed hosting account plan" @@ -432,7 +438,11 @@ class HostingAccount(models.Model): HostingPlan, on_delete=models.PROTECT, null=True, blank=True ) reseller = models.ForeignKey( - Reseller, on_delete=models.PROTECT, null=True, blank=True + Reseller, + on_delete=models.PROTECT, + null=True, + blank=True, + verbose_name="manager", ) customer = models.ForeignKey( Customer, on_delete=models.PROTECT, null=True, blank=True @@ -886,6 +896,23 @@ class DatabaseLogin(ProvisioningJob): return DatabaseLoginSpec(self.database.spec, self.pk) +class SystemBackupJob(ProvisioningJob): + identifier = models.UUIDField( + default=uuid.uuid4, unique=True, editable=False + ) + actor = models.ForeignKey( + settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL + ) + scheduled_for = models.DateTimeField(unique=True, null=True) + report = models.JSONField(default=dict) + + +class SystemBackupSchedule(models.Model): + enabled = models.BooleanField(default=False) + time = models.TimeField(null=True) + next_run_at = models.DateTimeField(null=True) + + class OperatorOperation(ProvisioningJob): actor = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True @@ -896,6 +923,7 @@ class OperatorOperation(ProvisioningJob): source = models.OneToOneField( "self", on_delete=models.SET_NULL, null=True, blank=True ) + parameters = models.JSONField(default=dict) result = models.JSONField(default=dict) @@ -1091,6 +1119,7 @@ class WebsiteCertificateJob(ProvisioningJob): null=True, ) requested_customer_id = models.PositiveBigIntegerField(null=True) + acme = models.JSONField(default=dict) encrypted_upload = models.TextField(blank=True, default="") certificate = models.JSONField(default=dict) @@ -1147,6 +1176,7 @@ class IndependentWebsite(ProvisioningJob): class Operation(models.TextChoices): ACTIVATE = "activate", "Provision website" PHP = "php", "Change PHP series" + SETTINGS = "settings", "Change PHP settings" HTTPS = "https", "Enable HTTPS" SUSPEND = "suspend", "Suspend website" RESUME = "resume", "Resume website" @@ -1165,6 +1195,11 @@ class IndependentWebsite(ProvisioningJob): requested_php_version = models.CharField(max_length=5, blank=True) php_version = models.CharField(max_length=5, blank=True) storage_limit_mib = models.PositiveIntegerField(null=True, blank=True) + requested_php_settings = models.JSONField(null=True, blank=True) + applied_php_settings = models.JSONField(null=True, blank=True) + requested_customer_id = models.PositiveBigIntegerField( + null=True, blank=True + ) retirement_id = models.UUIDField(default=uuid.uuid4, editable=False) class Meta: diff --git a/src/coulobre/hosting/operator_backups.py b/src/coulobre/hosting/operator_backups.py new file mode 100644 index 0000000..e887f20 --- /dev/null +++ b/src/coulobre/hosting/operator_backups.py @@ -0,0 +1,175 @@ +from django import forms +from django.contrib import messages +from django.contrib.admin.models import CHANGE, LogEntry +from django.core.exceptions import ValidationError +from django.core.paginator import Paginator +from django.db import transaction +from django.db.models import OuterRef, Subquery +from django.http import Http404 +from django.shortcuts import redirect +from django.urls import reverse +from django.views.generic import FormView + +from .account_administration import OperatorAuthorization +from .account_backups import ( + mail_backups_enabled, + queue_account_backup, + save_backup_schedule, +) +from .installation_features import panel_feature_allowed +from .models import ( + AccountBackupJob, + AccountBackupSchedule, + HostingAccount, + Reseller, +) +from .resource_requests import lock_hosting_account + + +class GroupBackupForm(forms.Form): + manager = forms.ModelChoiceField( + queryset=Reseller.objects.select_related("user") + ) + action = forms.ChoiceField( + choices=[ + ("run", "Run backups now"), + ("schedule", "Set a daily schedule"), + ] + ) + include_mailboxes = forms.BooleanField(required=False) + time = forms.TimeField( + required=False, + label="Daily time (UTC)", + input_formats=["%H:%M"], + widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}), + ) + confirmed = forms.BooleanField( + label="Apply to every active hosting account assigned to this manager" + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["include_mailboxes"].disabled = not mail_backups_enabled() + + def clean(self): + data = super().clean() + if data.get("action") == "schedule" and not data.get("time"): + self.add_error("time", "Choose a daily start time.") + return data + + +class OperatorBackupsView(OperatorAuthorization, FormView): + form_class = GroupBackupForm + template_name = "hosting/operator_backups.html" + + def selected_manager(self): + return self.request.GET.get("manager", "") + + def accounts(self): + scope = HostingAccount.objects.filter(retired_at__isnull=True) + manager = self.selected_manager() + if manager: + if ( + not manager.isascii() + or not manager.isdecimal() + or len(manager) > 18 + ): + raise Http404 + scope = scope.filter(reseller_id=int(manager)) + return scope + + def get_initial(self): + return {"manager": self.selected_manager()} + + def get_context_data(self, **kwargs): + latest = AccountBackupJob.objects.filter( + account_id=OuterRef("pk") + ).order_by("-pk") + accounts = ( + self.accounts() + .select_related("reseller__user", "backup_schedule") + .annotate( + last_backup=Subquery(latest.values("requested_at")[:1]), + last_completed=Subquery(latest.values("finished_at")[:1]), + last_problem=Subquery(latest.values("problem")[:1]), + ) + .order_by("primary_domain") + ) + page = Paginator(accounts, 30).get_page(self.request.GET.get("page")) + return super().get_context_data( + accounts=page.object_list, + page_obj=page, + is_paginated=page.has_other_pages(), + managers=Reseller.objects.select_related("user").order_by( + "user__username" + ), + selected_manager=self.selected_manager(), + enabled=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"), + **kwargs, + ) + + def form_valid(self, form): + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): + raise Http404 + data = form.cleaned_data + manager = data["manager"] + accounts = ( + HostingAccount.objects.filter( + reseller=manager, retired_at__isnull=True + ) + .order_by("pk") + .values_list("pk", flat=True) + ) + successes = skipped = 0 + for pk in list(accounts): + try: + if apply_group_backup(pk, manager.pk, data): + successes += 1 + else: + skipped += 1 + except (HostingAccount.DoesNotExist, ValidationError): + skipped += 1 + LogEntry.objects.log_actions( + self.request.user.pk, + [manager], + CHANGE, + f"Backup {data['action']}: {successes} accepted, " + f"{skipped} skipped.", + ) + messages.success( + self.request, + f"{successes} accounts accepted. {skipped} skipped.", + ) + return redirect( + reverse("panel:operator_backups", query={"manager": manager.pk}) + ) + + +@transaction.atomic +def apply_group_backup(account_id, manager_id, data): + account = lock_hosting_account(account_id, customer_id=None) + if account.reseller_id != manager_id or account.retired_at is not None: + return False + if data["action"] == "run": + return ( + queue_account_backup( + account.pk, include_mailboxes=data["include_mailboxes"] + ) + is not None + ) + existing = getattr(account, "backup_schedule", None) + save_backup_schedule( + account.pk, + can_manage_mail=True, + schedule_fields={ + "enabled": True, + "frequency": AccountBackupSchedule.Frequency.DAILY, + "weekday": None, + "time": data["time"], + "include_mailboxes": data["include_mailboxes"], + "offsite_destination": existing.offsite_destination + if existing + else "", + }, + ) + return True diff --git a/src/coulobre/hosting/operator_tools.py b/src/coulobre/hosting/operator_tools.py index 9d2adf1..78e5f47 100644 --- a/src/coulobre/hosting/operator_tools.py +++ b/src/coulobre/hosting/operator_tools.py @@ -164,3 +164,103 @@ class ConnectedNodesView(OperatorAuthorization, TemplateView): return super().get_context_data( topology=inspect_linked_nodes(), **kwargs ) + + +class HttpDefaultsForm(forms.Form): + def __init__(self, *args, target, **kwargs): + from coulobre.http_defaults import CONTROLS + + super().__init__(*args, **kwargs) + self.target = target + for key, (label, minimum, maximum, default) in CONTROLS[ + target + ].items(): + self.fields[key] = forms.IntegerField( + label=label, + min_value=minimum, + max_value=maximum, + initial=default, + ) + + def clean(self): + from coulobre.http_defaults import HttpDefaultsRequest + + values = super().clean() + if not self.errors: + try: + self.requested = HttpDefaultsRequest(self.target, values) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + return values + + +class HttpDefaultsView(OperatorAuthorization, FormView): + form_class = HttpDefaultsForm + template_name = "hosting/http_defaults.html" + + def target(self): + from django.http import Http404 + + target = self.kwargs["target"] + if target not in ("apache", "php"): + raise Http404 + return target + + def history(self): + return OperatorOperation.objects.filter( + action="http-defaults", target=self.target() + ).order_by("-pk") + + def get_initial(self): + latest = ( + self.history() + .filter(finished_at__isnull=False, problem="") + .first() + ) + return latest.parameters if latest else {} + + def get_form_kwargs(self): + return super().get_form_kwargs() | {"target": self.target()} + + def get_context_data(self, **kwargs): + return super().get_context_data( + target=self.target(), + available=Path(SOCKET).is_socket(), + jobs=self.history()[:10], + **kwargs, + ) + + def form_valid(self, form): + spec = form.requested + manifest = spec.manifest() + if self.request.POST.get("action") != "apply": + self.request.session["http_template_preview"] = manifest + return self.render_to_response( + self.get_context_data( + form=form, + preview=spec.render(), + ) + ) + if not Path(SOCKET).is_socket(): + form.add_error(None, "Start the local operator worker.") + return self.form_invalid(form) + if self.request.session.pop("http_template_preview", None) != manifest: + form.add_error( + None, "Review the exact template before applying it." + ) + return self.form_invalid(form) + with transaction.atomic(): + locked = type(self.request.user).objects.select_for_update() + locked.get(pk=self.request.user.pk) + if self.history().filter(finished_at__isnull=True).exists(): + form.add_error(None, "Wait for the current template change.") + return self.form_invalid(form) + job = OperatorOperation.objects.create( + actor=self.request.user, + action="http-defaults", + target=self.target(), + parameters=spec.values, + ) + transaction.on_commit(lambda: run_operator_operation.delay(job.pk)) + messages.success(self.request, "HTTP template change queued.") + return redirect(self.request.path) diff --git a/src/coulobre/hosting/php_settings.py b/src/coulobre/hosting/php_settings.py index 77802dc..0918e46 100644 --- a/src/coulobre/hosting/php_settings.py +++ b/src/coulobre/hosting/php_settings.py @@ -109,6 +109,23 @@ def plan_php_versions(account): return plan.allowed_php_versions() if plan is not None else () +def limit_customer_php_settings(account, requested): + limits = plan_php_settings(account).manifest() + values = requested.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: + return PhpPoolSettings.from_manifest(values) + except PhpPoolSettingsError as error: + raise ValidationError(str(error)) from error + + @transaction.atomic def queue_site_php_settings( account_id, php_settings, *, use_plan=False, customer_id=None @@ -123,20 +140,7 @@ def queue_site_php_settings( 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 + php_settings = limit_customer_php_settings(account, php_settings) changes = { "domain": account.primary_domain, diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index 87a78bf..676b8ed 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -98,7 +98,7 @@ def update_reseller(reseller_id, policy, actor): if "is_active" in policy and user.is_active != policy["is_active"]: if not may_manage_sign_in(user): raise ValidationError( - "This login can no longer be managed as a reseller." + "This login can no longer be managed as a manager." ) user.is_active = policy["is_active"] user.save(update_fields=["is_active"]) @@ -121,7 +121,7 @@ def create_reseller_account(access, account): reseller = lock_resellers(candidates).first() if reseller is None or not reseller.user.is_active: raise ValidationError( - {NON_FIELD_ERRORS: "Your reseller access has changed."} + {NON_FIELD_ERRORS: "Your manager access has changed."} ) if reseller.hostingaccount_set.count() >= reseller.account_limit: raise ValidationError( diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py index 037a73c..81f72fa 100644 --- a/src/coulobre/hosting/reseller_onboarding.py +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -69,3 +69,26 @@ def save_customer_link(account, reseller, customer, action): {"customer": str(customer)}, account_domain=account.primary_domain, ) + + +@transaction.atomic +def claim_customer_hosting(access, account_id): + account, manager = lock_reseller_account(access, account_id) + require_unassigned_customer(account) + customer, created = Customer.objects.get_or_create( + user_id=manager.user_id, defaults={"reseller": manager} + ) + if customer.reseller_id not in {None, manager.pk}: + raise ValidationError( + "Your customer profile belongs to another manager." + ) + if customer.reseller_id is None: + customer.reseller = manager + customer.save(update_fields=["reseller"]) + save_customer_link( + account, + manager, + customer, + Action.CUSTOMER_CREATE if created else Action.CUSTOMER_LINK, + ) + return account diff --git a/src/coulobre/hosting/reseller_onboarding_views.py b/src/coulobre/hosting/reseller_onboarding_views.py index 15bb55d..8aaafc5 100644 --- a/src/coulobre/hosting/reseller_onboarding_views.py +++ b/src/coulobre/hosting/reseller_onboarding_views.py @@ -1,19 +1,28 @@ from django import forms +from django.contrib import messages from django.contrib.auth import get_user_model -from django.contrib.auth.mixins import PermissionRequiredMixin -from django.core.exceptions import ValidationError -from django.db import IntegrityError +from django.contrib.auth.mixins import ( + PermissionRequiredMixin, + UserPassesTestMixin, +) +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import IntegrityError, transaction from django.http import Http404 from django.shortcuts import get_object_or_404, redirect from django.utils.functional import cached_property +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_POST from django.views.generic import FormView from .access import reseller_for_user from .invitations import InviteLoginForm, queue_invitation -from .models import HostingAccount +from .models import HostingAccount, HostingPlan +from .reseller_accounts import save_operator_account from .reseller_onboarding import ( + claim_customer_hosting, create_reseller_customer, link_reseller_customer, + lock_reseller_account, scoped_customers, ) @@ -103,3 +112,76 @@ class ResellerCustomerLink(ResellerCustomerEditor): form.add_error(None, error) return self.form_invalid(form) return redirect(account) + + +@require_POST +@never_cache +def claim_own_customer_hosting(request, pk): + manager = reseller_for_user(request.user) + if manager is None: + raise PermissionDenied + try: + account = claim_customer_hosting(manager, pk) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + messages.error(request, " ".join(error.messages)) + return redirect("panel:account", pk=pk) + messages.success( + request, "This hosting account is now in your Customer workspace." + ) + return redirect(account) + + +class ManagerHostingPlanForm(forms.Form): + plan = forms.ModelChoiceField(queryset=HostingPlan.objects.none()) + + def __init__(self, *args, manager, **kwargs): + super().__init__(*args, **kwargs) + self.fields["plan"].queryset = manager.hosting_plans.order_by("name") + + +class ManagerHostingPlanView(UserPassesTestMixin, FormView): + form_class = ManagerHostingPlanForm + template_name = "hosting/workspace_form.html" + extra_context = { + "title": "Assign hosting plan", + "submit_label": "Assign plan", + } + + def test_func(self): + self.manager = reseller_for_user(self.request.user) + return self.manager is not None + + @cached_property + def account(self): + return get_object_or_404( + self.manager.hostingaccount_set.filter(retired_at__isnull=True), + pk=self.kwargs["pk"], + ) + + def get_form_kwargs(self): + return super().get_form_kwargs() | {"manager": self.manager} + + def get_initial(self): + return {"plan": self.account.hosting_plan_id} + + @transaction.atomic + def form_valid(self, form): + try: + account, manager = lock_reseller_account( + self.manager, self.account.pk + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + chosen = form.cleaned_data["plan"] + if not manager.hosting_plans.filter(pk=chosen.pk).exists(): + form.add_error("plan", "This plan is no longer available.") + return self.form_invalid(form) + account.hosting_plan = chosen + save_operator_account( + account, + self.request.user.get_username(), + changed_fields=["hosting_plan"], + ) + return redirect(account) diff --git a/src/coulobre/hosting/reseller_profiles.py b/src/coulobre/hosting/reseller_profiles.py index 5cd36aa..f4dfe35 100644 --- a/src/coulobre/hosting/reseller_profiles.py +++ b/src/coulobre/hosting/reseller_profiles.py @@ -19,7 +19,7 @@ class ResellerProfileForm(forms.ModelForm): class Meta: model = ResellerProfile - fields = ("name", "account_limit", "hosting_plans", "manage_resources") + fields = ("name", "account_limit", "hosting_plans") help_texts = { "account_limit": "Enter 0 to manage existing accounts only.", } diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py index b557c3d..755ce51 100644 --- a/src/coulobre/hosting/reseller_views.py +++ b/src/coulobre/hosting/reseller_views.py @@ -32,16 +32,8 @@ class ResellerPolicyForm(forms.ModelForm): class Meta: model = Reseller - fields = ( - "is_active", - "account_limit", - "hosting_plans", - "manage_resources", - ) - labels = { - "hosting_plans": "Allowed hosting plans", - "manage_resources": "Manage databases and mailboxes", - } + fields = ("is_active", "account_limit", "hosting_plans") + labels = {"hosting_plans": "Allowed hosting plans"} help_texts = { "account_limit": "Enter 0 to manage existing accounts only.", "hosting_plans": ( diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index b078fda..2dce3f8 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -57,13 +57,26 @@ def create_database_request( @transaction.atomic def create_mailbox_request( - account_id, local_part, *, customer_id=None, auto_provision=False + account_id, + local_part, + *, + customer_id=None, + auto_provision=False, + mail_domain_name=None, ): account = lock_hosting_account(account_id, customer_id) require_open_account(account) - require_managed(account, account.primary_domain, "mail_managed") + domain = mail_domain_name or account.primary_domain + if domain != account.primary_domain: + from .domain_services import allowed_domains + + if domain not in allowed_domains(account): + raise ValidationError( + "This mail domain is outside the hosting account." + ) + require_managed(account, domain, "mail_managed") try: - spec = MailboxSpec(account.primary_domain, local_part) + spec = MailboxSpec(domain, local_part) except ValueError as error: raise ValidationError({"local_part": str(error)}) from error diff --git a/src/coulobre/hosting/system_backup_views.py b/src/coulobre/hosting/system_backup_views.py new file mode 100644 index 0000000..1aa67a9 --- /dev/null +++ b/src/coulobre/hosting/system_backup_views.py @@ -0,0 +1,123 @@ +from datetime import UTC, datetime, timedelta +from pathlib import Path + +from django import forms +from django.conf import settings +from django.contrib import messages +from django.contrib.admin.models import CHANGE, LogEntry +from django.db import transaction +from django.http import Http404 +from django.shortcuts import redirect +from django.utils import timezone +from django.views.generic import FormView + +from coulobre.operator_node import SOCKET + +from .account_administration import OperatorAuthorization +from .models import SystemBackupJob, SystemBackupSchedule + + +class SystemBackupScheduleForm(forms.Form): + enabled = forms.BooleanField(required=False, label="Run daily") + time = forms.TimeField( + required=False, + label="Daily start time (UTC)", + input_formats=["%H:%M"], + widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}), + ) + + def clean(self): + data = super().clean() + if data.get("enabled") and not data.get("time"): + self.add_error("time", "Choose the daily start time.") + return data + + +def next_system_backup(time, now): + candidate = datetime.combine(now.astimezone(UTC).date(), time, tzinfo=UTC) + return candidate if candidate > now else candidate + timedelta(days=1) + + +@transaction.atomic +def queue_scheduled_system_backup(now): + schedule = ( + SystemBackupSchedule.objects.select_for_update().filter(pk=1).first() + ) + if ( + schedule is None + or not schedule.enabled + or schedule.time is None + or schedule.next_run_at is None + or schedule.next_run_at > now + ): + return + if not SystemBackupJob.objects.filter(finished_at__isnull=True).exists(): + SystemBackupJob.objects.get_or_create( + scheduled_for=schedule.next_run_at + ) + schedule.next_run_at = next_system_backup(schedule.time, now) + schedule.save(update_fields=["next_run_at"]) + + +class SystemBackupView(OperatorAuthorization, FormView): + form_class = SystemBackupScheduleForm + template_name = "hosting/system_backup.html" + + def available(self): + return settings.SYSTEM_BACKUPS and Path(SOCKET).is_socket() + + def get_initial(self): + schedule = SystemBackupSchedule.objects.filter(pk=1).first() + return ( + {"enabled": schedule.enabled, "time": schedule.time} + if schedule + else {} + ) + + def get_context_data(self, **kwargs): + return super().get_context_data( + available=self.available(), + jobs=SystemBackupJob.objects.select_related("actor").order_by( + "-pk" + )[:30], + **kwargs, + ) + + @transaction.atomic + def post(self, request, *args, **kwargs): + if not self.available(): + raise Http404 + if request.POST.get("action") != "create": + return super().post(request, *args, **kwargs) + if request.POST.get("confirm") != "yes": + messages.error( + request, "Confirm that you want to create the backup." + ) + return redirect("panel:system_backup") + SystemBackupSchedule.objects.get_or_create(pk=1) + SystemBackupSchedule.objects.select_for_update().get(pk=1) + if SystemBackupJob.objects.filter(finished_at__isnull=True).exists(): + messages.error(request, "Wait for the current backup.") + else: + SystemBackupJob.objects.create(actor=request.user) + messages.success(request, "System backup queued.") + return redirect("panel:system_backup") + + def form_valid(self, form): + data = form.cleaned_data + defaults = data | { + "next_run_at": next_system_backup(data["time"], timezone.now()) + if data["enabled"] + else None, + } + schedule, _ = SystemBackupSchedule.objects.update_or_create( + pk=1, defaults=defaults + ) + LogEntry.objects.log_actions( + self.request.user.pk, + [schedule], + CHANGE, + "Changed system backup schedule.", + ) + messages.success(self.request, "System backup schedule saved.") + return redirect("panel:system_backup") diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 0c39d7b..f4a5cd7 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -62,6 +62,7 @@ from .models import ( SiteSFTP, SiteStorageLimit, SiteStorageUsage, + SystemBackupJob, WebActivation, WebHTTPS, WebProvisioningPlan, @@ -1312,13 +1313,18 @@ def collect_mailbox_usage(mailbox_id, requested_at): @shared_task(queue="coulobre-operator-actions") def run_operator_operation(job_id): + from coulobre.http_defaults import HttpDefaultsRequest 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) + spec = ( + HttpDefaultsRequest(job.target, job.parameters) + if job.action == "http-defaults" + else OperatorRequest(job.action, job.target, job.plan) + ) result = apply_on_local_node( spec, SOCKET, "operator service", "host operation", timeout=32 * 60 ) @@ -1465,6 +1471,7 @@ def apply_certificate_job(job_id): site, job.action, *(open_upload(job) if job.action == "upload" else ()), + **job.acme, ) reply = apply_on_local_node( spec, @@ -1623,3 +1630,48 @@ def apply_folder_sftp_job(job_id): FolderSftpLogin.objects.filter( pk=job_id, action="remove", problem="", finished_at__isnull=False ).delete() + + +@shared_task +def dispatch_system_backups(): + from .system_backup_views import queue_scheduled_system_backup + + if settings.SYSTEM_BACKUPS: + queue_scheduled_system_backup(timezone.now()) + dispatch_provisioning_jobs( + SystemBackupJob, + run_system_backup, + "coulobre-operator-actions", + lease=timedelta(minutes=35), + ) + + +@shared_task( + queue="coulobre-operator-actions", + acks_late=True, + reject_on_worker_lost=True, +) +def run_system_backup(job_id): + from coulobre.operator_node import SOCKET, OperatorRequest + + from .node_client import apply_on_local_node + + def apply(job): + reply = apply_on_local_node( + OperatorRequest("system-backup", target=str(job.identifier)), + SOCKET, + "operator service", + "system backup", + timeout=32 * 60, + ) + fields = ("archive", "bytes", "sha256", "created_at") + return {"report": {key: reply[key] for key in fields if key in reply}} + + if settings.SYSTEM_BACKUPS: + run_provisioning_job( + SystemBackupJob.objects.all(), + job_id, + apply, + "The operator service did not confirm the system backup.", + lease=timedelta(minutes=35), + ) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 40e8521..86b6fbf 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -14,7 +14,8 @@
{% if is_tenant or perms.hosting.view_hostingplan %} -
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
+
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %} + {% if is_reseller %}Assign plan{% endif %}
{% endif %} {% if is_operator and perms.hosting.view_reseller %}
Manager
{{ account.reseller|default_if_none:"Unassigned" }}
@@ -30,6 +31,9 @@ {% else %}Assigned{% endif %} {% else %} Add customer login +
{% csrf_token %} + +
{% if reseller_customer_link %} Link existing customer {% endif %} @@ -140,7 +144,7 @@ {% endif %} {% endif %} - {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} + {% if own_customer_operations and is_customer or own_customer_operations and is_operator and perms.hosting.add_hostingdatabase %} {% if automatic_database_provisioning %}Add{% else %}Request{% endif %} database {% endif %} @@ -305,7 +309,7 @@ {% endif %} {% endif %} - {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %} + {% if own_customer_operations and is_customer or own_customer_operations and is_operator and perms.hosting.add_hostingmailbox %} {% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/account_metrics_cells.html b/src/coulobre/hosting/templates/hosting/account_metrics_cells.html new file mode 100644 index 0000000..ef86cbf --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_metrics_cells.html @@ -0,0 +1,5 @@ +{% if usage and usage.storage is not None %}{{ usage.storage|filesizeformat }}{% else %}Unavailable{% endif %} +{% if usage and usage.traffic is not None %}{{ usage.traffic|filesizeformat }}{% else %}Unavailable{% endif %} +{% if usage %}{{ usage.domains|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %} +{% if usage %}{{ usage.databases|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %} +{% if usage %}{{ usage.mailboxes|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/all_users.html b/src/coulobre/hosting/templates/hosting/all_users.html index b99b68b..9d0cf62 100644 --- a/src/coulobre/hosting/templates/hosting/all_users.html +++ b/src/coulobre/hosting/templates/hosting/all_users.html @@ -9,11 +9,11 @@
- + - {% for login in logins %} - - {% empty %}{% endfor %} + {% for login, usage in login_rows %} + {% include "hosting/account_metrics_cells.html" %} + {% empty %}{% endfor %}
UserWorkspaceManagerHosting accountsAdded
UserWorkspaceManagerHosting accountsDiskMonthly trafficDomainsDatabasesMailboxesAdded
{{ login.get_username }}{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}{{ login.hosting_customer.reseller|default:"Unassigned" }}{{ login.account_count }}{{ login.date_joined|date:"j M Y" }}
No logins found.
{{ login.get_username }}{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}{{ login.hosting_customer.reseller|default:"Unassigned" }}{{ login.account_count }}{{ login.date_joined|date:"j M Y" }}
No logins found.
diff --git a/src/coulobre/hosting/templates/hosting/customer_certificates.html b/src/coulobre/hosting/templates/hosting/customer_certificates.html index d6ccd1b..7befa73 100644 --- a/src/coulobre/hosting/templates/hosting/customer_certificates.html +++ b/src/coulobre/hosting/templates/hosting/customer_certificates.html @@ -50,7 +50,11 @@
Challenge method
HTTP-01
Renewal
Managed by Certbot on the web node

The website's DNS must resolve to this node and HTTP port 80 must be reachable for validation.

-

Wildcard certificates require DNS-01 support on the server.

+ {% if enabled %} +
{% csrf_token %}{{ acme_form.as_div }} + +
+ {% endif %}
{% else %}
diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html index 8dd8469..14d4bb7 100644 --- a/src/coulobre/hosting/templates/hosting/customer_list.html +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -1,9 +1,9 @@ {% extends "hosting/base.html" %} -{% block title %}{% if is_reseller %}My customers{% else %}Customers{% endif %} · Coulobre Panel{% endblock %} +{% block title %}{% if is_reseller %}My users{% else %}Customers{% endif %} · Coulobre Panel{% endblock %} {% block content %}
-

{% if is_reseller %}My customers{% else %}Customers{% endif %}

+

{% if is_reseller %}My users{% else %}Customers{% endif %}

Manage the logins people use to access their assigned hosting.

{% if is_operator and perms.hosting.add_customer %} @@ -29,6 +29,7 @@ Username Sign-in status + {% if is_reseller %}DiskMonthly trafficDomainsDatabasesMailboxesAdded{% endif %} {% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %}Actions{% endif %} @@ -47,6 +48,7 @@ {% else %}Active {% endif %} + {% if is_reseller %}{% include "hosting/account_metrics_cells.html" with usage=customer.workspace_metrics %}{{ customer.user.date_joined|date:"j M Y" }}{% endif %} {% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %}
diff --git a/src/coulobre/hosting/templates/hosting/dns_defaults_form.html b/src/coulobre/hosting/templates/hosting/dns_defaults_form.html index b726117..77cc588 100644 --- a/src/coulobre/hosting/templates/hosting/dns_defaults_form.html +++ b/src/coulobre/hosting/templates/hosting/dns_defaults_form.html @@ -1,6 +1,10 @@ {% extends "hosting/base.html" %} {% block title %}DNS zone template · Coulobre Panel{% endblock %} {% block content %} +

DNS zone template

These settings apply when you create a managed DNS zone.

diff --git a/src/coulobre/hosting/templates/hosting/dns_topology.html b/src/coulobre/hosting/templates/hosting/dns_topology.html new file mode 100644 index 0000000..7924bce --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/dns_topology.html @@ -0,0 +1,20 @@ +{% extends "hosting/base.html" %} +{% block title %}DNS Settings · Coulobre Panel{% endblock %} +{% block content %} +

DNS Settings

+ +

Service routing

Connected nodes
+
    + {% for node in topology.nodes %}
  • {{ node.role|upper }} · {{ node.host }} · {{ node.state|default:"Unavailable"|capfirst }}
  • {% endfor %} +
  • DNS socket configured · {{ local_dns|yesno:"Yes,No" }}
  • +
  • Mail socket configured · {{ local_mail|yesno:"Yes,No" }}
  • +
+ {% if topology.problem %}

{{ topology.problem }}

{% endif %} +
+

Domain service ownership

+
{% csrf_token %}{{ form.as_div }}
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/domain_workspace.html b/src/coulobre/hosting/templates/hosting/domain_workspace.html index 0ac827a..f61933a 100644 --- a/src/coulobre/hosting/templates/hosting/domain_workspace.html +++ b/src/coulobre/hosting/templates/hosting/domain_workspace.html @@ -22,13 +22,21 @@ {% elif page == 'dns' %} {% if zone %}
-

DNS records

{% if may_edit_dns %}Edit zone{% endif %}
+

DNS records

{% if zone.publication %}

Publication {{ zone.publication.state }}

{% endif %}
{% 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 %} + {% if not policy.dns_managed %} +

Records for your DNS provider

+

At your authoritative DNS provider, add or update the web records. Keep existing email records until your mail provider is ready.

+
    {% for record in external_website_records %}
  • {{ record.name }} {{ record.record_type }} {{ record.address }}
  • {% empty %}
  • Ask your hosting provider for the website addresses.
  • {% endfor %}
+ {% if mail_domain and policy.mail_managed %}

Check MX, SPF, DKIM and DMARC records

{% endif %} +
+ {% elif zone_defaults.nameservers %} +

Nameservers

{{ zone_defaults.nameservers|join:", " }}

+ {% endif %} {% elif page == 'php' or page == 'files' %}
{% if primary %} @@ -37,19 +45,41 @@ {% else %}Browse files{% endif %} {% elif website %} {% if page == 'php' %}Select PHP version + Edit PHP limits {% else %}Browse files{% endif %} {% else %}

Select an active website for this action.

{% endif %}
+ {% elif page == 'email' %} + {% if not policy.mail_managed %} +

This domain uses an external mail provider.

+ {% else %} +

Mailboxes on {{ domain }}

+ {% if mail_enabled %}Add mailbox{% endif %} +
+
+ + {% for mailbox in mailboxes %} + + {% empty %}{% endfor %} +
Email addressQuotaStateActions
{{ mailbox.spec.address }}{{ mailbox.quota_mib|default_if_none:"Unlimited" }}{% if mailbox.quota_mib %} MiB{% endif %}{{ mailbox.provisioning.state|default:"Requested"|capfirst }}{% if mailbox.provisioning.state == 'configured' %} + Credentials + {% if roundcube_enabled %}
{% csrf_token %}
{% endif %} + {% endif %}
No mailboxes on this domain.
+ {% if mail_domain %}

Check email DNS

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

Forwarders and catch-all

Manage forwarders
- {% else %} +

Forwarders and catch-all

{% if can_edit_routing %}Manage forwarders{% endif %}
+ {% if not can_edit_routing %}

Mail forwarding is unavailable on this installation.

{% endif %} + {% elif can_edit_mailbox %} - {% endif %} + {% else %}

Mailbox delivery rules are unavailable on this installation.

{% endif %}
{% else %}

This domain has no managed email accounts.

{% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/http_defaults.html b/src/coulobre/hosting/templates/hosting/http_defaults.html new file mode 100644 index 0000000..2d941b8 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/http_defaults.html @@ -0,0 +1,27 @@ +{% extends "hosting/base.html" %} +{% block title %}HTTP Settings · Coulobre Panel{% endblock %} +{% block content %} +

HTTP Settings

+ {% for message in messages %}

{{ message }}

{% endfor %} + +
+ {% if target == 'apache' %}

Set server-wide Apache defaults. Review the effect on the panel and hosted sites before applying them.

+ {% else %}

Set PHP defaults for installed PHP-FPM versions. Website-specific settings still apply.

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

Template preview

{{ preview }}
{% endif %} +
+ + {% if preview and available %}{% endif %} +
+
+ {% if not available %}

Enable the operator worker to apply a template.

{% endif %} +
+

Change history

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

    {{ job.problem }}

    {% endif %}
  • + {% empty %}
  • No template changes yet.
  • {% endfor %}
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/independent_websites.html b/src/coulobre/hosting/templates/hosting/independent_websites.html index fed4e98..a4676de 100644 --- a/src/coulobre/hosting/templates/hosting/independent_websites.html +++ b/src/coulobre/hosting/templates/hosting/independent_websites.html @@ -30,7 +30,8 @@ Files {% endif %} {% for action in actions %} - {{ action.label }} + {% if action.value == 'settings' %}{{ action.label }} + {% else %}{{ action.label }}{% endif %} {% endfor %} {% if is_operator and perms.hosting.view_hostingaccount %} Download manifest diff --git a/src/coulobre/hosting/templates/hosting/mail_policy_form.html b/src/coulobre/hosting/templates/hosting/mail_policy_form.html index 40df287..58e0eb9 100644 --- a/src/coulobre/hosting/templates/hosting/mail_policy_form.html +++ b/src/coulobre/hosting/templates/hosting/mail_policy_form.html @@ -24,8 +24,10 @@

Last confirmed routes

{% include "hosting/mail_routes.html" with routes=applied %} {% endif %} - {% if not routing %} -

Messages still arrive in this mailbox. The mail server suppresses repeat replies to the same sender for seven days.

+ {% if spam_editor %} +

These rules apply at mailbox delivery. The mail node continues to enforce its server-wide filtering policy.

+ {% elif not routing %} +

Leave the start and end times blank to reply whenever the settings are enabled.

{% endif %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_form.html b/src/coulobre/hosting/templates/hosting/mailbox_form.html index 3205769..5aa5167 100644 --- a/src/coulobre/hosting/templates/hosting/mailbox_form.html +++ b/src/coulobre/hosting/templates/hosting/mailbox_form.html @@ -5,7 +5,7 @@

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

-

{{ account.primary_domain }}

+

{{ mail_domain_name|default:account.primary_domain }}

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

Account Backup & Restore

+ {% for message in messages %}

{{ message }}

{% endfor %} + +
+ + + +
+ + {% for account in accounts %} + + + + + + {% empty %}{% endfor %} +
Hosting accountManagerLatest backupScheduleActions
{{ account.primary_domain }}{{ account.reseller|default:"Unassigned" }}{% if account.last_backup %}{{ account.last_backup|date:"j M Y H:i" }} UTC · {% if account.last_problem %}Failed{% elif account.last_completed %}Completed{% else %}Queued{% endif %}{% else %}None{% endif %}{% if account.backup_schedule.enabled %}{{ account.backup_schedule.get_frequency_display }} at {{ account.backup_schedule.time|time:"H:i" }} UTC{% else %}Disabled{% endif %}Archives and restores{% if enabled %} · Schedule{% endif %}
No accounts available.
+ {% include "hosting/pagination.html" %} +
+ {% if enabled %} +
+

Back up a manager's hosting accounts

+
{% csrf_token %}{{ form.as_div }}
+
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/operator_certificates.html b/src/coulobre/hosting/templates/hosting/operator_certificates.html index 10b223c..042ba7a 100644 --- a/src/coulobre/hosting/templates/hosting/operator_certificates.html +++ b/src/coulobre/hosting/templates/hosting/operator_certificates.html @@ -15,6 +15,18 @@
Service health +
+

Local TLS checks

{% if tls_job %}

{{ tls_job.state|capfirst }} · {{ tls_job.requested_at|date:"j M Y H:i" }} UTC

{% endif %}
+ {% if tls_available %}
{% csrf_token %}
{% endif %} +
+ {% if tls_job.problem %}

{{ tls_job.problem }}

{% endif %} + {% if tls_result %}
+ + {% for endpoint in tls_result.result.endpoints %} + + {% endfor %} +
EndpointCertificateIssuerExpiry
{{ endpoint.service }} · {{ endpoint.port }}{% if endpoint.status == 'presented' %}{{ endpoint.name_matches|yesno:"Hostname matches,Hostname mismatch" }}{% else %}Unavailable on loopback{% endif %}{{ endpoint.issuer|default:"Unavailable" }}{{ endpoint.expires|default:"Unavailable" }}
{% endif %} +
{% else %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index 4df0dec..fb63b57 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -4,6 +4,9 @@ ← Managers

{{ reseller }}

+ {% if perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %} + Add hosting account + {% endif %} {% if perms.hosting.change_reseller %} Contact and invitation Edit manager @@ -11,7 +14,6 @@
Panel sign-in
{{ reseller.user.is_active|yesno:"Active,Suspended" }}
-
Database and mailbox management
{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}
Accounts allocated
{{ account_count }} of {{ reseller.account_limit }}
{% if perms.hosting.view_hostingplan %}
diff --git a/src/coulobre/hosting/templates/hosting/site_php_settings_form.html b/src/coulobre/hosting/templates/hosting/site_php_settings_form.html index 87f53f4..de46311 100644 --- a/src/coulobre/hosting/templates/hosting/site_php_settings_form.html +++ b/src/coulobre/hosting/templates/hosting/site_php_settings_form.html @@ -5,12 +5,12 @@

Change PHP settings

-

{{ account.primary_domain }}

+

{{ site_domain|default:account.primary_domain }}

-

Blank fields use the web node defaults.

+

{% if is_customer %}Blank fields use the hosting plan defaults.{% else %}Blank fields use the web node defaults.{% endif %}

{% csrf_token %} {{ form.as_div }}
diff --git a/src/coulobre/hosting/templates/hosting/system_backup.html b/src/coulobre/hosting/templates/hosting/system_backup.html new file mode 100644 index 0000000..d9c67c1 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/system_backup.html @@ -0,0 +1,30 @@ +{% extends "hosting/base.html" %} +{% block title %}System Backup · Coulobre Panel{% endblock %} +{% block content %} +

System Backup

+ {% for message in messages %}

{{ message }}

{% endfor %} + {% if available %} +
+

Run a backup

+

The archive contains local service configuration, MariaDB, and hosted files and mail. Retrieve it on the server using an administrator account.

+ {% csrf_token %} + + + +
+
+

Schedule

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

Enable system backups and the local operator worker on this server.

{% endif %} +

Backup history

+
    {% for job in jobs %} +
  • {{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.actor|default:"Scheduled" }} · {{ job.state|capfirst }} + {% if job.problem %}

    {{ job.problem }}

    {% endif %} + {% if job.report.archive %}

    {{ job.report.archive }} · {{ job.report.bytes|filesizeformat }}

    {% endif %} +
  • + {% empty %}
  • No system backups have been run.
  • {% endfor %}
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/system_workspace.html b/src/coulobre/hosting/templates/hosting/system_workspace.html index de3067d..353e9c2 100644 --- a/src/coulobre/hosting/templates/hosting/system_workspace.html +++ b/src/coulobre/hosting/templates/hosting/system_workspace.html @@ -6,8 +6,8 @@ {% if section == 'statistics' %}
WebsiteAccountLast known issuerExpiry
- {% for account, storage, traffic in rows %} - + {% for account, usage 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 }}
{{ account.primary_domain }}{% if usage.storage is not None %}{{ usage.storage|filesizeformat }}{% else %}Unavailable{% endif %}{% if usage.traffic is not None %}{{ usage.traffic|filesizeformat }}{% else %}Unavailable{% endif %}{{ usage.domains }}{{ usage.databases|default_if_none:"Unavailable" }}{{ usage.mailboxes|default_if_none:"Unavailable" }}
No hosting accounts are available.
{% elif section == 'tasks' %} @@ -19,7 +19,7 @@ {% else %}
    - {% for account, storage, traffic in rows %}
  • {% if target %}{{ account.primary_domain }}{% else %}{{ account.primary_domain }}{% endif %}
  • + {% for account, usage in rows %}
  • {% if target %}{{ account.primary_domain }}{% else %}{{ account.primary_domain }}{% endif %}
  • {% empty %}
  • No hosting accounts are available.
  • {% endfor %}
{% if not target %}

Website logs need a configured collector.

{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/workspace_navigation.html b/src/coulobre/hosting/templates/hosting/workspace_navigation.html index 9ddb800..c7877ac 100644 --- a/src/coulobre/hosting/templates/hosting/workspace_navigation.html +++ b/src/coulobre/hosting/templates/hosting/workspace_navigation.html @@ -2,7 +2,7 @@ {% endfor %} diff --git a/src/coulobre/hosting/test_database_provisioning.py b/src/coulobre/hosting/test_database_provisioning.py index aaedcb3..8a13ceb 100644 --- a/src/coulobre/hosting/test_database_provisioning.py +++ b/src/coulobre/hosting/test_database_provisioning.py @@ -106,6 +106,8 @@ class DatabaseProvisioningTests(TestCase): ) self.client.force_login(requester) url = reverse("panel:database_create", args=[self.account.pk]) + self.assertEqual(self.client.get(url).status_code, 403) + HostingAccount.objects.filter(pk=self.account.pk).update(customer=None) self.assertContains(self.client.get(url), "Request database") self.assertRedirects( self.client.post(url, {"suffix": "request"}), self.detail diff --git a/src/coulobre/hosting/test_resellers.py b/src/coulobre/hosting/test_resellers.py index a29d286..954324c 100644 --- a/src/coulobre/hosting/test_resellers.py +++ b/src/coulobre/hosting/test_resellers.py @@ -275,7 +275,7 @@ class ResellerAccountCreationTests(TestCase): "hosting_plan": self.allowed.pk, }, ) - self.assertContains(response, "Your reseller access has changed.") + self.assertContains(response, "Your manager access has changed.") self.assertEqual(self.reseller.hostingaccount_set.count(), 1) def test_operator_can_configure_limit_and_allowed_plans(self): @@ -352,7 +352,7 @@ class ResellerManagementTests(TestCase): self.client.get(self.index, {"q": "new-"}), "0 of 4" ) self.assertContains( - self.client.get(reseller.get_absolute_url()), "Created reseller" + self.client.get(reseller.get_absolute_url()), "Created manager" ) audit = reseller.audit_events.get() self.assertEqual(audit.actor_username, "operator") diff --git a/src/coulobre/hosting/test_website_files.py b/src/coulobre/hosting/test_website_files.py index 228db92..9a76261 100644 --- a/src/coulobre/hosting/test_website_files.py +++ b/src/coulobre/hosting/test_website_files.py @@ -269,6 +269,8 @@ class WebsiteFilePanelTests(TestCase): self.staff.user_permissions.add( Permission.objects.get(codename="manage_website_files") ) + self.assertEqual(self.client.get(self.primary_url).status_code, 403) + HostingAccount.objects.filter(pk=self.account.pk).update(customer=None) with patch( "coulobre.hosting.website_file_views.request_website_files", return_value={"entries": [], "after": ""}, diff --git a/src/coulobre/hosting/test_website_jobs.py b/src/coulobre/hosting/test_website_jobs.py index c2392b9..a883292 100644 --- a/src/coulobre/hosting/test_website_jobs.py +++ b/src/coulobre/hosting/test_website_jobs.py @@ -240,6 +240,8 @@ class WebsiteJobWorkflowTests(TestCase): self.operator.user_permissions.add( Permission.objects.get(codename="manage_website_jobs") ) + self.assertEqual(self.client.get(self.jobs_url).status_code, 403) + HostingAccount.objects.filter(pk=self.account.pk).update(customer=None) self.assertEqual(self.client.get(self.jobs_url).status_code, 200) with self.settings(WEBSITE_JOBS=False): self.assertEqual(self.client.get(self.jobs_url).status_code, 404) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 6f8679e..ddca1f4 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -31,6 +31,7 @@ from .database_login_views import ( ) from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView +from .dns_topology_views import DnsTopologyView from .domain_services import domain_workspace from .folder_sftp_views import folder_sftp_users from .health_views import ServiceHealthView @@ -38,14 +39,24 @@ from .independent_website_views import ( IndependentWebsiteCreate, IndependentWebsiteManifest, IndependentWebsiteOperation, + IndependentWebsitePhpSettings, ) from .installation_views import FeatureConfigurationView, InstallationView from .invitations import AcceptInvitation, ManageInvitation from .mail_delivery_views import MailDeliveryView from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup -from .mail_policy_views import MailRoutingEditor, MailVacationEditor +from .mail_policy_views import ( + MailRoutingEditor, + MailSpamEditor, + MailVacationEditor, +) from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action -from .operator_tools import ConnectedNodesView, OperatorToolsView +from .operator_backups import OperatorBackupsView +from .operator_tools import ( + ConnectedNodesView, + HttpDefaultsView, + OperatorToolsView, +) from .panel_content import ( AnnouncementView, DirectAdminGuideView, @@ -64,8 +75,10 @@ from .password_reset import ( from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin from .redirect_views import customer_redirects from .reseller_onboarding_views import ( + ManagerHostingPlanView, ResellerCustomerCreate, ResellerCustomerLink, + claim_own_customer_hosting, ) from .reseller_profiles import ( ResellerProfileCreate, @@ -86,6 +99,7 @@ from .sign_in import ( PanelLoginView, VerifyFactorView, ) +from .system_backup_views import SystemBackupView from .update_views import UpdateView from .website_file_views import WebsiteFilesView from .website_job_views import WebsiteJobEditor, WebsiteJobList @@ -125,6 +139,31 @@ urlpatterns = [ folder_sftp_users, name="folder_sftp_users", ), + path( + "accounts//claim/", + claim_own_customer_hosting, + name="claim_customer_hosting", + ), + path( + "accounts//hosting-plan/", + ManagerHostingPlanView.as_view(), + name="manager_assign_plan", + ), + path("backups/", OperatorBackupsView.as_view(), name="operator_backups"), + path("backups/system/", SystemBackupView.as_view(), name="system_backup"), + path( + "hosting//sites//php-settings/", + IndependentWebsitePhpSettings.as_view(), + name="independent_php_settings", + ), + path( + "dns-settings/routing/", DnsTopologyView.as_view(), name="dns_topology" + ), + path( + "http-settings//", + HttpDefaultsView.as_view(), + name="http_defaults", + ), path("ssl/", operator_certificates, name="operator_certificates"), path( "hosting//certificates/", @@ -136,6 +175,9 @@ urlpatterns = [ customer_redirects, name="customer_redirects", ), + path( + "mailboxes//spam/", MailSpamEditor.as_view(), name="mail_spam" + ), path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"), path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), path( diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index fbb20d8..77c74fe 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -41,6 +41,7 @@ from .access import ( customer_for_user, is_tenant, manages_account, + owns_customer_operations, reseller_for_user, ) from .account_backup_forms import ( @@ -57,6 +58,7 @@ from .account_backups import ( queue_account_backup, save_backup_schedule, ) +from .account_metrics import customer_metrics from .account_setup import default_dns_zone, setup_new_account, website_records from .backup_restores import ( RestoreKind, @@ -529,6 +531,14 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): and self.request.user.has_perm(VIEW_CUSTOMERS) ): initial["customer"] = int(customer) + manager = self.request.GET.get("manager", "") + if ( + manager.isascii() + and manager.isdecimal() + and len(manager) <= 18 + and (self.request.user.has_perm(VIEW_RESELLERS)) + ): + initial["reseller"] = int(manager) return initial def form_valid(self, form): @@ -608,6 +618,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): and user.has_perm(CHANGE_ACCOUNTS) and bool(missing_account_setup(self.object, user)) ) + context["own_customer_operations"] = owns_customer_operations( + user, self.object + ) context["show_website_usage"] = settings.WEBSITE_USAGE and ( tenant or user.has_perm("hosting.view_websiteusage") ) @@ -628,6 +641,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): manage_files = ( not self.object.services_suspended and can_manage_website_files(self.request) + and owns_customer_operations(user, self.object) ) context["manage_website_files"] = manage_files context["manage_website_jobs"] = can_manage_website_jobs( @@ -812,6 +826,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["manage_sftp"] = ( settings.LOCAL_WEB_SFTP and can_manage_sftp(user) + and owns_customer_operations(user, self.object) and (site_active or hasattr(self.object, "sftp")) ) if reseller is not None or ( @@ -1067,9 +1082,10 @@ class SitePhpSettingsEdit(PermissionRequiredMixin, FormView): def has_permission(self): user = self.request.user - return customer_for_user(user) is not None or ( + allowed = customer_for_user(user) is not None or ( reseller_for_user(user) is None and super().has_permission() ) + return allowed and owns_customer_operations(user, self.account) @cached_property def account(self): @@ -1123,7 +1139,9 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView): return super().dispatch(request, *args, **kwargs) def has_permission(self): - return can_change_php_version(self.request) + return can_change_php_version( + self.request + ) and owns_customer_operations(self.request.user, self.account) @cached_property def account(self): @@ -1773,7 +1791,9 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): return super().dispatch(request, *args, **kwargs) def has_permission(self): - return can_manage_sftp(self.request.user) + return can_manage_sftp(self.request.user) and owns_customer_operations( + self.request.user, self.account + ) @cached_property def account(self): @@ -1863,12 +1883,21 @@ class CustomerList(TenantScopeMixin, PermissionRequiredMixin, ListView): return queryset def get_context_data(self, **kwargs): - return super().get_context_data( + context = super().get_context_data( search=self.search, can_impersonate=can_impersonate_customer(self.request.user), can_start_support=can_start_writable_support(self.request.user), **kwargs, ) + manager = reseller_for_user(self.request.user) + if manager: + measurements = customer_metrics( + [customer.pk for customer in context["customers"]], + manager=manager, + ) + for customer in context["customers"]: + customer.workspace_metrics = measurements.get(customer.pk) + return context class CustomerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView): @@ -1985,7 +2014,10 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def has_permission(self): if reseller_for_user(self.request.user) is not None: return False - return self.customer is not None or super().has_permission() + allowed = self.customer is not None or super().has_permission() + return allowed and owns_customer_operations( + self.request.user, self.account + ) @cached_property def account(self): @@ -2395,6 +2427,43 @@ class MailboxCreate(ResourceRequestCreate): provisioning_permissions = PROVISION_MAILBOX create_resource = staticmethod(create_mailbox_request) + @cached_property + def mail_domain_name(self): + domain = self.request.GET.get("domain") + if domain is None: + return None + if self.customer is None or getattr( + self.request, "impersonation", None + ): + raise Http404 + from .domain_services import allowed_domains + + if domain not in allowed_domains(self.account): + raise Http404 + return domain + + def get_context_data(self, **kwargs): + return super().get_context_data( + mail_domain_name=self.mail_domain_name, **kwargs + ) + + def create_request(self, account_id, **values): + return super().create_request( + account_id, mail_domain_name=self.mail_domain_name, **values + ) + + def form_valid(self, form): + response = super().form_valid(form) + if response.status_code == 302 and self.mail_domain_name is not None: + return redirect( + reverse( + "panel:domain_workspace", + args=[self.account.pk, "email"], + query={"domain": self.mail_domain_name}, + ) + ) + return response + def get_form(self, form_class=None): form = super().get_form(form_class) form.fields["local_part"].help_text = INVALID_LOCAL_PART diff --git a/src/coulobre/hosting/website_file_views.py b/src/coulobre/hosting/website_file_views.py index ce6a86f..4990237 100644 --- a/src/coulobre/hosting/website_file_views.py +++ b/src/coulobre/hosting/website_file_views.py @@ -19,7 +19,11 @@ from coulobre.website_files import ( directory_parts, ) -from .access import TenantScopeMixin, can_manage_hosting +from .access import ( + TenantScopeMixin, + can_manage_hosting, + owns_customer_operations, +) from .independent_websites import active_websites from .installation_features import panel_feature_allowed from .models import HostingAccount @@ -80,7 +84,9 @@ class WebsiteFilesView( return super().dispatch(request, *args, **kwargs) def has_permission(self): - return can_manage_website_files(self.request) + return can_manage_website_files( + self.request + ) and owns_customer_operations(self.request.user, self.account) @cached_property def account(self): diff --git a/src/coulobre/hosting/website_job_views.py b/src/coulobre/hosting/website_job_views.py index bf9d27e..fb6f9a4 100644 --- a/src/coulobre/hosting/website_job_views.py +++ b/src/coulobre/hosting/website_job_views.py @@ -15,7 +15,11 @@ from django.views.generic.detail import SingleObjectMixin from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command -from .access import TenantScopeMixin, can_manage_hosting +from .access import ( + TenantScopeMixin, + can_manage_hosting, + owns_customer_operations, +) from .independent_websites import check_actor from .installation_features import panel_feature_allowed from .models import HostingAccount @@ -109,7 +113,9 @@ class WebsiteJobAccountView( return super().dispatch(request, *args, **kwargs) def has_permission(self): - return can_manage_website_jobs(self.request) + return can_manage_website_jobs( + self.request + ) and owns_customer_operations(self.request.user, self.account) @cached_property def account(self): diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index c233f9e..36186a8 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -1,7 +1,6 @@ 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 @@ -10,6 +9,7 @@ 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 .account_metrics import account_metrics from .installation_features import panel_feature_allowed from .models import HostingAccount, WebsiteScheduledJob @@ -28,6 +28,7 @@ CUSTOMER_PAGES = { "email": ("Email Accounts", "account", "email"), "forwarders": ("Forwarders", "account", "email"), "replies": ("Automatic replies", "account", "email"), + "spam": ("Spam protection", "account", "email"), "backups": ("Backup & Restore", "customer_backups", ""), "tasks": ("Scheduled Tasks", "website_jobs", ""), } @@ -38,6 +39,66 @@ SYSTEM_PAGES = { } +CUSTOMER_NAV_ROUTES = { + "customer_certificates": "certificates", + "customer_redirects": "redirects", + "folder_sftp_users": "sftp", + "sftp_keys": "sftp", + "customer_databases": "databases", + "database_logins": "databases", + "database_create": "databases", + "database_credentials": "databases", + "database_login_credentials": "databases", + "customer_backups": "backups", + "customer_restore": "backups", + "website_jobs": "tasks", + "website_job_create": "tasks", + "website_job_edit": "tasks", + "site_php_settings": "php", + "independent_php_settings": "php", + "website_files": "files", + "independent_website_files": "files", + "mailbox_create": "email", + "mailbox_credentials": "email", + "mail_routing": "forwarders", + "mail_vacation": "replies", + "mail_spam": "spam", +} + +WORKSPACE_PARENT_ROUTES = { + "dns_topology": ("dns_defaults", ()), + "operator_settings": ("operator_settings", ("general",)), + "http_defaults": ("http_defaults", ("apache",)), + "server_updates": ("updates", ()), + "mail_queue": ("mail_queue_index", ()), + "reseller": ("resellers", ()), + "reseller_edit": ("resellers", ()), + "hosting_plan_create": ("hosting_plans", ()), + "hosting_plan_edit": ("hosting_plans", ()), + "manager_assign_plan": ("manager_packages", ()), + "account": ("accounts", ()), +} + + +def active_navigation(request, *, customer): + match = request.resolver_match + if match is None: + return request.path + name = match.url_name + if customer: + page = ( + match.kwargs.get("page") + if name == "domain_workspace" + else CUSTOMER_NAV_ROUTES.get(name) + ) + if page: + return reverse("panel:customer_workspace", args=[page]) + if target := WORKSPACE_PARENT_ROUTES.get(name): + route, arguments = target + return reverse(f"panel:{route}", args=arguments) + return request.path + + def workspace_accounts(user): accounts = HostingAccount.objects.filter(retired_at__isnull=True) customer = customer_for_user(user) @@ -93,7 +154,16 @@ def customer_workspace(request, page): return redirect("panel:accounts") if page == "overview": return redirect(account) - if page in {"domains", "dns", "php", "files", "forwarders", "replies"}: + if page in { + "domains", + "dns", + "php", + "files", + "email", + "forwarders", + "replies", + "spam", + }: return redirect("panel:domain_workspace", pk=account.pk, page=page) _, destination, fragment = pages[page] return redirect( @@ -125,43 +195,27 @@ 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 - ) + pagination = Paginator(accounts, 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, - ) + operator = ( + customer_for_user(request.user) is None + and reseller_for_user(request.user) is None + ) + measures = ( + account_metrics( + page_obj.object_list, + databases=not operator + or request.user.has_perm("hosting.view_hostingdatabase"), + mailboxes=not operator + or request.user.has_perm("hosting.view_hostingmailbox"), ) + if page == "statistics" + else {} + ) + rows = [(account, measures.get(account.pk, {})) for account in page_obj] tasks = () - task_accounts = set(account.pk for account, _, _ in rows) + task_accounts = {account.pk for account, _ in rows} if page == "tasks": tasks = ( WebsiteScheduledJob.objects.filter(account_id__in=task_accounts) @@ -223,7 +277,7 @@ def groups_for(request, *, customer, manager): ), ( "Email Manager", - hosted("email", "forwarders", "replies") + hosted("email", "forwarders", "replies", "spam") + ( [link("mail_delivery", "Mail delivery")] if panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") @@ -286,6 +340,7 @@ def groups_for(request, *, customer, manager): ( link("operator_settings", "Operator Settings", "general"), link("dns_defaults", "DNS Settings"), + link("http_defaults", "HTTP Settings", "apache"), ) ) if user.is_superuser: @@ -295,6 +350,8 @@ def groups_for(request, *, customer, manager): link("announcements", "Message"), link("directadmin_guide", "Import"), link("operator_certificates", "SSL Overview"), + link("operator_backups", "Backup & Restore"), + link("system_backup", "System Backup"), ) ) if user.is_superuser: diff --git a/src/coulobre/http_defaults.py b/src/coulobre/http_defaults.py new file mode 100644 index 0000000..44cc2b7 --- /dev/null +++ b/src/coulobre/http_defaults.py @@ -0,0 +1,150 @@ +import os +from dataclasses import dataclass +from pathlib import Path + +from .node_files import ( + locked_root_directory, + read_root_file, + replace_configuration, + require_root_directory, +) +from .php_runtime import PhpRuntime, installed_php_versions + +OPERATION = "http-defaults" +APACHE_DEFAULTS = Path( + "/etc/apache2/conf-enabled/coulobre-hosting-limits.conf" +) +HEADER = "# Managed by Coulobre Panel\n" +CONTROLS = { + "apache": { + "keep_alive": ("Keep-alive", 0, 1, 1), + "keep_alive_timeout": ("Keep-alive timeout (seconds)", 1, 30, 5), + "request_timeout": ("Request timeout (seconds)", 10, 300, 60), + "request_body_mib": ("Request body limit (MiB)", 64, 2048, 128), + }, + "php": { + "memory_mib": ("Memory limit (MiB)", 32, 2048, 128), + "upload_mib": ("Upload limit (MiB)", 1, 512, 16), + "execution_seconds": ("Execution limit (seconds)", 15, 600, 30), + }, +} + + +@dataclass(frozen=True) +class HttpDefaultsRequest: + target: str + values: dict + + def __post_init__(self): + if not isinstance(self.target, str) or self.target not in CONTROLS: + raise ValueError("Choose Apache or PHP-FPM settings.") + controls = CONTROLS[self.target] + if ( + not isinstance(self.values, dict) + or self.values.keys() != controls.keys() + ): + raise ValueError("Provide all of the supported template settings.") + for key, (label, minimum, maximum, _) in controls.items(): + value = self.values[key] + if type(value) is not int or not minimum <= value <= maximum: + raise ValueError( + f"{label} must be between {minimum} and {maximum}." + ) + if ( + self.target == "php" + and self.values["upload_mib"] >= self.values["memory_mib"] + ): + raise ValueError( + "Set the upload limit below the PHP memory limit." + ) + + def manifest(self): + return { + "operation": OPERATION, + "target": self.target, + "values": self.values, + } + + @classmethod + def from_manifest(cls, data): + if data.keys() != {"operation", "target", "values"}: + raise ValueError("Expected HTTP template settings.") + return cls(data["target"], data["values"]) + + def render(self): + data = self.values + if self.target == "apache": + enabled = "On" if data["keep_alive"] else "Off" + body_limit = data["request_body_mib"] * 1024 * 1024 + return ( + HEADER + + f"KeepAlive {enabled}\n" + + f"KeepAliveTimeout {data['keep_alive_timeout']}\n" + + f"Timeout {data['request_timeout']}\n" + + f"LimitRequestBody {body_limit}\n" + ) + upload = data["upload_mib"] + return ( + "; Managed by Coulobre Panel\n" + f"memory_limit = {data['memory_mib']}M\n" + f"upload_max_filesize = {upload}M\n" + f"post_max_size = {upload + 1}M\n" + f"max_execution_time = {data['execution_seconds']}\n" + ) + + +def targets_for(request): + if request.target == "apache": + return [ + ( + APACHE_DEFAULTS, + ("/usr/sbin/apache2ctl", "configtest"), + "apache2.service", + ) + ] + targets = [] + for series in installed_php_versions(): + php = PhpRuntime(series) + ini = php.pools.parent / "conf.d" / "98-coulobre-defaults.ini" + targets.append((ini, (php.binary, "--test"), f"{php.service}.service")) + if not targets: + raise ValueError("No managed PHP-FPM series is installed.") + return targets + + +def apply_http_defaults(request): + from .operator_node import STATE, command + + if os.geteuid() != 0: + raise ValueError("Apply HTTP templates as root on the web server.") + with locked_root_directory(STATE): + originals = {} + targets = targets_for(request) + content = request.render() + for path, _, _ in targets: + require_root_directory(path.parent) + originals[path] = ( + read_root_file(path) if os.path.lexists(path) else None + ) + written = [] + reload_attempts = [] + try: + for path, _, _ in targets: + replace_configuration(path, content) + written.append(path) + for _, check, _ in targets: + command(*check) + for _, _, service in targets: + reload_attempts.append(service) + command("/usr/bin/systemctl", "reload", service) + command("/usr/bin/systemctl", "is-active", "--quiet", service) + except (OSError, ValueError, KeyboardInterrupt): + for path in reversed(written): + if originals[path] is None: + path.unlink(missing_ok=True) + else: + replace_configuration(path, originals[path]) + for service in reload_attempts: + command("/usr/bin/systemctl", "reload", service) + raise + return {"services": [service for _, _, service in targets], "active": True} diff --git a/src/coulobre/local_update.py b/src/coulobre/local_update.py index 5ba8c05..4d0980d 100644 --- a/src/coulobre/local_update.py +++ b/src/coulobre/local_update.py @@ -55,6 +55,9 @@ MANAGED_UNITS = frozenset( "coulobre-mail-credentials.socket", "coulobre-mailbox-provisioner.service", "coulobre-offsite-worker.service", + "coulobre-operator-apply.socket", + "coulobre-operator-worker.service", + "coulobre-folder-sftp.socket", "coulobre-provisioner.service", "coulobre-service-credentials.socket", "coulobre-sftp-apply.socket", diff --git a/src/coulobre/mail_node_vacation.py b/src/coulobre/mail_node_vacation.py index 0954821..2ed6d56 100644 --- a/src/coulobre/mail_node_vacation.py +++ b/src/coulobre/mail_node_vacation.py @@ -42,6 +42,34 @@ def vacation_script(spec): ) +def mailbox_delivery_script(spec): + if not spec.move_spam and not spec.junk_senders: + return vacation_script(spec) + required = ["fileinto", "mailbox", "envelope"] + tests = [] + if spec.move_spam: + tests.append('header :is ["X-Spam", "X-Spam-Flag"] "YES"') + if spec.junk_senders: + senders = ", ".join( + sieve_string(sender) for sender in spec.junk_senders + ) + tests.append(f'envelope :is "from" [{senders}]') + reply = "" + if spec.enabled: + required.append("vacation") + if spec.starts_at or spec.ends_at: + required.extend(("date", "relational")) + reply = vacation_script(spec).split("\n", maxsplit=1)[1] + extensions = ", ".join(sieve_string(item) for item in required) + return ( + f"require [{extensions}];\n" + f"if anyof ({', '.join(tests)}) {{\n" + ' fileinto :create "Junk";\n' + " stop;\n" + "}\n" + reply + ) + + def script_path(mailbox): return VACATION_ROOT / mailbox.domain / f"{mailbox.local_part}.sieve" @@ -66,7 +94,7 @@ def apply_vacation(spec): or os.path.lexists(mail.retirement_guard(record.mailbox)) ): raise ValueError("The managed mailbox is unavailable.") - if not spec.enabled: + if not spec.enabled and not spec.move_spam and not spec.junk_senders: remove_vacation(spec.mailbox) return config = mail.run("doveconf", "-f", "protocol=lmtp", "-n") @@ -78,7 +106,7 @@ def apply_vacation(spec): target = script_path(spec.mailbox) for directory in (VACATION_ROOT, target.parent): require_root_directory(directory, create_mode=0o751) - content = vacation_script(spec) + content = mailbox_delivery_script(spec) if ( os.path.lexists(target) and read_root_file(target, mode=0o640) == content diff --git a/src/coulobre/mail_policy.py b/src/coulobre/mail_policy.py index 62215e0..0227959 100644 --- a/src/coulobre/mail_policy.py +++ b/src/coulobre/mail_policy.py @@ -10,6 +10,7 @@ from .mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec MAIL_POLICY_LIMIT = 64 * 1024 DEFAULT_REPEAT_DAYS = 7 MAX_REPEAT_DAYS = 60 +MAX_JUNK_SENDERS = 20 MAX_ALIASES = 100 MAX_DESTINATIONS = 10 OPERATIONS = ("set_mail_routing", "set_mail_vacation") @@ -125,8 +126,23 @@ class MailVacation(MailPolicy): starts_at: str = "" ends_at: str = "" repeat_days: int = DEFAULT_REPEAT_DAYS + move_spam: bool = False + junk_senders: tuple[str, ...] = () def __post_init__(self): + if ( + type(self.move_spam) is not bool + or not isinstance(self.junk_senders, (list, tuple)) + or len(self.junk_senders) > MAX_JUNK_SENDERS + ): + raise ValueError("Choose up to 20 senders for the mailbox filter.") + senders = tuple( + dict.fromkeys( + mail_address(sender, self.mailbox.domain).lower() + for sender in self.junk_senders + ) + ) + object.__setattr__(self, "junk_senders", senders) if ( type(self.repeat_days) is not int or not 1 <= self.repeat_days <= MAX_REPEAT_DAYS @@ -167,7 +183,7 @@ class MailVacation(MailPolicy): raise ValueError("The end time must be after the start time.") def manifest(self): - return { + payload = { "version": 1, "operation": "set_mail_vacation", "mailbox": self.mailbox.manifest(), @@ -181,6 +197,12 @@ class MailVacation(MailPolicy): if self.repeat_days != DEFAULT_REPEAT_DAYS else {} ) + if self.move_spam or self.junk_senders: + payload["spam"] = { + "move_spam": self.move_spam, + "junk_senders": list(self.junk_senders), + } + return payload def parse_mail_policy(data): @@ -204,10 +226,16 @@ def parse_mail_policy(data): "starts_at", "ends_at", } - if data.get("operation") == "set_mail_vacation" and fields in ( - vacation_fields, - vacation_fields | {"repeat_days"}, + if ( + data.get("operation") == "set_mail_vacation" + and fields - {"repeat_days", "spam"} == vacation_fields ): + spam = data.get("spam", {"move_spam": False, "junk_senders": []}) + if not isinstance(spam, dict) or spam.keys() != { + "move_spam", + "junk_senders", + }: + raise ValueError("Expected structured mailbox spam rules.") return MailVacation( MailboxSpec.from_manifest(data["mailbox"]), data["enabled"], @@ -216,5 +244,6 @@ def parse_mail_policy(data): data["starts_at"], data["ends_at"], data.get("repeat_days", DEFAULT_REPEAT_DAYS), + **spam, ) raise ValueError("Expected a version 1 mail policy.") diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py index ba6c196..4c79dd7 100644 --- a/src/coulobre/operator_node.py +++ b/src/coulobre/operator_node.py @@ -23,6 +23,8 @@ ACTIONS = ( "reload", "restart", "database-report", + "system-backup", + "server-tls", ) APT = "/usr/bin/apt-get" @@ -39,6 +41,10 @@ class OperatorRequest: if self.action in {"reload", "restart"}: if self.target not in SERVICES: raise ValueError("Choose a managed service.") + elif self.action == "system-backup": + from .system_backup import archive_id + + archive_id(self.target) elif self.target: raise ValueError("This operation does not use a service target.") if self.action == "package-upgrade": @@ -117,6 +123,10 @@ def packages(request): raise ValueError( "The package plan changed. Collect and review a new preview." ) + if plan["count"] > len(plan["packages"]): + raise ValueError( + "Review this package update from the server console." + ) if plan["count"]: command( APT, @@ -167,6 +177,18 @@ def apply_request(request): return packages(request) if request.action == "database-report": return database_report() + if request.action == "server-tls": + from .server_tls import server_tls_report + + return server_tls_report() + if request.action == "system-backup": + if os.environ.get("COULOBRE_SYSTEM_BACKUPS") != "1": + raise ValueError( + "Enable system backups in the host configuration." + ) + from .system_backup import create_backup + + return create_backup(request.target) with locked_root_directory(STATE): service = SERVICES[request.target] command("/usr/bin/systemctl", request.action, service) @@ -175,6 +197,19 @@ def apply_request(request): def main(): - return serve_apply_request( - 1, OperatorRequest.from_manifest, apply_request, include_result=True - ) + from .http_defaults import HttpDefaultsRequest, apply_http_defaults + + def parse(payload): + if ( + isinstance(payload, dict) + and payload.get("operation") == "http-defaults" + ): + return HttpDefaultsRequest.from_manifest(payload) + return OperatorRequest.from_manifest(payload) + + def apply(request): + if isinstance(request, HttpDefaultsRequest): + return apply_http_defaults(request) + return apply_request(request) + + return serve_apply_request(1, parse, apply, include_result=True) diff --git a/src/coulobre/server_tls.py b/src/coulobre/server_tls.py new file mode 100644 index 0000000..4a7ec79 --- /dev/null +++ b/src/coulobre/server_tls.py @@ -0,0 +1,91 @@ +import os +import re +import subprocess +from urllib.parse import urlsplit + +from cryptography import x509 + +from .domain_names import canonical_domain + +FIRST_CERTIFICATE = re.compile( + b"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", re.DOTALL +) + + +def server_tls_report(): + origin = os.environ.get("COULOBRE_PASSWORD_RESET_ORIGIN", "") + try: + panel = urlsplit(origin) + panel_hostname = panel.hostname + except ValueError: + panel_hostname = None + endpoints = ( + ("panel", panel_hostname, 443, ()), + ("mail-imap", os.environ.get("COULOBRE_MAIL_IMAP_HOST"), 993, ()), + ( + "mail-smtp", + os.environ.get("COULOBRE_MAIL_SUBMISSION_HOST"), + 587, + ("-starttls", "smtp"), + ), + ) + return { + "endpoints": [ + inspect_local_tls(service, hostname, port, extra) + for service, hostname, port, extra in endpoints + ] + } + + +def inspect_local_tls(service, hostname, port, extra): + base = {"service": service, "status": "unavailable", "port": port} + if not hostname: + return base + try: + hostname = canonical_domain(hostname) + result = subprocess.run( + ( + "/usr/bin/openssl", + "s_client", + "-connect", + f"127.0.0.1:{port}", + "-servername", + hostname, + "-showcerts", + *extra, + ), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=False, + timeout=5, + env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"}, + ) + certificate = FIRST_CERTIFICATE.search(result.stdout) + if certificate is None: + return base | {"hostname": hostname} + leaf = x509.load_pem_x509_certificate(certificate[0]) + names = leaf.extensions.get_extension_for_class( + x509.SubjectAlternativeName + ).value.get_values_for_type(x509.DNSName) + except ( + OSError, + ValueError, + x509.ExtensionNotFound, + subprocess.TimeoutExpired, + ): + return base + return base | { + "status": "presented", + "hostname": hostname, + "issuer": leaf.issuer.rfc4514_string()[:350], + "expires": leaf.not_valid_after_utc.isoformat(), + "name_matches": any(matches_name(hostname, name) for name in names), + } + + +def matches_name(hostname, name): + name = name.lower() + if name.startswith("*."): + return hostname.partition(".")[2] == name[2:] + return name == hostname diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index b2228c4..435f3ac 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -218,10 +218,12 @@ except ValueError as error: LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1" WEBSITE_USAGE = os.environ.get("COULOBRE_WEBSITE_USAGE") == "1" +WEBSITE_WILDCARD_CERTIFICATES = os.environ.get("COULOBRE_ACME_DNS_01") == "1" LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1" WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1" WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1" LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1" +SYSTEM_BACKUPS = os.environ.get("COULOBRE_SYSTEM_BACKUPS") == "1" LOCAL_FOLDER_SFTP = ( LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1" ) @@ -479,3 +481,10 @@ if LOCAL_ACCOUNT_BACKUPS and OFFSITE_BACKUP_DESTINATIONS: "schedule": 15.0, "options": {"expires": 14.0}, } + +if SYSTEM_BACKUPS: + CELERY_BEAT_SCHEDULE["dispatch-system-backups"] = { + "task": "coulobre.hosting.tasks.dispatch_system_backups", + "schedule": 60.0, + "options": {"expires": 55.0}, + } diff --git a/src/coulobre/system_backup.py b/src/coulobre/system_backup.py new file mode 100644 index 0000000..1eaeacb --- /dev/null +++ b/src/coulobre/system_backup.py @@ -0,0 +1,322 @@ +import argparse +import hashlib +import json +import os +import re +import subprocess +import tarfile +from datetime import UTC, datetime +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path, PurePosixPath +from tempfile import TemporaryDirectory +from uuid import UUID, uuid4 + +from .node_files import ( + check_root_file, + locked_root_directory, + read_root_file, + replace_configuration, + require_root_directory, +) + +STATE = Path("/var/lib/coulobre/system-backups") +MYSQL_SOCKET = "/run/mysqld/mysqld.sock" +ENVIRONMENT = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} +MANIFEST = "recovery/manifest.json" +SCHEMA = 1 +HOST_PATHS = ( + "etc/coulobre", + "etc/apache2", + "etc/php", + "etc/mysql", + "etc/postfix", + "etc/dovecot", + "etc/rspamd", + "etc/bind", + "etc/letsencrypt", + "etc/ssh/coulobre-authorized-keys", + "etc/ssh/sshd_config.d", + "etc/systemd/system", + "var/lib/coulobre/web-node", + "var/lib/coulobre/database-node", + "var/lib/coulobre/mail-node", + "var/lib/coulobre-vacation", + "var/lib/coulobre-mail", + "srv/coulobre/web", + "srv/coulobre-mail", + "var/lib/coulobre/account-backups", +) +ARCHIVE_NAME = re.compile(r"backup-([0-9a-f-]{36})[.]tar[.]gz") + + +def archive_id(value): + try: + canonical = str(UUID(value)) + except (ValueError, TypeError, AttributeError): + raise ValueError("Choose a valid system backup ID.") from None + if value != canonical: + raise ValueError("Choose a canonical system backup ID.") + return canonical + + +def archive_paths(identifier): + name = f"backup-{archive_id(identifier)}" + return STATE / f"{name}.tar.gz", STATE / f"{name}.json" + + +def run(*arguments, stdout=subprocess.DEVNULL, timeout=900): + try: + subprocess.run( + arguments, + env=ENVIRONMENT, + timeout=timeout, + stdin=subprocess.DEVNULL, + stdout=stdout, + check=True, + ) + except subprocess.TimeoutExpired: + raise ValueError("The system backup operation timed out.") from None + except subprocess.CalledProcessError: + raise ValueError( + "The system backup command failed. Check the service journal." + ) from None + + +def hash_archive(archive): + with archive.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +def check_archive_record(archive, record_path, *, contents=False): + check_root_file(archive, mode=0o600) + report = json.loads(read_root_file(record_path, mode=0o600)) + if ( + not isinstance(report, dict) + or report.get("archive") != archive.name + or report.get("bytes") != archive.stat().st_size + or not re.fullmatch(r"[a-f0-9]{64}", str(report.get("sha256", ""))) + or contents + and report["sha256"] != hash_archive(archive) + ): + raise ValueError( + "The system backup record does not match its archive." + ) + return report + + +def release_version(): + try: + return version("coulobre-panel") + except PackageNotFoundError: + return "source checkout" + + +def save_identities(destination): + for database in ("passwd", "group"): + result = subprocess.run( + ("/usr/bin/getent", database), + env=ENVIRONMENT, + capture_output=True, + timeout=10, + check=True, + ) + managed = [ + line + for line in result.stdout.decode("utf-8").splitlines() + if line.split(":", 1)[0].startswith(("coulobre", "cbf-")) + ] + (destination / database).write_text( + "\n".join(managed) + "\n", encoding="utf-8" + ) + + +def create_backup(identifier): + if os.geteuid() != 0: + raise ValueError("Run system backups as root.") + archive, record = archive_paths(identifier) + try: + keep = int(os.environ.get("COULOBRE_SYSTEM_BACKUP_KEEP", "7")) + except ValueError: + keep = 0 + if not 1 <= keep <= 30: + raise ValueError( + "Set system backup retention between 1 and 30 archives." + ) + require_root_directory(STATE.parent, create_mode=0o750) + require_root_directory(STATE, create_mode=0o700) + with locked_root_directory(STATE): + if record.exists(): + return check_archive_record(archive, record) + if archive.exists(): + check_root_file(archive, mode=0o600) + archive.unlink() + sources = [ + source for source in HOST_PATHS if os.path.lexists("/" + source) + ] + with TemporaryDirectory(prefix=".snapshot-", dir=STATE) as temporary: + workspace = Path(temporary) + recovery = workspace / "recovery" + recovery.mkdir(mode=0o700) + manifest = { + "created_at": datetime.now(UTC).isoformat(), + "schema": SCHEMA, + "release": release_version(), + "root_paths": sources, + } + (workspace / MANIFEST).write_text( + json.dumps(manifest), encoding="utf-8" + ) + save_identities(recovery) + dump = recovery / "mariadb.sql" + with dump.open("xb") as target: + run( + "/usr/bin/mariadb-dump", + "--protocol=socket", + "--user=root", + f"--socket={MYSQL_SOCKET}", + "--all-databases", + "--single-transaction", + "--quick", + "--routines", + "--events", + "--triggers", + "--hex-blob", + stdout=target, + ) + if not dump.stat().st_size: + raise ValueError("The MariaDB recovery dump is empty.") + staged = workspace / "archive.tar.gz" + run( + "/usr/bin/tar", + "--create", + "--gzip", + f"--file={staged}", + "--numeric-owner", + "--exclude=*.sock", + "--one-file-system", + "-C", + temporary, + "recovery", + "-C", + "/", + *sources, + timeout=1200, + ) + staged.chmod(0o600) + report = { + "archive": archive.name, + "bytes": staged.stat().st_size, + "sha256": hash_archive(staged), + "created_at": manifest["created_at"], + } + with staged.open("rb") as source: + os.fsync(source.fileno()) + staged.replace(archive) + replace_configuration(record, json.dumps(report), mode=0o600) + expire_backups(archive, keep) + return report + + +def expire_backups(current, keep): + archives = [] + for path in STATE.iterdir(): + name = ARCHIVE_NAME.fullmatch(path.name) + if name and path != current: + try: + archive, record = archive_paths(name[1]) + if record.exists(): + report = check_archive_record(archive, record) + created = datetime.fromisoformat(report["created_at"]) + archives.append((created, archive, record)) + except (OSError, KeyError, TypeError, ValueError): + continue + for _, archive, record in sorted(archives, reverse=True)[keep - 1 :]: + archive.unlink() + record.unlink() + + +def package_path(name): + path = PurePosixPath(name) + if ( + not path.parts + or path.is_absolute() + or ".." in path.parts + or str(path) != name + or not any( + name == root or name.startswith(root + "/") + for root in (*HOST_PATHS, "recovery") + ) + ): + raise ValueError( + "The archive contains a path outside its recovery scope." + ) + return path + + +def stage_recovery(identifier): + if os.geteuid() != 0: + raise ValueError("Stage system recovery as root.") + archive, record = archive_paths(identifier) + destination = STATE / f"recovery-{archive_id(identifier)}" + with locked_root_directory(STATE): + if os.path.lexists(destination): + raise ValueError("A recovery staging directory already exists.") + check_archive_record(archive, record, contents=True) + with TemporaryDirectory(prefix=".restore-", dir=STATE) as temporary: + staging = Path(temporary) / "data" + staging.mkdir(mode=0o700) + links = [] + special = [] + with tarfile.open(archive, "r:gz") as snapshot: + source = snapshot.extractfile(MANIFEST) + if source is None: + raise ValueError("The system backup manifest is missing.") + manifest = json.loads(source.read(16385)) + if ( + not isinstance(manifest, dict) + or manifest.get("schema") != SCHEMA + ): + raise ValueError( + "The recovery archive uses an unsupported format." + ) + for member in snapshot: + path = package_path(member.name) + if member.isfile() or member.isdir(): + snapshot.extract(member, staging, filter="data") + elif member.issym() or member.islnk(): + links.append( + { + "path": str(path), + "target": member.linkname, + "type": "symlink" + if member.issym() + else "hardlink", + } + ) + else: + special.append(str(path)) + (staging / "recovery-special-files.json").write_text( + json.dumps(special, indent=2), encoding="utf-8" + ) + (staging / "recovery-links.json").write_text( + json.dumps(links, indent=2), encoding="utf-8" + ) + staging.replace(destination) + return destination + + +def main(argv=None): + parser = argparse.ArgumentParser(description="Coulobre system recovery") + parser.add_argument("action", choices=("create", "stage")) + parser.add_argument("backup_id", nargs="?") + args = parser.parse_args(argv) + try: + if args.action == "create": + print(json.dumps(create_backup(args.backup_id or str(uuid4())))) + elif args.backup_id: + print(stage_recovery(args.backup_id)) + else: + parser.error("Choose the backup ID to stage.") + except (OSError, ValueError, tarfile.TarError) as error: + parser.exit(1, f"coulobre-system-backup: {error}\n") + return 0 diff --git a/src/coulobre/web_certificates.py b/src/coulobre/web_certificates.py index d9ffdf8..535673c 100644 --- a/src/coulobre/web_certificates.py +++ b/src/coulobre/web_certificates.py @@ -1,5 +1,6 @@ import fcntl import os +import re import shutil from dataclasses import dataclass, field from pathlib import Path @@ -51,10 +52,32 @@ class WebCertificateRequest: action: str chain: str = field(default="", repr=False) key: str = field(default="", repr=False) + wildcard: bool = False + email: str = "" def __post_init__(self): if self.action not in ACTIONS: raise ValueError("Choose a supported certificate operation.") + if ( + type(self.wildcard) is not bool + or not isinstance(self.email, str) + or ( + self.email + and ( + len(self.email) > 254 + or not re.fullmatch( + r"[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+", self.email + ) + ) + ) + or ( + (self.wildcard or self.email) + and self.action not in {"issue", "reissue"} + ) + ): + raise ValueError( + "Choose supported ACME contact and challenge settings." + ) if self.action == "upload": check_pem_size(self.chain, MAX_CERTIFICATE_BYTES) check_pem_size(self.key, MAX_KEY_BYTES) @@ -66,7 +89,11 @@ class WebCertificateRequest: "operation": "manage_certificate", "site": self.site.manifest(), "action": self.action, - } + } | ( + {"wildcard": self.wildcard, "email": self.email} + if self.wildcard or self.email + else {} + ) def manifest(self): return self.identity() | ( @@ -80,6 +107,8 @@ class WebCertificateRequest: fields = {"operation", "site", "action"} if data.get("action") == "upload": fields |= {"chain", "key"} + if "wildcard" in data or "email" in data: + fields |= {"wildcard", "email"} if data.keys() != fields: raise ValueError("Expected a certificate operation.") return cls( @@ -87,6 +116,8 @@ class WebCertificateRequest: data["action"], data.get("chain", ""), data.get("key", ""), + data.get("wildcard", False), + data.get("email", ""), ) @@ -176,10 +207,12 @@ def apply_website_certificate(request): if os.geteuid() != 0: raise ValueError("Run certificate management as root on the web node.") site = request.site - if request.action == "issue": + if request.action == "issue" and not (request.wildcard or request.email): provision_https(site) - elif request.action == "reissue": - reissue_certificate(site) + elif request.action in {"issue", "reissue"}: + reissue_certificate( + site, wildcard=request.wildcard, email=request.email + ) elif request.action == "upload": install_uploaded_certificate( site, *validated_pem(request.chain, request.key) @@ -201,7 +234,7 @@ def reload_apache(): run("/usr/sbin/service", "apache2", "reload") -def reissue_certificate(site): +def reissue_certificate(site, *, wildcard=False, email=""): with locked_web_node(fcntl.LOCK_EX): paths = SitePaths.for_site(site) check_https_prerequisites(site, paths) @@ -217,7 +250,9 @@ def reissue_certificate(site): if (path := lineage / f"{name}.pem").is_symlink() } try: - request_certificate(site, force=True) + request_certificate( + site, force=True, wildcard=wildcard, email=email + ) apache, enabled = https_paths(paths) install_https_configuration( site, apache, enabled, socket_path=paths.apache_socket diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index f9dd743..a656014 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -22,6 +22,7 @@ from .web_node_apply import ( CERTBOT_ROOT = Path("/etc/letsencrypt") ACME_WEBROOT = Path("/var/www/coulobre-acme") +ACME_DNS_HOOKS = Path("/etc/coulobre/acme-dns") def provision_https(site): @@ -60,19 +61,38 @@ def ensure_certificate(site): request_certificate(site) -def request_certificate(site, *, force=False): +def request_certificate(site, *, force=False, wildcard=False, email=""): + challenge = ("--webroot", "--webroot-path", str(ACME_WEBROOT)) + names = ("--domains", site.domain) + if wildcard: + require_root_directory(ACME_DNS_HOOKS) + auth, cleanup = (ACME_DNS_HOOKS / name for name in ("auth", "cleanup")) + for hook in (auth, cleanup): + check_root_file(hook) + if not os.access(hook, os.X_OK): + raise ValueError( + "Provide executable DNS-01 hooks on the web node." + ) + challenge = ( + "--manual", + "--preferred-challenges", + "dns", + "--manual-auth-hook", + str(auth), + "--manual-cleanup-hook", + str(cleanup), + ) + names += ("--domains", f"*.{site.domain}") command = ( "/usr/bin/certbot", "certonly", "--non-interactive", "--force-renewal" if force else "--keep-until-expiring", - "--webroot", - "--webroot-path", - str(ACME_WEBROOT), + *challenge, "--cert-name", certbot_lineage(site).name, - "--domains", - site.domain, + *names, + *((f"--email={email}",) if email else ()), ) try: subprocess.run(