From fd2bdb8a185807d7f58d020b11fb07fddb4ad67e Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 22:09:27 +0100 Subject: [PATCH 1/9] Establish role workspaces and customer onboarding --- docs/deployment.md | 12 +- docs/security.md | 2 +- src/coulobre/hosting/access.py | 59 ++- .../hosting/account_administration.py | 353 ++++++++++++++++++ src/coulobre/hosting/account_backups.py | 6 +- src/coulobre/hosting/customer_backup_views.py | 67 ++++ src/coulobre/hosting/installation_views.py | 17 +- src/coulobre/hosting/invitations.py | 8 +- .../migrations/0060_welcome_message.py | 17 + src/coulobre/hosting/models.py | 2 + src/coulobre/hosting/panel_roles.py | 21 +- src/coulobre/hosting/reseller_views.py | 6 +- src/coulobre/hosting/static/hosting/panel.css | 26 ++ .../templates/hosting/account_detail.html | 2 +- .../templates/hosting/account_retirement.html | 2 +- .../hosting/templates/hosting/all_users.html | 22 ++ .../hosting/templates/hosting/base.html | 85 +---- .../templates/hosting/customer_backups.html | 19 + .../templates/hosting/installation.html | 5 +- .../templates/hosting/manager_packages.html | 11 + .../templates/hosting/panel_invitation.txt | 4 +- .../templates/hosting/reseller_detail.html | 4 +- .../templates/hosting/reseller_form.html | 6 +- .../templates/hosting/reseller_list.html | 12 +- .../hosting/reseller_profile_form.html | 2 +- .../hosting/reseller_profile_list.html | 6 +- .../templates/hosting/system_workspace.html | 16 + .../templates/hosting/workspace_form.html | 21 ++ .../hosting/workspace_navigation.html | 8 + src/coulobre/hosting/test_service_health.py | 4 +- src/coulobre/hosting/test_workspaces.py | 122 ++++++ src/coulobre/hosting/urls.py | 33 ++ src/coulobre/hosting/views.py | 2 +- src/coulobre/hosting/workspaces.py | 227 +++++++++++ 34 files changed, 1061 insertions(+), 148 deletions(-) create mode 100644 src/coulobre/hosting/account_administration.py create mode 100644 src/coulobre/hosting/customer_backup_views.py create mode 100644 src/coulobre/hosting/migrations/0060_welcome_message.py create mode 100644 src/coulobre/hosting/templates/hosting/all_users.html create mode 100644 src/coulobre/hosting/templates/hosting/customer_backups.html create mode 100644 src/coulobre/hosting/templates/hosting/manager_packages.html create mode 100644 src/coulobre/hosting/templates/hosting/system_workspace.html create mode 100644 src/coulobre/hosting/templates/hosting/workspace_form.html create mode 100644 src/coulobre/hosting/templates/hosting/workspace_navigation.html create mode 100644 src/coulobre/hosting/test_workspaces.py create mode 100644 src/coulobre/hosting/workspaces.py diff --git a/docs/deployment.md b/docs/deployment.md index a5c7238..4057fa8 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -498,12 +498,12 @@ sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat ## Manage panel roles -A verified superuser can assign a Customer or Customer manager role to an -active login from **Customers** or **Customer managers**. Choose **Assign +A verified superuser can assign a Customer or Manager role to an +active login from **Customers** or **Managers**. Choose **Assign to existing login** and enter the username. Customer roles use their own -assigned hosting accounts. Customer managers use their own hosting account +assigned hosting accounts. Managers use their own hosting account assignments and hosting plan policy. New manager assignments use the default -customer manager profile when one is configured. +manager profile when one is configured. Logins with multiple roles can choose **Panel role** in the account area. The role applies to the session, including direct page requests and actions. @@ -784,7 +784,7 @@ loaded as long as any existing managed login uses it. Use the in-place procedure above with the v0.10 source release. Keep a copy of the v0.9 release and a matching database and configuration backup for -rollback. The upgrade adds tables for invitations and customer manager +rollback. The upgrade adds tables for invitations and manager profiles, and initializes the new web setup flags without running provisioning for existing accounts. @@ -1273,7 +1273,7 @@ sudo systemctl enable --now coulobre-database-provisioner.service ``` Select **Add database** on a hosting account to queue its provisioning. -Customers can add databases on their own accounts. Customer managers need +Customers can add databases on their own accounts. Managers need permission to manage resources for their assigned accounts. For a pending request, an operator can select **Provision database**. Operators need permission to view hosting accounts and databases and the **Can add database diff --git a/docs/security.md b/docs/security.md index b1ae06d..b159fe0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -18,7 +18,7 @@ after users have a way to update. - Serve the panel over HTTPS. If you use a reverse proxy, restrict the private origin to that proxy and let the managed Apache configuration set the forwarding headers. Keep debug mode off on shared or public hosts. -- Require two-factor authentication for staff and customer managers. Use an +- Require two-factor authentication for staff and managers. Use an authenticator app for administrative accounts and keep recovery codes in a protected location. The **My account** page lets users verify a new email address, replace their authenticator, renew recovery codes, and revoke diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 14515f2..0525105 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -7,21 +7,6 @@ class PanelRole(StrEnum): CUSTOMER = "customer" -NAVIGATION_SECTIONS = { - "accounts": "accounts", - "retired-accounts": "accounts", - "databases": "accounts", - "dns-zones": "accounts", - "mailboxes": "accounts", - "mail-domains": "accounts", - "customers": "customers", - "resellers": "resellers", - "hosting-plans": "hosting_plans", - "plans": "plans", - "service-health": "service_health", -} - - def customer_for_user(user): role = getattr(user, "panel_role", None) if role is not None and role != PanelRole.CUSTOMER: @@ -62,33 +47,37 @@ def manages_account(user, account): 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 - match = request.resolver_match - section = None - if match is not None and match.namespace == "panel": - section = NAVIGATION_SECTIONS.get( - match.route.split("/", 1)[0], match.url_name - ) + from .workspaces import CUSTOMER_ACCOUNT, groups_for, workspace_accounts + operator = request.user.is_authenticated and not (customer or reseller) - grouped = reseller or ( - operator - and sum( - request.user.has_perm(f"hosting.view_{resource}") - for resource in ( - "hostingaccount", - "customer", - "reseller", - "hostingplan", - ) - ) - > 1 + groups = groups_for(request, customer=customer, manager=reseller) + current = next( + ( + label + for label, links in groups + if any(url == request.path for url, _ in links) + ), + "", ) + selected = request.session.get(CUSTOMER_ACCOUNT) + available = [] + if customer and not getattr(request, "impersonation", None): + available = list( + workspace_accounts(request.user) + .only("id", "primary_domain") + .order_by("primary_domain") + ) + if available and selected not in {account.pk for account in available}: + selected = available[0].pk return { "is_customer": customer, "is_reseller": reseller, "is_tenant": customer or reseller, "is_operator": operator, - "group_customer_navigation": grouped, - "panel_section": section, + "navigation_groups": groups, + "open_workspace_group": current, + "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 new file mode 100644 index 0000000..91be61c --- /dev/null +++ b/src/coulobre/hosting/account_administration.py @@ -0,0 +1,353 @@ +from django import forms +from django.contrib import messages +from django.contrib.admin.models import ADDITION, LogEntry +from django.contrib.auth import get_user_model, password_validation +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.mixins import ( + PermissionRequiredMixin, + UserPassesTestMixin, +) +from django.core.exceptions import ValidationError +from django.db import IntegrityError, transaction +from django.db.models import Count, Q +from django.shortcuts import redirect +from django.urls import reverse_lazy +from django.views.generic import FormView, ListView + +from coulobre.domain_names import canonical_domain + +from .access import OperatorOnlyMixin, reseller_for_user +from .account_setup import setup_new_account +from .dns_defaults import zone_defaults +from .installation_features import ( + default_dns_zones_allowed, + panel_feature_allowed, +) +from .invitations import InviteLoginForm, queue_invitation +from .models import Customer, HostingAccount, HostingPlan, Reseller +from .reseller_accounts import ( + create_reseller_account, + lock_resellers, + save_operator_account, +) +from .resource_requests import lock_hosting_account, require_open_account + + +class ManagerOnboardingForm(InviteLoginForm): + primary_domain = HostingAccount._meta.get_field( + "primary_domain" + ).formfield(required=True) + plan = forms.ModelChoiceField( + queryset=HostingPlan.objects.none(), label="Hosting plan" + ) + manage_dns = forms.BooleanField( + required=False, label="Manage DNS in Coulobre" + ) + manage_mail = forms.BooleanField( + required=False, label="Manage email in Coulobre" + ) + send_invitation = forms.BooleanField( + required=False, initial=True, label="Send a welcome email" + ) + welcome_message = forms.CharField( + required=False, + max_length=2000, + widget=forms.Textarea(attrs={"rows": 3}), + label="Message to include in the welcome email", + ) + initial_password = forms.CharField( + required=False, + strip=False, + max_length=256, + widget=forms.PasswordInput, + label="Initial password", + help_text="Leave blank to use a password setup link.", + ) + + def __init__(self, *args, manager, defaults, **kwargs): + super().__init__(*args, **kwargs) + self.fields["plan"].queryset = manager.hosting_plans.order_by("name") + self.fields["manage_dns"].disabled = not default_dns_zones_allowed( + defaults + ) + self.fields["manage_mail"].disabled = not panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" + ) + + def clean_primary_domain(self): + try: + domain = canonical_domain(self.cleaned_data["primary_domain"]) + except ValueError as error: + raise ValidationError(str(error)) from error + if HostingAccount.objects.filter(primary_domain=domain).exists(): + raise ValidationError( + "This domain already belongs to a hosting account." + ) + return domain + + def clean(self): + cleaned = super().clean() + password = cleaned.get("initial_password") + if password: + if cleaned.get("send_invitation"): + self.add_error( + "initial_password", + "The welcome email uses a password setup link. Leave " + "this field blank to send it.", + ) + try: + password_validation.validate_password(password, self.instance) + except ValidationError as error: + self.add_error("initial_password", error) + return cleaned + + +class ManagerOnboardingView(UserPassesTestMixin, FormView): + form_class = ManagerOnboardingForm + template_name = "hosting/workspace_form.html" + extra_context = { + "title": "Add a new user", + "submit_label": "Create customer and hosting account", + "invitation_preview": True, + } + + def test_func(self): + self.manager = reseller_for_user(self.request.user) + return self.manager is not None + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "manager": self.manager, + "defaults": zone_defaults(), + } + + def form_valid(self, form): + data = form.cleaned_data + try: + with transaction.atomic(): + user = form.save(commit=False) + if data["initial_password"]: + user.set_password(data["initial_password"]) + user.save() + customer = Customer.objects.create( + user=user, reseller=self.manager + ) + account = HostingAccount( + name=user.get_username(), + primary_domain=data["primary_domain"], + customer=customer, + hosting_plan=data["plan"], + ) + create_reseller_account(self.manager, account) + defaults = zone_defaults() + setup_new_account( + account, + { + "setup_website": panel_feature_allowed( + "LOCAL_WEB_ACTIVATION" + ), + "setup_dns": data["manage_dns"], + "setup_email": data["manage_mail"], + "setup_www": defaults.include_www, + "setup_wildcard": defaults.include_wildcard, + }, + ) + if data["send_invitation"]: + queue_invitation( + user, welcome_message=data["welcome_message"] + ) + except ValidationError as error: + form.add_error(None, ValidationError(error.messages)) + return self.form_invalid(form) + except IntegrityError: + if not ( + HostingAccount.objects.filter( + primary_domain=data["primary_domain"] + ).exists() + or get_user_model() + .objects.filter(username__iexact=data["username"]) + .exists() + ): + raise + form.add_error(None, "The username or domain is already in use.") + return self.form_invalid(form) + messages.success( + self.request, "The customer and hosting account were created." + ) + return redirect(account) + + +class ManagerPackagesView(UserPassesTestMixin, ListView): + template_name = "hosting/manager_packages.html" + context_object_name = "plans" + + def test_func(self): + self.manager = reseller_for_user(self.request.user) + return self.manager is not None + + def get_queryset(self): + return self.manager.hosting_plans.order_by("name") + + +class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView): + permission_required = "hosting.view_customer" + template_name = "hosting/all_users.html" + context_object_name = "logins" + paginate_by = 40 + + def get_queryset(self): + profiles = [Q(hosting_customer__isnull=False)] + if self.request.user.has_perm("hosting.view_reseller"): + profiles.append( + Q(hosting_reseller__isnull=False, is_superuser=False) + ) + if self.request.user.is_superuser: + profiles.append(Q(is_superuser=True)) + scope = Q() + for profile in profiles: + scope |= profile + return ( + get_user_model() + .objects.filter(scope) + .filter(username__icontains=self.request.GET.get("q", "")[:150]) + .select_related( + "hosting_customer__reseller__user", "hosting_reseller" + ) + .annotate( + account_count=Count( + "hosting_customer__hostingaccount", + filter=Q( + hosting_customer__hostingaccount__retired_at__isnull=True + ), + distinct=True, + ) + ) + .order_by("username") + ) + + +class OperatorAuthorization(UserPassesTestMixin): + def test_func(self): + user = self.request.user + return user.is_superuser and user.is_verified() + + +class OperatorLoginForm(UserCreationForm): + email = forms.EmailField() + + class Meta(UserCreationForm.Meta): + fields = ("username", "email") + + +class OperatorCreateView(OperatorAuthorization, FormView): + form_class = OperatorLoginForm + template_name = "hosting/workspace_form.html" + success_url = reverse_lazy("panel:all_users") + extra_context = { + "title": "Add an operator", + "submit_label": "Create operator", + } + + @transaction.atomic + def form_valid(self, form): + user = form.save(commit=False) + user.is_staff = user.is_superuser = True + user.save() + from .panel_roles import ensure_operator_manager + + ensure_operator_manager(user) + LogEntry.objects.log_actions( + self.request.user.pk, [user], ADDITION, "Created panel operator." + ) + return super().form_valid(form) + + +class MoveHostingForm(forms.Form): + account = forms.ModelChoiceField( + queryset=HostingAccount.objects.filter( + retired_at__isnull=True + ).select_related("reseller__user") + ) + manager = forms.ModelChoiceField( + queryset=Reseller.objects.filter(user__is_active=True).select_related( + "user" + ) + ) + confirm = forms.BooleanField( + label="I reviewed the destination and its hosting plan policy" + ) + + +class MoveHostingView(OperatorAuthorization, FormView): + form_class = MoveHostingForm + template_name = "hosting/workspace_form.html" + extra_context = { + "title": "Move hosting to another manager", + "submit_label": "Move hosting account", + } + + def form_valid(self, form): + chosen = form.cleaned_data["manager"] + try: + with transaction.atomic(): + account = lock_hosting_account( + form.cleaned_data["account"].pk, customer_id=None + ) + require_open_account(account) + if account.reseller_id == chosen.pk: + raise ValidationError("Choose a different manager.") + managers = lock_resellers( + Reseller.objects.filter( + pk__in=[chosen.pk, account.reseller_id] + ) + ).select_related("user") + destination = next( + ( + manager + for manager in managers + if manager.pk == chosen.pk + ), + None, + ) + if destination is None or not destination.user.is_active: + raise ValidationError( + "The destination is no longer available." + ) + if ( + destination.hostingaccount_set.filter( + retired_at__isnull=True + ).count() + >= destination.account_limit + or not destination.hosting_plans.filter( + pk=account.hosting_plan_id + ).exists() + ): + raise ValidationError( + "The destination must have room and allow this plan." + ) + customer_id = account.customer_id + if customer_id is not None: + customer = Customer.objects.select_for_update().get( + pk=customer_id + ) + if ( + customer.hostingaccount_set.exclude(pk=account.pk) + .filter(retired_at__isnull=True) + .exists() + ): + raise ValidationError( + "This customer has other active hosting accounts. " + "Move them together when changing their manager." + ) + customer.reseller = destination + customer.save(update_fields=["reseller"]) + account.reseller = destination + save_operator_account( + account, + self.request.user.get_username(), + changed_fields=["reseller"], + ) + except ValidationError as error: + form.add_error(None, ValidationError(error.messages)) + return self.form_invalid(form) + return redirect(account) diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index c66e447..d6c4c70 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -41,8 +41,10 @@ def account_backup_manifest(account, *, include_mailboxes=False): @transaction.atomic -def queue_account_backup(account_id, *, include_mailboxes=False): - account = lock_hosting_account(account_id, customer_id=None) +def queue_account_backup( + account_id, *, include_mailboxes=False, customer_id=None +): + account = lock_hosting_account(account_id, customer_id=customer_id) require_open_account(account) _enqueue_backup(account, include_mailboxes=include_mailboxes) diff --git a/src/coulobre/hosting/customer_backup_views.py b/src/coulobre/hosting/customer_backup_views.py new file mode 100644 index 0000000..239717d --- /dev/null +++ b/src/coulobre/hosting/customer_backup_views.py @@ -0,0 +1,67 @@ +from django import forms +from django.contrib import messages +from django.contrib.auth.mixins import UserPassesTestMixin +from django.core.exceptions import ValidationError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.utils.functional import cached_property +from django.views.generic import FormView + +from .access import customer_for_user +from .account_backups import mail_backups_enabled, queue_account_backup +from .installation_features import panel_feature_allowed +from .models import HostingAccount + + +class CustomerBackupForm(forms.Form): + include_mailboxes = forms.BooleanField( + required=False, label="Include mailboxes" + ) + + +class CustomerBackupView(UserPassesTestMixin, FormView): + template_name = "hosting/customer_backups.html" + form_class = CustomerBackupForm + + def test_func(self): + return customer_for_user(self.request.user) is not None + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount, + pk=self.kwargs["pk"], + retired_at__isnull=True, + customer=customer_for_user(self.request.user), + ) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + form.fields["include_mailboxes"].disabled = not mail_backups_enabled() + return form + + def get_context_data(self, **kwargs): + return super().get_context_data( + account=self.account, + backups=self.account.backup_jobs.order_by("-requested_at")[:30], + may_create=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"), + **kwargs, + ) + + def form_valid(self, form): + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): + raise Http404 + customer = customer_for_user(self.request.user) + try: + queue_account_backup( + self.account.pk, + include_mailboxes=form.cleaned_data["include_mailboxes"], + customer_id=customer.pk, + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + messages.success(self.request, "Backup requested.") + return redirect("panel:customer_backups", pk=self.account.pk) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 9e73056..254b8ce 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -3,10 +3,7 @@ from importlib.metadata import PackageNotFoundError, version from django import forms from django.contrib import messages from django.contrib.admin.models import CHANGE, LogEntry -from django.contrib.auth.mixins import ( - PermissionRequiredMixin, - UserPassesTestMixin, -) +from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.db import transaction from django.db.models import F from django.urls import reverse_lazy @@ -14,17 +11,14 @@ from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import FormView, TemplateView -from .access import OperatorOnlyMixin +from .access import is_tenant from .installation_features import FEATURES, FeaturePolicy from .models import PanelFeaturePolicy from .update_views import inspect_linked_nodes @method_decorator(never_cache, name="dispatch") -class InstallationView( - OperatorOnlyMixin, PermissionRequiredMixin, TemplateView -): - permission_required = "hosting.view_servicehealth" +class InstallationView(LoginRequiredMixin, TemplateView): template_name = "hosting/installation.html" def get_context_data(self, **kwargs): @@ -34,7 +28,10 @@ class InstallationView( installed_version = "Unavailable" policy = FeaturePolicy() features = [] - for feature in FEATURES: + may_view = not is_tenant( + self.request.user + ) and self.request.user.has_perm("hosting.view_servicehealth") + for feature in FEATURES if may_view else (): configured = feature.configured enabled = ( configured diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py index 02c0499..ca35aa1 100644 --- a/src/coulobre/hosting/invitations.py +++ b/src/coulobre/hosting/invitations.py @@ -103,7 +103,7 @@ invitation_token = InvitationToken() @transaction.atomic -def queue_invitation(user): +def queue_invitation(user, *, welcome_message=None): user = lock_user(user.pk) if not may_accept_invitation(user): return None @@ -113,6 +113,11 @@ def queue_invitation(user): "revision": uuid.uuid4(), "created_at": timezone.now(), "delivery": PanelInvitation.Delivery.PENDING, + **( + {"welcome_message": welcome_message} + if welcome_message is not None + else {} + ), }, ) if not reset_enabled(): @@ -178,6 +183,7 @@ def deliver_invitation(invitation_id, revision): "hosting/panel_invitation.txt", { "username": user.get_username(), + "welcome_message": invitation.welcome_message, "setup_url": origin + path, "panel_url": origin + "/", "account": account, diff --git a/src/coulobre/hosting/migrations/0060_welcome_message.py b/src/coulobre/hosting/migrations/0060_welcome_message.py new file mode 100644 index 0000000..9722938 --- /dev/null +++ b/src/coulobre/hosting/migrations/0060_welcome_message.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0059_panel_feature_policy"), + ] + + operations = [ + migrations.AddField( + model_name="panelinvitation", + name="welcome_message", + field=models.TextField(blank=True, default=""), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index a2c0fc9..4f8e008 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -160,6 +160,8 @@ class Customer(models.Model): class PanelInvitation(models.Model): + welcome_message = models.TextField(blank=True, default="") + class Delivery(models.TextChoices): PENDING = "pending", "Waiting to send" SENT = "sent", "Sent" diff --git a/src/coulobre/hosting/panel_roles.py b/src/coulobre/hosting/panel_roles.py index 04aaff8..c2acc7e 100644 --- a/src/coulobre/hosting/panel_roles.py +++ b/src/coulobre/hosting/panel_roles.py @@ -23,7 +23,7 @@ SESSION_ROLE = "coulobre_panel_role" ROLE_LABELS = { PanelRole.ADMIN: "Server administrator", PanelRole.CUSTOMER: "Customer", - PanelRole.MANAGER: "Customer manager", + PanelRole.MANAGER: "Manager", } @@ -42,6 +42,20 @@ def assigned_roles(user): return roles +def ensure_operator_manager(user): + if not user.is_superuser or hasattr(user, "hosting_reseller"): + return + profile = ResellerProfile.objects.filter(default_slot=1).first() + defaults = {"account_limit": profile.account_limit} if profile else {} + with transaction.atomic(): + manager, created = Reseller.objects.get_or_create( + user=user, defaults=defaults + ) + if created and profile is not None: + manager.hosting_plans.set(profile.hosting_plans.all()) + user.hosting_reseller = manager + + def deny_permission(*args, **kwargs): return False @@ -84,7 +98,9 @@ class PanelRoleMiddleware: def __call__(self, request): response = self.get_response(request) - if getattr(request, "active_panel_role", None): + if getattr( + request, "active_panel_role", None + ) and "no-store" not in response.get("Cache-Control", ""): add_never_cache_headers(response) return response @@ -92,6 +108,7 @@ class PanelRoleMiddleware: if not request.user.is_authenticated: return None user = get_user(request) + ensure_operator_manager(user) roles = assigned_roles(user) selection = request.session.get(SESSION_ROLE) if selection is None: diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py index 384f51a..7ee823f 100644 --- a/src/coulobre/hosting/reseller_views.py +++ b/src/coulobre/hosting/reseller_views.py @@ -163,8 +163,8 @@ class ResellerCreate( form_class = InviteLoginForm template_name = "hosting/reseller_form.html" extra_context = { - "page_title": "Add customer manager", - "submit_label": "Add customer manager", + "page_title": "Add manager", + "submit_label": "Add manager", } @cached_property @@ -220,7 +220,7 @@ class ResellerEdit( form_class = ResellerPolicyForm template_name = "hosting/reseller_form.html" extra_context = { - "page_title": "Edit customer manager", + "page_title": "Edit manager", "submit_label": "Save changes", } diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index f62287a..dfcf4f2 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -1179,3 +1179,29 @@ dd { padding-inline-end: max(var(--page-padding), 3.7rem); } } + +.workspace-context { + margin-bottom: var(--section-gap); +} + +.workspace-context select { + max-width: 100%; +} + +.workspace-list { + margin: 0; + padding: 1rem 1.2rem 1rem 2.3rem; +} + +.workspace-list li + li { + margin-top: 0.4rem; +} + +.sidebar-account .appearance-control { + display: block; + margin: 0.35rem 0; +} + +.sidebar-account .appearance-control[hidden] { + display: none; +} diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a306962..270188c 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -17,7 +17,7 @@
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
{% endif %} {% if is_operator and perms.hosting.view_reseller %} -
Customer manager
{{ account.reseller|default_if_none:"Unassigned" }}
+
Manager
{{ account.reseller|default_if_none:"Unassigned" }}
{% endif %} {% if is_operator and perms.hosting.view_customer %}
Customer
{{ account.customer|default_if_none:"No customer linked" }}
diff --git a/src/coulobre/hosting/templates/hosting/account_retirement.html b/src/coulobre/hosting/templates/hosting/account_retirement.html index 9ebc7fa..8108e60 100644 --- a/src/coulobre/hosting/templates/hosting/account_retirement.html +++ b/src/coulobre/hosting/templates/hosting/account_retirement.html @@ -20,7 +20,7 @@
DNS zones
{% for zone in inventory.zones %}{{ zone.domain }}{% if zone.published is not None %} (published serial {{ zone.published }}){% endif %}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}
Existing backups
{{ inventory.backups }}
{% if inventory.customer %}
Customer
{{ inventory.customer }}
{% endif %} - {% if inventory.reseller %}
Customer manager
{{ inventory.reseller }}
{% endif %} + {% if inventory.reseller %}
Manager
{{ inventory.reseller }}
{% endif %} {% if retirement %} diff --git a/src/coulobre/hosting/templates/hosting/all_users.html b/src/coulobre/hosting/templates/hosting/all_users.html new file mode 100644 index 0000000..b99b68b --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/all_users.html @@ -0,0 +1,22 @@ +{% extends "hosting/base.html" %} +{% block title %}All users · Coulobre Panel{% endblock %} +{% block content %} +

All users

+
+
+ + +
+
+ + + + {% for login in logins %} + + {% empty %}{% endfor %} + +
UserWorkspaceManagerHosting accountsAdded
{{ 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.
+
+ {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index c17a9e7..e6025a7 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -22,74 +22,12 @@ Menu
+ {% if workspace_accounts %} + + + + + + {% endif %} {% if request.impersonation %}
@@ -132,9 +85,9 @@ {% else %} {% block public_content %}{% endblock %} + {% endif %} - diff --git a/src/coulobre/hosting/templates/hosting/customer_backups.html b/src/coulobre/hosting/templates/hosting/customer_backups.html new file mode 100644 index 0000000..49af019 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_backups.html @@ -0,0 +1,19 @@ +{% extends "hosting/base.html" %} +{% block title %}Backup & Restore · Coulobre Panel{% endblock %} +{% block content %} +

Backup & Restore

{{ account.primary_domain }}

+ {% for message in messages %}

{{ message }}

{% endfor %} + {% if may_create %} +
+

Create a backup

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

Recent backups

+
    + {% for backup in backups %}
  • {{ backup.requested_at|date:"j M Y H:i" }} · {% if not backup.finished_at %}Queued{% elif backup.problem %}Failed{% else %}Ready{% endif %}
  • + {% empty %}
  • No backups yet.
  • {% endfor %} +
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/installation.html b/src/coulobre/hosting/templates/hosting/installation.html index af16dc4..195b471 100644 --- a/src/coulobre/hosting/templates/hosting/installation.html +++ b/src/coulobre/hosting/templates/hosting/installation.html @@ -10,9 +10,10 @@
Installed version
{{ installed_version }}
Core software license
Apache License 2.0
+
-
+ {% if features %}

Feature configuration

@@ -45,5 +46,5 @@
-
+
{% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/manager_packages.html b/src/coulobre/hosting/templates/hosting/manager_packages.html new file mode 100644 index 0000000..2e51623 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/manager_packages.html @@ -0,0 +1,11 @@ +{% extends "hosting/base.html" %} +{% block title %}User packages · Coulobre Panel{% endblock %} +{% block content %} +

User packages

+
+
    + {% for plan in plans %}
  • {{ plan.name }}{% if plan.description %}

    {{ plan.description }}

    {% endif %}
  • + {% empty %}
  • No packages have been made available to you.
  • {% endfor %} +
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/panel_invitation.txt b/src/coulobre/hosting/templates/hosting/panel_invitation.txt index 88a5c7a..91e0901 100644 --- a/src/coulobre/hosting/templates/hosting/panel_invitation.txt +++ b/src/coulobre/hosting/templates/hosting/panel_invitation.txt @@ -1,4 +1,6 @@ -Welcome to Coulobre Panel. +{% if welcome_message %}{{ welcome_message }} + +{% endif %}Welcome to Coulobre Panel. Username: {{ username }} Panel: {{ panel_url }} diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index bcad959..4df0dec 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -1,12 +1,12 @@ {% extends "hosting/base.html" %} {% block title %}{{ reseller }} · Coulobre Panel{% endblock %} {% block content %} - ← Customer managers + ← Managers

{{ reseller }}

{% if perms.hosting.change_reseller %} Contact and invitation - Edit customer manager + Edit manager {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_form.html b/src/coulobre/hosting/templates/hosting/reseller_form.html index 9ae0dec..02e92d4 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_form.html +++ b/src/coulobre/hosting/templates/hosting/reseller_form.html @@ -1,14 +1,14 @@ {% extends "hosting/base.html" %} {% block title %}{{ page_title }} · Coulobre Panel{% endblock %} {% block content %} - ← {% if reseller %}{{ reseller }}{% else %}Customer managers{% endif %} + ← {% if reseller %}{{ reseller }}{% else %}Managers{% endif %}

{{ page_title }}

{% if profiles %}
- - {% for profile in profiles %}{% endfor %} diff --git a/src/coulobre/hosting/templates/hosting/reseller_list.html b/src/coulobre/hosting/templates/hosting/reseller_list.html index 7f8b29e..359a0c4 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_list.html @@ -1,8 +1,8 @@ {% extends "hosting/base.html" %} -{% block title %}Customer managers · Coulobre Panel{% endblock %} +{% block title %}Managers · Coulobre Panel{% endblock %} {% block content %}
-

Customer managers

+

Managers

{% if perms.hosting.change_reseller and perms.hosting.view_hostingplan %} Profiles @@ -11,11 +11,11 @@ {% if request.user.is_superuser and request.user.is_verified %} Assign to existing login {% endif %} - Add customer manager + Add manager {% endif %}
-
+
@@ -40,9 +40,9 @@
{% elif search %} -

No customer managers match this search.

+

No managers match this search.

{% else %} -

No customer managers yet.

+

No managers yet.

{% endif %} {% include "hosting/pagination.html" %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_profile_form.html b/src/coulobre/hosting/templates/hosting/reseller_profile_form.html index fbe7961..4c15049 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_profile_form.html +++ b/src/coulobre/hosting/templates/hosting/reseller_profile_form.html @@ -1,7 +1,7 @@ {% extends "hosting/base.html" %} {% block title %}{% if object %}Edit profile{% else %}Add profile{% endif %} · Coulobre Panel{% endblock %} {% block content %} - ← Customer manager profiles + ← Manager profiles

{% if object %}Edit profile{% else %}Add profile{% endif %}

diff --git a/src/coulobre/hosting/templates/hosting/reseller_profile_list.html b/src/coulobre/hosting/templates/hosting/reseller_profile_list.html index d096030..259660b 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_profile_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_profile_list.html @@ -1,9 +1,9 @@ {% extends "hosting/base.html" %} -{% block title %}Customer manager profiles · Coulobre Panel{% endblock %} +{% block title %}Manager profiles · Coulobre Panel{% endblock %} {% block content %} - ← Customer managers + ← Managers
-

Customer manager profiles

+

Manager profiles

Add profile
diff --git a/src/coulobre/hosting/templates/hosting/system_workspace.html b/src/coulobre/hosting/templates/hosting/system_workspace.html new file mode 100644 index 0000000..561f3e2 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/system_workspace.html @@ -0,0 +1,16 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} +

{{ title }}

+
+
    + {% for account in accounts %} +
  • + {% if target %}{{ account.primary_domain }} + {% else %}{{ account.primary_domain }}{% endif %} +
  • + {% empty %}
  • No hosting accounts are available.
  • {% endfor %} +
+ {% if not target %}

This service needs setup.

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

{{ title }}

+
+ + {% csrf_token %} + {{ form.as_div }} + {% if invitation_preview %} +
+ Welcome email preview +

The message includes an invitation link for choosing a password and setup details for the new hosting account. Your welcome text appears before the setup details.

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

Retention and name release

-

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

+

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

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

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

Type the primary domain to confirm this preview.

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

Email changes require configured panel email delivery.

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

Connected nodes

Service health
+ {% if topology.problem %}

{{ topology.problem }}

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

Recent restores

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

Backup & Restore

{{ account.primary_domain }}

{% for message in messages %}

{{ message }}

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

Create a backup

+

Create a backup

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

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

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

{% endif %}

Recent backups

+
+

Recent restores

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

Restore {{ kind }}

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

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

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

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

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

+ {% else %}

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

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

Review destination

+

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

+ {% if preview.filename %}

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

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

DirectAdmin import

+
+

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

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

{{ title }}

{{ account.primary_domain }}

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

{{ message }}

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

DNS records

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

This domain has no saved Coulobre DNS zone.

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

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

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

Select an active website for this action.

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

Forwarders and catch-all

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

This domain has no managed email accounts.

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

Configure features

+

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

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

{{ message }}

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

Installation

+ About Coulobre +
+ {% else %}

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

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

Mail Queue

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

{{ title }}

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

{{ message }}

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

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

{% endif %} +
+
+

Operation history

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

{{ job.problem }}

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

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

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

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

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

No operations yet.

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

{{ title }}

+ {% for message in messages %}

{{ message }}

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

Previewing {{ theme_preview }}

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

{{ preview.subject }}

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

{{ title }}

+

{{ title }}

{% if section == 'statistics' %}

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

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

This service needs setup.

{% endif %} + {% if section == 'statistics' %} +
+ + {% for account, storage, traffic in rows %} + + {% empty %}{% endfor %} +
Hosting accountDisk useTrafficDomainsDatabasesMailboxes
{{ account.primary_domain }}{% if storage is not None %}{{ storage|filesizeformat }}{% else %}Unavailable{% endif %}{% if traffic is not None %}{{ traffic|filesizeformat }}{% else %}Unavailable{% endif %}{{ account.domain_count|default:"1" }}{{ account.database_count }}{{ account.mailbox_count }}
No hosting accounts are available.
+ {% elif section == 'tasks' %} +
+ + {% for job in tasks %} + + {% empty %}{% endfor %} +
DomainTaskStatusNext run (UTC)
{{ job.domain }}{% if target %}{{ job.name }}{% else %}{{ job.name }}{% endif %}{{ job.enabled|yesno:"Enabled,Paused" }}{{ job.next_run_at|date:"j M Y H:i"|default:"—" }}
No scheduled tasks for these accounts.
+ {% else %} + + {% if not target %}

Website logs need a configured collector.

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

Updates

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

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

{{ message }}

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

The message includes an invitation link for choosing a password and setup details for the new hosting account. Your welcome text appears before the setup details.

+
{{ welcome_preview }}
{% endif %} + {% if moving %} +
+

Move to {{ destination }}

+
    {% for item in moving %}
  • {{ item.primary_domain }} · {{ item.hosting_plan }} · from {{ item.reseller|default:"Unassigned" }}
  • {% endfor %}
+
+ {% endif %}
- + {% if invitation_preview or move_preview_enabled %}{% endif %} + {% if not move_preview_enabled or moving %}{% endif %} Cancel
diff --git a/src/coulobre/hosting/test_customer_restore.py b/src/coulobre/hosting/test_customer_restore.py new file mode 100644 index 0000000..d81dc0c --- /dev/null +++ b/src/coulobre/hosting/test_customer_restore.py @@ -0,0 +1,73 @@ +from unittest.mock import patch +from uuid import uuid4 + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.account_backup import AccountBackup +from coulobre.web_node import WebSite + +from .models import ( + AccountBackupJob, + ComponentRestoreJob, + Customer, + HostingAccount, + HostingDatabase, +) +from .tasks import restore_backup_component + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DATABASE_RESTORE=True) +class CustomerRestoreTests(TestCase): + def test_restore_requires_its_customers_backup_and_current_assignment( + self, + ): + users = get_user_model().objects + customer = Customer.objects.create(user=users.create_user("customer")) + other = Customer.objects.create(user=users.create_user("other")) + account = HostingAccount.objects.create( + name="Shop", primary_domain="shop.example.test", customer=customer + ) + database = HostingDatabase.objects.create( + account=account, suffix="cms" + ) + archive = AccountBackup( + WebSite(account.pk, account.primary_domain), (database.spec,) + ) + backup = AccountBackupJob.objects.create( + account=account, + manifest=archive.manifest(), + finished_at=timezone.now(), + export_customer_id=customer.pk, + ) + url = reverse( + "panel:customer_restore", args=[account.pk, backup.pk, "database"] + ) + self.client.force_login(other.user) + self.assertEqual(self.client.get(url).status_code, 404) + self.client.force_login(customer.user) + data = {"restore_id": str(uuid4()), "resource": database.suffix} + self.assertContains( + self.client.post(url, data | {"action": "restore"}), + "Review the destination before restoring.", + ) + self.assertContains( + self.client.post(url, data | {"action": "preview"}), + database.spec.name, + ) + self.assertFalse(ComponentRestoreJob.objects.exists()) + self.assertRedirects( + self.client.post(url, data | {"action": "restore"}), + reverse("panel:customer_backups", args=[account.pk]), + ) + job = ComponentRestoreJob.objects.get() + HostingAccount.objects.filter(pk=account.pk).update(customer=other) + with patch( + "coulobre.hosting.tasks.restore_local_component" + ) as restore: + restore_backup_component(job.pk) + restore.assert_not_called() + job.refresh_from_db() + self.assertEqual(job.state, "failed") diff --git a/src/coulobre/hosting/test_operator_workspaces.py b/src/coulobre/hosting/test_operator_workspaces.py new file mode 100644 index 0000000..dbc32d1 --- /dev/null +++ b/src/coulobre/hosting/test_operator_workspaces.py @@ -0,0 +1,91 @@ +import json +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import SimpleTestCase, TestCase +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from coulobre.mail_queue import MailQueueAction, change_queue_entry +from coulobre.operator_node import OperatorRequest, packages + +from .models import PanelTheme + + +class OperatorRequestTests(SimpleTestCase): + def test_unknown_services_and_changed_package_plans_are_rejected(self): + with self.assertRaises(ValueError): + OperatorRequest("restart", "ssh.service") + with ( + patch("coulobre.operator_node.locked_root_directory"), + patch( + "coulobre.operator_node.apt_plan", + return_value={"fingerprint": "0" * 64}, + ), + patch("coulobre.operator_node.command") as command, + self.assertRaisesMessage(ValueError, "The package plan changed"), + ): + packages(OperatorRequest("package-upgrade", plan="f" * 64)) + command.assert_not_called() + + def test_mail_action_requires_entire_recipient_scope_and_fresh_arrival( + self, + ): + message = { + "queue_id": "Ab12345", + "queue_name": "deferred", + "arrival_time": 1710000000, + "recipients": [ + {"address": "alice@example.test"}, + {"address": "bob@different.test"}, + ], + } + request = MailQueueAction( + "example.test", message["queue_id"], 1710000000, "flush" + ) + with ( + patch( + "coulobre.mail_queue.read_queue", + side_effect=lambda consume: consume([json.dumps(message)]), + ), + patch("coulobre.mail_queue.subprocess.run") as command, + ): + with self.assertRaises(ValueError): + change_queue_entry(request) + message["recipients"].pop() + message["arrival_time"] += 1 + with self.assertRaises(ValueError): + change_queue_entry(request) + command.assert_not_called() + + +class ThemePreviewTests(TestCase): + def test_theme_preview_uses_validated_css_and_requires_confirmation(self): + operator = get_user_model().objects.create_superuser("operator") + self.client.force_login(operator) + session = self.client.session + device = TOTPDevice.objects.create(user=operator, name="test") + session["otp_device_id"] = device.persistent_id + session.save() + url = reverse("panel:theme_management") + hostile = SimpleUploadedFile( + "custom.css", b":root { --accent: url(https://example.test); }" + ) + response = self.client.post( + url, {"name": "Test theme", "stylesheet": hostile} + ) + self.assertContains(response, "hexadecimal values") + stylesheet = SimpleUploadedFile( + "custom.css", b":root { --accent: #123456; }" + ) + response = self.client.post( + url, {"name": "Test theme", "stylesheet": stylesheet} + ) + self.assertContains(response, "Previewing Test theme") + self.assertFalse(PanelTheme.objects.exists()) + self.assertContains( + self.client.get(reverse("panel:preview_stylesheet")), "#123456" + ) + self.assertRedirects(self.client.post(url, {"action": "install"}), url) + self.assertEqual(PanelTheme.objects.get().name, "Test theme") diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py index b02839b..a8b3e92 100644 --- a/src/coulobre/hosting/test_workspaces.py +++ b/src/coulobre/hosting/test_workspaces.py @@ -60,17 +60,19 @@ class WorkspaceTests(TestCase): dns = reverse("panel:customer_workspace", args=["dns"]) self.assertRedirects( self.client.get(dns, {"account": second.pk}), - second.get_absolute_url() + "#domains-dns", + reverse("panel:domain_workspace", args=[second.pk, "dns"]), ) self.assertRedirects( - self.client.get(dns), second.get_absolute_url() + "#domains-dns" + self.client.get(dns), + reverse("panel:domain_workspace", args=[second.pk, "dns"]), ) self.assertEqual( self.client.get(dns, {"account": foreign.pk}).status_code, 404 ) HostingAccount.objects.filter(pk=second.pk).update(customer=None) self.assertRedirects( - self.client.get(dns), first.get_absolute_url() + "#domains-dns" + self.client.get(dns), + reverse("panel:domain_workspace", args=[first.pk, "dns"]), ) def test_manager_creates_login_and_hosting_under_its_own_policy(self): @@ -120,3 +122,55 @@ class WorkspaceTests(TestCase): self.assertFalse( get_user_model().objects.filter(username="overflow").exists() ) + + def test_transfer_preserves_every_active_account_in_the_customer_scope( + self, + ): + users = get_user_model().objects + operator = users.create_superuser("operator") + manager = Reseller.objects.create(user=users.create_user("source")) + destination = Reseller.objects.create( + user=users.create_user("destination"), account_limit=2 + ) + customer = Customer.objects.create( + user=users.create_user("customer"), reseller=manager + ) + plan = HostingPlan.objects.create(name="Small") + destination.hosting_plans.add(plan) + accounts = [ + HostingAccount.objects.create( + name=label, + primary_domain=f"{label}.example.test", + customer=customer, + reseller=manager, + hosting_plan=plan, + ) + for label in ("first", "second") + ] + from django_otp.plugins.otp_totp.models import TOTPDevice + + device = TOTPDevice.objects.create(user=operator, name="test") + self.client.force_login(operator) + session = self.client.session + session["otp_device_id"] = device.persistent_id + session.save() + url = reverse("panel:move_accounts") + data = {"account": accounts[0].pk, "manager": destination.pk} + self.assertContains( + self.client.post(url, data | {"action": "move", "confirm": "on"}), + "Preview and confirm", + ) + preview = self.client.post(url, data | {"action": "preview"}) + for account in accounts: + self.assertContains(preview, account.primary_domain) + response = self.client.post( + url, data | {"action": "move", "confirm": "on"} + ) + self.assertRedirects(response, accounts[0].get_absolute_url()) + customer.refresh_from_db() + self.assertEqual(customer.reseller_id, destination.pk) + self.assertEqual(destination.hostingaccount_set.count(), 2) + self.client.force_login(manager.user) + self.assertEqual( + self.client.get(accounts[0].get_absolute_url()).status_code, 404 + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index cac1d1c..0091d82 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -21,9 +21,10 @@ from .account_security import ( ) from .backup_restores import RestoreKind from .credential_views import DatabaseCredentialView, MailboxCredentialView -from .customer_backup_views import CustomerBackupView +from .customer_backup_views import CustomerBackupView, CustomerRestoreView from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView +from .domain_services import domain_workspace from .health_views import ServiceHealthView from .independent_website_views import ( IndependentWebsiteCreate, @@ -34,7 +35,16 @@ from .installation_views import FeatureConfigurationView, InstallationView from .invitations import AcceptInvitation, ManageInvitation from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_policy_views import MailRoutingEditor, MailVacationEditor -from .mail_queue_views import MailQueueView +from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action +from .operator_tools import ConnectedNodesView, OperatorToolsView +from .panel_content import ( + AnnouncementView, + DirectAdminGuideView, + ThemeManagementView, + ThemeSelectionView, + preview_stylesheet, + user_stylesheet, +) from .panel_roles import AssignPanelRoleView, switch_panel_role from .password_reset import ( CustomerPasswordResetView, @@ -75,6 +85,49 @@ from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), + path( + "mail-domains//queue/change/", + mail_queue_action, + name="mail_queue_action", + ), + path( + "system/nodes/", ConnectedNodesView.as_view(), name="connected_nodes" + ), + path( + "service-health/actions/", + OperatorToolsView.as_view(page="services"), + name="operator_service_actions", + ), + path( + "updates/server-packages/", + OperatorToolsView.as_view(page="packages"), + name="server_updates", + ), + path( + "server/database/", + OperatorToolsView.as_view(page="database"), + name="database_monitor", + ), + path("themes/", ThemeManagementView.as_view(), name="theme_management"), + path( + "my-account/theme/", + ThemeSelectionView.as_view(), + name="theme_selection", + ), + path("themes/preview.css", preview_stylesheet, name="preview_stylesheet"), + path("user-theme.css", user_stylesheet, name="user_stylesheet"), + path("announcements/", AnnouncementView.as_view(), name="announcements"), + path( + "imports/directadmin/", + DirectAdminGuideView.as_view(), + name="directadmin_guide", + ), + path( + "accounts//domains//", + domain_workspace, + name="domain_workspace", + ), path( "hosting//", customer_workspace, name="customer_workspace" ), @@ -99,6 +152,11 @@ urlpatterns = [ CustomerBackupView.as_view(), name="customer_backups", ), + path( + "hosting//backups//restore//", + CustomerRestoreView.as_view(), + name="customer_restore", + ), path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"), path("updates/", UpdateView.as_view(), name="updates"), path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"), @@ -127,6 +185,11 @@ urlpatterns = [ FeatureConfigurationView.as_view(), name="feature_configuration", ), + path( + "settings//", + FeatureConfigurationView.as_view(), + name="operator_settings", + ), path("account/role/", switch_panel_role, name="switch_panel_role"), path( "logins/assign-role/", diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index a633d1a..30762be 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -77,6 +77,7 @@ from .dns_forms import ( zone_record_rows, ) from .dns_publication import queue_dns_publication +from .domain_policies import require_managed from .health_views import STALE_AFTER from .impersonation import ( CUSTOMER_WRITE_PERMISSIONS, @@ -1058,9 +1059,7 @@ class SiteStorageLimitEdit( return redirect(self.account) -class SitePhpSettingsEdit( - OperatorOnlyMixin, PermissionRequiredMixin, FormView -): +class SitePhpSettingsEdit(PermissionRequiredMixin, FormView): permission_required = CHANGE_SITE_PHP_SETTINGS form_class = SitePhpSettingsForm template_name = "hosting/site_php_settings_form.html" @@ -1070,14 +1069,21 @@ class SitePhpSettingsEdit( raise Http404 return super().dispatch(request, *args, **kwargs) + def has_permission(self): + user = self.request.user + return customer_for_user(user) is not None or ( + reseller_for_user(user) is None and super().has_permission() + ) + @cached_property def account(self): - return get_object_or_404( - HostingAccount.objects.select_related( - "hosting_plan", "php_settings_job" - ), - pk=self.kwargs["pk"], - ) + accounts = HostingAccount.objects.select_related( + "hosting_plan", "php_settings_job" + ).filter(retired_at__isnull=True) + customer = customer_for_user(self.request.user) + if customer is not None: + accounts = accounts.filter(customer=customer) + return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_initial(self): job = getattr(self.account, "php_settings_job", None) @@ -1099,6 +1105,9 @@ class SitePhpSettingsEdit( self.account.pk, None if use_plan else settings_from_form(form.cleaned_data), use_plan=use_plan, + customer_id=self.account.customer_id + if customer_for_user(self.request.user) is not None + else None, ) except HostingAccount.DoesNotExist: raise Http404 from None @@ -2210,6 +2219,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): self.account.pk, customer_id=None ) require_open_account(account) + require_managed(account, account.primary_domain, "dns_managed") zone = HostingDnsZone.objects.create( account=account, domain=account.primary_domain, @@ -2332,6 +2342,7 @@ class DnsZoneEdit(DnsZoneEditor): self.account.pk, customer_id=None ) require_open_account(account) + require_managed(account, self.zone.domain, "dns_managed") self.check_managed_mail_records(values) zones = HostingDnsZone.objects.filter( pk=self.zone.pk, serial=serial diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 14b10d1..073d2f7 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -1,14 +1,17 @@ from django.conf import settings from django.core.exceptions import PermissionDenied +from django.core.paginator import Paginator +from django.db.models import Count from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse +from django.utils import timezone from django.views.decorators.cache import never_cache from django.views.decorators.http import require_safe from .access import customer_for_user, reseller_for_user from .installation_features import panel_feature_allowed -from .models import HostingAccount +from .models import HostingAccount, WebsiteScheduledJob CUSTOMER_ACCOUNT = "coulobre_active_hosting_account" @@ -87,6 +90,8 @@ def customer_workspace(request, page): return redirect("panel:accounts") if page == "overview": return redirect(account) + if page in {"domains", "dns", "php", "files", "forwarders", "replies"}: + return redirect("panel:domain_workspace", pk=account.pk, page=page) _, destination, fragment = pages[page] return redirect( reverse( @@ -117,12 +122,60 @@ def system_workspace(request, page): or reseller_for_user(request.user) is not None or request.user.has_perm("hosting.view_websiteusage") ) + counts = { + "domain_count": Count("website_domains", distinct=True), + "database_count": Count("databases", distinct=True), + "mailbox_count": Count("mail_domains__mailboxes", distinct=True), + } + pagination = Paginator( + accounts.annotate(**counts).prefetch_related("website_usage"), 25 + ) + page_obj = pagination.get_page(request.GET.get("page")) + month = timezone.now().strftime("%Y-%m") + rows = [] + for account in page_obj.object_list: + snapshots = [ + row.report + for row in account.website_usage.all() + if row.observed_at + ] + storage = [ + row["storage_bytes"] + for row in snapshots + if row.get("storage_bytes") is not None + ] + traffic = [ + row["traffic_bytes"] + for row in snapshots + if row.get("month") == month + and row.get("traffic_bytes") is not None + ] + rows.append( + ( + account, + sum(storage) if storage else None, + sum(traffic) if traffic else None, + ) + ) + tasks = () + task_accounts = set(account.pk for account, _, _ in rows) + if page == "tasks": + tasks = ( + WebsiteScheduledJob.objects.filter(account_id__in=task_accounts) + .select_related("account") + .order_by("domain", "name")[:250] + ) return render( request, "hosting/system_workspace.html", { "title": title, - "accounts": accounts, + "section": page, + "rows": rows, + "tasks": tasks, + "month": month, + "page_obj": page_obj, + "is_paginated": pagination.num_pages > 1, "target": f"panel:{target}" if may_open else None, }, ) @@ -185,7 +238,7 @@ def groups_for(request, *, customer, manager): ("view_hostingaccount", "accounts", "Hosting accounts"), ("view_customer", "all_users", "Show All Users"), ("view_reseller", "resellers", "Managers"), - ("add_reseller", "reseller_create", "Add New Reseller"), + ("add_reseller", "reseller_create", "Add Manager"), ("view_hostingplan", "hosting_plans", "Hosting plans"), ): if user.has_perm(f"hosting.{permission}"): @@ -193,22 +246,42 @@ def groups_for(request, *, customer, manager): server, admin_tools = [], [] if user.has_perm("hosting.view_webprovisioningplan"): server.append(link("plans", "Web provisioning")) + if user.has_perm("hosting.view_hostingmaildomain") and user.has_perm( + "hosting.view_hostingaccount" + ): + admin_tools.append(link("mail_queue_index", "Mail Queue")) if user.has_perm("hosting.view_servicehealth"): admin_tools.append(link("service_health", "System Services")) if user.is_superuser: accounts.extend( ( link("operator_create", "Add New Operator"), - link("reseller_profiles", "Reseller Packages"), + link("reseller_profiles", "Manager Packages"), link("move_accounts", "Move Users"), ) ) server.extend( ( - link("feature_configuration", "Operator Settings"), + link("operator_settings", "Operator Settings", "general"), link("dns_defaults", "DNS Settings"), ) ) + if user.is_superuser: + admin_tools.extend( + ( + link("theme_management", "Themes"), + link("announcements", "Message"), + link("directadmin_guide", "Import"), + ) + ) + if user.is_superuser: + server.append(link("connected_nodes", "Connected Nodes")) + admin_tools.extend( + ( + link("operator_service_actions", "Service actions"), + link("database_monitor", "DB Monitor"), + ) + ) groups = [ ("Account Manager", accounts), ("Server Manager", server), diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index e7e9973..4f40fe4 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -167,10 +167,18 @@ class MailboxSigningRequest: def parse_mailbox_request(data): from .mail_policy import OPERATIONS, parse_mail_policy - from .mail_queue import MailQueueRequest + from .mail_queue import MailQueueAction, MailQueueRequest - if isinstance(data, dict) and data.get("operation") == "inspect_queue": + if isinstance(data, dict) and data.get("operation") in { + "inspect_queue", + "inspect_queue_entries", + }: return MailQueueRequest.from_manifest(data) + if ( + isinstance(data, dict) + and data.get("operation") == "change_queue_entry" + ): + return MailQueueAction.from_manifest(data) if isinstance(data, dict) and data.get("operation") in OPERATIONS: return parse_mail_policy(data) return parse_retirement( @@ -203,10 +211,17 @@ def mailbox_request_identity(spec): def apply_mailbox_request(request): from .mail_policy import MailRouting, MailVacation - from .mail_queue import MailQueueRequest, inspect_queue + from .mail_queue import ( + MailQueueAction, + MailQueueRequest, + change_queue_entry, + inspect_queue, + ) if isinstance(request, MailQueueRequest): return inspect_queue(request) + if isinstance(request, MailQueueAction): + return change_queue_entry(request) if isinstance(request, MailboxUsageRequest): return inspect_mailbox_usage(request.mailbox) if isinstance(request, MailRouting): diff --git a/src/coulobre/mail_queue.py b/src/coulobre/mail_queue.py index eafe1c5..e840f1f 100644 --- a/src/coulobre/mail_queue.py +++ b/src/coulobre/mail_queue.py @@ -1,35 +1,118 @@ import json +import re import subprocess from dataclasses import dataclass from .domain_names import canonical_domain MAX_QUEUE_ROWS = 20000 +QUEUE_ID = re.compile(r"[A-Za-z0-9]{5,32}") +QUEUE_ACTIONS = { + "flush": ("/usr/sbin/postqueue", "-i"), + "hold": ("/usr/sbin/postsuper", "-h"), + "release": ("/usr/sbin/postsuper", "-H"), +} QUEUE_NAMES = ("active", "deferred", "hold", "incoming", "maildrop") @dataclass(frozen=True) class MailQueueRequest: domain: str + detailed: bool = False def __post_init__(self): object.__setattr__(self, "domain", canonical_domain(self.domain)) def manifest(self): - return {"operation": "inspect_queue", "domain": self.domain} + operation = ( + "inspect_queue_entries" if self.detailed else "inspect_queue" + ) + return {"operation": operation, "domain": self.domain} @classmethod def from_manifest(cls, data): if data.keys() != {"operation", "domain"}: raise ValueError("Expected a mail queue request.") - return cls(data["domain"]) + return cls( + data["domain"], data["operation"] == "inspect_queue_entries" + ) -def summarize_queue(lines, domain): +@dataclass(frozen=True) +class MailQueueAction: + domain: str + queue_id: str + arrival: int + action: str + + def __post_init__(self): + object.__setattr__(self, "domain", canonical_domain(self.domain)) + if not isinstance(self.queue_id, str) or not QUEUE_ID.fullmatch( + self.queue_id + ): + raise ValueError("Choose a valid mail queue entry.") + if ( + self.action not in QUEUE_ACTIONS + or type(self.arrival) is not int + or not 0 < self.arrival < 2**53 + ): + raise ValueError("Choose an available queue action.") + + def manifest(self): + return { + "operation": "change_queue_entry", + "domain": self.domain, + "queue_id": self.queue_id, + "arrival": self.arrival, + "action": self.action, + } + + @classmethod + def from_manifest(cls, data): + if data.keys() != { + "operation", + "domain", + "queue_id", + "arrival", + "action", + }: + raise ValueError("Expected a mail queue action.") + return cls( + data["domain"], data["queue_id"], data["arrival"], data["action"] + ) + + +def visible_entry(message, domain): + recipients = [ + item["address"].rpartition("@")[2].lower() + for item in message["recipients"] + ] + queue_id = message.get("queue_id", "") + arrival = message.get("arrival_time") + if not recipients or any(item != domain for item in recipients): + return None + if ( + not QUEUE_ID.fullmatch(queue_id) + or type(arrival) is not int + or not 0 < arrival < 2**53 + ): + return None + return { + "queue_id": queue_id, + "arrival": arrival, + "queue": message["queue_name"], + } + + +def summarize_queue(lines, domain, *, detailed=False): counts = dict.fromkeys(QUEUE_NAMES, 0) + report = {"counts": counts, "partial": False} + if detailed: + report["entries"] = [] for index, line in enumerate(lines): if index == MAX_QUEUE_ROWS: - return {"counts": counts, "partial": True} + report["partial"] = True + return report if len(line) > 1024 * 1024: raise ValueError("Postfix returned an oversized queue entry.") message = json.loads(line) @@ -43,10 +126,22 @@ def summarize_queue(lines, domain): for address in addresses ): counts[queue] += 1 - return {"counts": counts, "partial": False} + if detailed and len(report["entries"]) < 100: + entry = visible_entry(message, domain) + if entry: + report["entries"].append(entry) + return report def inspect_queue(request): + return read_queue( + lambda lines: summarize_queue( + lines, request.domain, detailed=request.detailed + ) + ) + + +def read_queue(consume): with subprocess.Popen( ["/usr/sbin/postqueue", "-j"], stdin=subprocess.DEVNULL, @@ -56,7 +151,7 @@ def inspect_queue(request): ) as process: try: lines = iter(lambda: process.stdout.readline(1024 * 1024 + 1), b"") - result = summarize_queue(lines, request.domain) + result = consume(lines) if not result["partial"] and process.wait(timeout=5): raise ValueError("Postfix could not read the mail queue.") return result @@ -67,3 +162,44 @@ def inspect_queue(request): finally: if process.poll() is None: process.kill() + + +def change_queue_entry(request): + def find_entry(lines): + for index, line in enumerate(lines): + if index == MAX_QUEUE_ROWS or len(line) > 1024 * 1024: + break + message = json.loads(line) + if message.get("queue_id") == request.queue_id: + return { + "entry": visible_entry(message, request.domain), + "partial": True, + } + return {"entry": None, "partial": True} + + entry = read_queue(find_entry)["entry"] + if entry is None or entry["arrival"] != request.arrival: + raise ValueError("The queue entry changed or is outside this domain.") + expected = { + "flush": ("deferred",), + "hold": ("active", "deferred"), + "release": ("hold",), + } + if entry["queue"] not in expected[request.action]: + raise ValueError( + "This action is unavailable for the entry's current queue." + ) + try: + subprocess.run( + [*QUEUE_ACTIONS[request.action], request.queue_id], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + timeout=25, + env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"}, + ) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + raise ValueError( + "Postfix could not complete the queue action." + ) from error diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py new file mode 100644 index 0000000..ba6c196 --- /dev/null +++ b/src/coulobre/operator_node.py @@ -0,0 +1,180 @@ +import hashlib +import os +import re +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from .node_files import locked_root_directory +from .node_requests import serve_apply_request + +SOCKET = "/run/coulobre-operator-apply.sock" +STATE = Path("/var/lib/coulobre/operator") +SERVICES = { + "apache": "apache2.service", + "dns": "named.service", + "smtp": "postfix.service", + "imap": "dovecot.service", + "spam": "rspamd.service", +} +ACTIONS = ( + "package-preview", + "package-upgrade", + "reload", + "restart", + "database-report", +) +APT = "/usr/bin/apt-get" + + +@dataclass(frozen=True) +class OperatorRequest: + action: str + target: str = "" + plan: str = "" + + def __post_init__(self): + if self.action not in ACTIONS: + raise ValueError("Choose a supported operator action.") + if self.action in {"reload", "restart"}: + if self.target not in SERVICES: + raise ValueError("Choose a managed service.") + elif self.target: + raise ValueError("This operation does not use a service target.") + if self.action == "package-upgrade": + if not re.fullmatch(r"[a-f0-9]{64}", self.plan): + raise ValueError("Review the package plan before applying it.") + elif self.plan: + raise ValueError("This operation does not use a package plan.") + + @classmethod + def from_manifest(cls, payload): + if ( + not isinstance(payload, dict) + or payload.keys() != {"version", "action", "target", "plan"} + or type(payload["version"]) is not int + or payload["version"] != 1 + or any( + not isinstance(payload[key], str) + for key in ("action", "target", "plan") + ) + ): + raise ValueError("Expected an operator request.") + return cls(payload["action"], payload["target"], payload["plan"]) + + def manifest(self): + return { + "version": 1, + "action": self.action, + "target": self.target, + "plan": self.plan, + } + + +def command(*args, timeout=90): + try: + result = subprocess.run( + args, + stdin=subprocess.DEVNULL, + capture_output=True, + timeout=timeout, + check=False, + env={ + "PATH": "/usr/sbin:/usr/bin", + "LC_ALL": "C", + "DEBIAN_FRONTEND": "noninteractive", + }, + ) + except subprocess.TimeoutExpired: + raise ValueError( + "The host operation timed out. Review the service journal." + ) from None + if result.returncode: + raise ValueError( + "The host operation failed. Review the service journal." + ) + return result.stdout.decode("utf-8", errors="replace") + + +def apt_plan(): + output = command(APT, "--simulate", "--no-remove", "upgrade") + lines = [line for line in output.splitlines() if line.startswith("Inst ")] + digest = hashlib.sha256("\n".join(lines).encode()).hexdigest() + return { + "fingerprint": digest, + "packages": [line[:240] for line in lines[:90]], + "count": len(lines), + } + + +def packages(request): + with locked_root_directory(STATE): + if request.action == "package-preview": + command(APT, "update", timeout=180) + return apt_plan() + plan = apt_plan() + if request.plan != plan["fingerprint"]: + raise ValueError( + "The package plan changed. Collect and review a new preview." + ) + if plan["count"]: + command( + APT, + "-o", + "Dpkg::Options::=--force-confold", + "--yes", + "--no-remove", + "upgrade", + timeout=1500, + ) + report = apt_plan() + return {"upgrades_remaining": report["count"]} + + +def database_report(): + query = ( + "SELECT @@version, @@slow_query_log; SHOW GLOBAL STATUS WHERE " + "Variable_name IN ('Threads_connected','Slow_queries','Uptime');" + ) + output = command( + "/usr/bin/mariadb", + "--batch", + "--skip-column-names", + "--protocol=socket", + "--execute", + query, + ) + rows = [row.split("\t") for row in output.splitlines()] + if not rows or any(len(row) != 2 for row in rows): + raise ValueError("MariaDB returned an invalid status report.") + version, slow_log = rows[0] + counters = {key: value for key, value in rows[1:] if value.isdecimal()} + return { + "version": version[:80], + "slow_logging": slow_log == "1", + "counters": counters, + } + + +def apply_request(request): + if os.geteuid() != 0: + raise ValueError("Run operator actions as root on the host.") + if request.action.startswith("package-"): + if os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") != "1": + raise ValueError( + "Enable server package updates in the host configuration." + ) + return packages(request) + if request.action == "database-report": + return database_report() + with locked_root_directory(STATE): + service = SERVICES[request.target] + command("/usr/bin/systemctl", request.action, service) + command("/usr/bin/systemctl", "is-active", "--quiet", service) + return {"active": True} + + +def main(): + return serve_apply_request( + 1, OperatorRequest.from_manifest, apply_request, include_result=True + ) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index c38d540..cbd7dc7 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -111,6 +111,7 @@ TEMPLATES = [ "django.contrib.messages.context_processors.messages", "coulobre.hosting.access.panel_access", "coulobre.hosting.themes.panel_appearance", + "coulobre.hosting.panel_content.panel_announcements", ], }, }, From 5611395cd23a7d19bb36c0c683c8e4f15193b2b1 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 22:36:14 +0100 Subject: [PATCH 3/9] Enforce manager boundaries and add scoped mail delivery history --- src/coulobre/hosting/access.py | 6 + .../hosting/independent_website_views.py | 8 +- src/coulobre/hosting/independent_websites.py | 6 +- src/coulobre/hosting/mail_delivery_views.py | 146 +++++++++++++ src/coulobre/hosting/mail_policy_views.py | 9 +- .../migrations/0067_mail_delivery_search.py | 65 ++++++ src/coulobre/hosting/models.py | 11 + src/coulobre/hosting/reseller_onboarding.py | 39 +--- src/coulobre/hosting/tasks.py | 72 +++++++ .../templates/hosting/account_detail.html | 4 +- .../templates/hosting/mail_delivery.html | 34 ++++ src/coulobre/hosting/test_mail_delivery.py | 92 +++++++++ .../hosting/test_reseller_onboarding.py | 117 +++-------- src/coulobre/hosting/urls.py | 2 + src/coulobre/hosting/views.py | 86 +++----- src/coulobre/hosting/website_file_views.py | 4 +- src/coulobre/hosting/website_job_views.py | 4 +- src/coulobre/hosting/workspaces.py | 14 +- src/coulobre/mail_delivery.py | 191 ++++++++++++++++++ src/coulobre/mail_node.py | 6 + 20 files changed, 706 insertions(+), 210 deletions(-) create mode 100644 src/coulobre/hosting/mail_delivery_views.py create mode 100644 src/coulobre/hosting/migrations/0067_mail_delivery_search.py create mode 100644 src/coulobre/hosting/templates/hosting/mail_delivery.html create mode 100644 src/coulobre/hosting/test_mail_delivery.py create mode 100644 src/coulobre/mail_delivery.py diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 0525105..f4ede66 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -44,6 +44,12 @@ def manages_account(user, account): return reseller is not None and account.reseller_id == reseller.pk +def can_manage_hosting(user, permissions): + return customer_for_user(user) is not None or ( + not is_tenant(user) and user.has_perms(permissions) + ) + + 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 diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py index d5e68d6..fa2c27d 100644 --- a/src/coulobre/hosting/independent_website_views.py +++ b/src/coulobre/hosting/independent_website_views.py @@ -11,7 +11,7 @@ from django.views.generic.detail import SingleObjectMixin from coulobre.domain_names import canonical_domain -from .access import OperatorOnlyMixin, TenantScopeMixin +from .access import OperatorOnlyMixin, TenantScopeMixin, reseller_for_user from .independent_websites import ( Operation, account_websites, @@ -83,6 +83,12 @@ class IndependentWebsiteEditor( raise Http404 return super().dispatch(request, *args, **kwargs) + def has_permission(self): + return ( + reseller_for_user(self.request.user) is None + and super().has_permission() + ) + @cached_property def account(self): return self.get_object() diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py index 90d4691..e142f86 100644 --- a/src/coulobre/hosting/independent_websites.py +++ b/src/coulobre/hosting/independent_websites.py @@ -8,7 +8,7 @@ from coulobre.php_pool_settings import PhpPoolSettings from coulobre.php_runtime import validate_php_version from coulobre.service_access import ServiceAccessRequest -from .access import is_tenant, manages_account +from .access import customer_for_user, is_tenant, manages_account from .installation_features import panel_feature_allowed from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob from .node_client import ( @@ -61,7 +61,9 @@ def website_actions(website): def check_actor(account, actor): - if is_tenant(actor) and not manages_account(actor, account): + if is_tenant(actor) and ( + customer_for_user(actor) is None or not manages_account(actor, account) + ): raise PermissionDenied diff --git a/src/coulobre/hosting/mail_delivery_views.py b/src/coulobre/hosting/mail_delivery_views.py new file mode 100644 index 0000000..fff0dd6 --- /dev/null +++ b/src/coulobre/hosting/mail_delivery_views.py @@ -0,0 +1,146 @@ +from datetime import timedelta + +from django import forms +from django.core.exceptions import PermissionDenied +from django.core.paginator import Paginator +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.utils import timezone +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache +from django.views.generic import FormView + +from coulobre.mail_delivery import MailDeliveryRequest + +from .access import customer_for_user +from .domain_policies import policy_for +from .installation_features import panel_feature_allowed +from .models import HostingAccount, HostingMailDomain, MailDeliverySearch +from .resource_requests import lock_hosting_account + + +class MailDeliveryForm(forms.Form): + domain = forms.ModelChoiceField(queryset=HostingMailDomain.objects.none()) + since = forms.TypedChoiceField( + coerce=int, + choices=[ + (1, "Last hour"), + (24, "Last 24 hours"), + (72, "Last 3 days"), + (168, "Last 7 days"), + ], + initial=24, + label="Period", + ) + sender = forms.EmailField(required=False) + recipient = forms.EmailField(required=False) + + def __init__(self, *args, domains, **kwargs): + super().__init__(*args, **kwargs) + self.fields["domain"].queryset = domains + + def clean(self): + data = super().clean() + if self.errors: + return data + domain = data["domain"] + if not policy_for(domain.account, domain.domain).mail_managed: + self.add_error("domain", "This domain uses an external provider.") + return data + now = int(timezone.now().timestamp()) + self.spec = MailDeliveryRequest( + domain.domain, + now - data["since"] * 3600, + now, + data["sender"], + data["recipient"], + ) + return data + + +@method_decorator(never_cache, name="dispatch") +class MailDeliveryView(FormView): + form_class = MailDeliveryForm + template_name = "hosting/mail_delivery.html" + + def dispatch(self, request, *args, **kwargs): + self.customer = customer_for_user(request.user) + if self.customer is None and not ( + request.user.is_superuser and request.user.is_verified() + ): + raise PermissionDenied + if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"): + raise Http404 + return super().dispatch(request, *args, **kwargs) + + def domain_scope(self): + domains = ( + HostingMailDomain.objects.filter(account__retired_at__isnull=True) + .select_related("account") + .order_by("domain") + ) + if self.customer is not None: + domains = domains.filter(account__customer=self.customer) + return domains + + def get_form_kwargs(self): + return super().get_form_kwargs() | {"domains": self.domain_scope()} + + def get_initial(self): + return {"domain": self.request.GET.get("domain")} + + def get_context_data(self, **kwargs): + search_id = self.request.GET.get("search") + search = page_obj = None + if search_id is not None: + if ( + not search_id.isascii() + or not search_id.isdecimal() + or len(search_id) > 18 + ): + raise Http404 + search = get_object_or_404( + MailDeliverySearch, + pk=search_id, + domain__in=self.domain_scope(), + actor=self.request.user, + customer_id_at_request=self.customer.pk + if self.customer + else None, + expires_at__gt=timezone.now(), + ) + page_obj = Paginator(search.report.get("events", []), 20).get_page( + self.request.GET.get("page") + ) + return super().get_context_data( + search=search, page_obj=page_obj, **kwargs + ) + + @transaction.atomic + def form_valid(self, form): + domain = form.cleaned_data["domain"] + try: + lock_hosting_account( + domain.account_id, self.customer.pk if self.customer else None + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + if not self.domain_scope().filter(pk=domain.pk).exists(): + raise Http404 + now = timezone.now() + if MailDeliverySearch.objects.filter( + actor=self.request.user, + requested_at__gte=now - timedelta(seconds=30), + ).exists(): + form.add_error(None, "Wait 30 seconds between searches.") + return self.form_invalid(form) + search = MailDeliverySearch.objects.create( + actor=self.request.user, + domain=domain, + customer_id_at_request=self.customer.pk if self.customer else None, + filters=form.spec.manifest(), + expires_at=now + timedelta(hours=1), + ) + destination = f"{self.request.path}?search={search.pk}" + return redirect(destination) diff --git a/src/coulobre/hosting/mail_policy_views.py b/src/coulobre/hosting/mail_policy_views.py index 49d79f8..7492026 100644 --- a/src/coulobre/hosting/mail_policy_views.py +++ b/src/coulobre/hosting/mail_policy_views.py @@ -13,7 +13,7 @@ from django.views.generic.detail import SingleObjectMixin from coulobre.mail_policy import MailRouting, MailVacation, parse_mail_policy -from .access import TenantScopeMixin, is_tenant +from .access import TenantScopeMixin, can_manage_hosting from .mail_policies import ( mail_policy_available, policy_account, @@ -42,11 +42,8 @@ def mail_policy_enabled(request, kind): return ( mail_policy_available(kind) and getattr(request, "impersonation", None) is None - and ( - is_tenant(request.user) - or request.user.has_perms( - (*VIEW_PERMISSIONS, POLICY_PERMISSIONS[kind]) - ) + and can_manage_hosting( + request.user, (*VIEW_PERMISSIONS, POLICY_PERMISSIONS[kind]) ) ) diff --git a/src/coulobre/hosting/migrations/0067_mail_delivery_search.py b/src/coulobre/hosting/migrations/0067_mail_delivery_search.py new file mode 100644 index 0000000..3a1c071 --- /dev/null +++ b/src/coulobre/hosting/migrations/0067_mail_delivery_search.py @@ -0,0 +1,65 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:33 + +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", "0066_customer_restore_scope"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="MailDeliverySearch", + 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)), + ( + "customer_id_at_request", + models.PositiveBigIntegerField(null=True), + ), + ("filters", models.JSONField()), + ("report", models.JSONField(default=dict)), + ("expires_at", models.DateTimeField(db_index=True)), + ( + "actor", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "domain", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="hosting.hostingmaildomain", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 93d9321..f759da4 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -851,6 +851,17 @@ class MailQueueOperation(ProvisioningJob): action = models.CharField(max_length=8) +class MailDeliverySearch(ProvisioningJob): + actor = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + domain = models.ForeignKey(HostingMailDomain, on_delete=models.CASCADE) + customer_id_at_request = models.PositiveBigIntegerField(null=True) + filters = models.JSONField() + report = models.JSONField(default=dict) + expires_at = models.DateTimeField(db_index=True) + + class AccountRetirement(models.Model): class Policy(models.TextChoices): HOLD = "hold", "Keep names reserved" diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py index a5d8551..037a73c 100644 --- a/src/coulobre/hosting/reseller_onboarding.py +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -16,7 +16,7 @@ def scoped_customers(reseller): ) -def lock_reseller_account(access, account_id, *, resources=False): +def lock_reseller_account(access, account_id): account = lock_hosting_account(account_id, customer_id=None) if account.reseller_id != access.pk: raise HostingAccount.DoesNotExist @@ -25,8 +25,6 @@ def lock_reseller_account(access, account_id, *, resources=False): ).first() if reseller is None or not reseller.user.is_active: raise PermissionDenied - if resources and not reseller.manage_resources: - raise PermissionDenied require_open_account(account) return account, reseller @@ -71,38 +69,3 @@ def save_customer_link(account, reseller, customer, action): {"customer": str(customer)}, account_domain=account.primary_domain, ) - - -@transaction.atomic -def request_reseller_resource(access, account_id, create, values): - account, reseller = lock_reseller_account( - access, account_id, resources=True - ) - resource = create(account.pk, **values) - record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource) - if getattr(resource, "provisioning", None) is not None: - record_resource_event( - reseller, account, Action.RESOURCE_PROVISION, resource - ) - return resource - - -@transaction.atomic -def provision_reseller_resource(access, account_id, provision, resource): - account, reseller = lock_reseller_account( - access, account_id, resources=True - ) - if provision(resource): - record_resource_event( - reseller, account, Action.RESOURCE_PROVISION, resource - ) - - -def record_resource_event(reseller, account, action, resource): - record_event( - reseller, - reseller.user.get_username(), - action, - {"resource": str(resource), "type": resource._meta.verbose_name}, - account_domain=account.primary_domain, - ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 411d70a..aba4cfe 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -50,6 +50,7 @@ from .models import ( HostingMailDomain, IndependentWebsite, MailboxProvisioning, + MailDeliverySearch, MailRoutingPublication, MailVacationPublication, OffsiteBackupTransfer, @@ -271,7 +272,14 @@ def dispatch_dns_publications(): @shared_task def dispatch_mailbox_provisioning(): + MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete() if settings.LOCAL_MAILBOX_PROVISIONING: + dispatch_provisioning_jobs( + MailDeliverySearch, + search_mail_delivery, + MAILBOX_PROVISIONING_QUEUE, + expires_at__gt=timezone.now(), + ) dispatch_provisioning_jobs( MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE ) @@ -1320,3 +1328,67 @@ def run_mail_queue_operation(job_id): "The mail node did not confirm the queue action.", lease=timedelta(minutes=3), ) + + +@shared_task(queue=MAILBOX_PROVISIONING_QUEUE) +def search_mail_delivery(job_id): + from datetime import UTC, datetime + + from coulobre.mail_delivery import MAX_RESULTS, MailDeliveryRequest + + from .domain_policies import policy_for + from .node_client import apply_on_local_node + + def apply(job): + domain = job.domain + expected = job.customer_id_at_request + if ( + (expected is not None and domain.account.customer_id != expected) + or domain.account.retired_at is not None + or job.expires_at <= timezone.now() + or not policy_for(domain.account, domain.domain).mail_managed + ): + raise ValueError("This mail domain is no longer available.") + spec = MailDeliveryRequest.from_manifest(job.filters) + if spec.domain != domain.domain: + raise ValueError("This mail domain is no longer available.") + reply = apply_on_local_node( + spec, + "/run/coulobre-mail-apply.sock", + "mail node", + "delivery search", + timeout=30, + ) + events = reply.get("events") + if not isinstance(events, list) or len(events) > MAX_RESULTS: + raise ValueError( + "The mail node returned an invalid delivery report." + ) + for event in events: + timestamp = ( + event.get("timestamp") if isinstance(event, dict) else None + ) + if ( + type(timestamp) is not int + or not spec.start <= timestamp <= spec.end + ): + raise ValueError( + "The mail node returned an invalid delivery timestamp." + ) + event["timestamp"] = datetime.fromtimestamp( + timestamp, UTC + ).strftime("%Y-%m-%d %H:%M:%S") + return { + "report": { + "events": events, + "partial": reply.get("partial") is True, + } + } + + if settings.LOCAL_MAILBOX_PROVISIONING: + run_provisioning_job( + MailDeliverySearch.objects.select_related("domain__account"), + job_id, + apply, + "The mail node did not return a delivery report.", + ) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 270188c..40e8521 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -140,7 +140,7 @@ {% endif %} {% endif %} - {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingdatabase %} + {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} {% if automatic_database_provisioning %}Add{% else %}Request{% endif %} database {% endif %} @@ -305,7 +305,7 @@ {% endif %} {% endif %} - {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingmailbox %} + {% if is_customer or 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/mail_delivery.html b/src/coulobre/hosting/templates/hosting/mail_delivery.html new file mode 100644 index 0000000..494980e --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mail_delivery.html @@ -0,0 +1,34 @@ +{% extends "hosting/base.html" %} +{% block title %}Mail delivery · Coulobre Panel{% endblock %} +{% block content %} +

Mail delivery

+
+
+ {% csrf_token %}{{ form.as_div }} +
+
+ {% if search %} +
+

{{ search.domain.domain }}

+ {% if not search.finished_at %}Refresh status{% endif %} +
+ {% if search.problem %}

{{ search.problem }}

+ {% elif not search.finished_at %}

{{ search.state|capfirst }}

+ {% else %} + {% if search.report.partial %}

Recent matches only. Choose a shorter period or add an address filter.

{% endif %} +
+ + {% for event in page_obj %} + + {% empty %}{% endfor %} +
Time (UTC)Queue IDSenderRecipientDelivery
{{ event.timestamp }}{{ event.queue_id }}{{ event.sender|default:"—" }}{{ event.recipient }}{% if event.original_recipient %} · originally {{ event.original_recipient }}{% endif %}{{ event.status|capfirst }}
No matching deliveries in the available journal.
+ {% if page_obj.has_other_pages %} +
+ {% if page_obj.has_previous %}Previous{% endif %} + {% if page_obj.has_next %}Next{% endif %} +
+ {% endif %} + {% endif %} +
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/test_mail_delivery.py b/src/coulobre/hosting/test_mail_delivery.py new file mode 100644 index 0000000..7af64b1 --- /dev/null +++ b/src/coulobre/hosting/test_mail_delivery.py @@ -0,0 +1,92 @@ +import json + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse + +from coulobre.mail_delivery import MailDeliveryRequest, project_delivery + +from .models import ( + Customer, + HostingAccount, + HostingMailDomain, + MailDeliverySearch, +) + + +class PostfixProjectionTests(SimpleTestCase): + def test_scope_uses_original_recipient_or_authenticated_sender(self): + messages = [ + ("qmgr", "A1234: from=, size=200"), + ("smtp", "A1234: to=, status=sent (accepted)"), + ("qmgr", "A1234: removed"), + ("qmgr", "B1234: from=, size=300"), + ("lmtp", "B1234: to=, status=sent (saved)"), + ( + "smtp", + "B1234: to=, status=sent " + "(accepted, orig_to=, end)", + ), + ( + "smtpd", + "C1234: client=host[192.0.2.3], sasl_method=PLAIN, " + "sasl_username=billing@tenant.test", + ), + ("qmgr", "C1234: from=, size=200"), + ("smtp", "C1234: to=, status=sent (accepted)"), + ( + "smtp", + "D1234: to=, orig_to=, " + "status=deferred (timeout)", + ), + ] + entries = [ + json.dumps( + { + "SYSLOG_IDENTIFIER": f"postfix/{service}", + "_EXE": f"/usr/lib/postfix/sbin/{service}", + "__REALTIME_TIMESTAMP": str(index * 1000000), + "MESSAGE": text, + } + ) + for index, (service, text) in enumerate(messages, start=1) + ] + result = project_delivery( + entries, MailDeliveryRequest("tenant.test", 1, 100) + ) + self.assertEqual( + [entry["queue_id"] for entry in result["events"]], + ["D1234", "C1234", "B1234"], + ) + + +@override_settings(LOCAL_MAILBOX_PROVISIONING=True) +class MailDeliveryScopeTests(TestCase): + def test_customer_cannot_submit_or_read_search_for_a_foreign_domain(self): + users = get_user_model().objects + customer = Customer.objects.create(user=users.create_user("customer")) + account = HostingAccount.objects.create( + name="Own account", primary_domain="own.test", customer=customer + ) + other = HostingAccount.objects.create( + name="Other account", primary_domain="other.test" + ) + own = HostingMailDomain.objects.create( + account=account, domain=account.primary_domain + ) + foreign = HostingMailDomain.objects.create( + account=other, domain=other.primary_domain + ) + self.client.force_login(customer.user) + url = reverse("panel:mail_delivery") + self.assertContains( + self.client.post(url, {"domain": foreign.pk, "since": 24}), + "Select a valid choice.", + ) + self.assertFalse(MailDeliverySearch.objects.exists()) + response = self.client.post(url, {"domain": own.pk, "since": 24}) + search = MailDeliverySearch.objects.get() + target = f"{url}?search={search.pk}" + self.assertRedirects(response, target) + HostingAccount.objects.filter(pk=account.pk).update(customer=None) + self.assertEqual(self.client.get(target).status_code, 404) diff --git a/src/coulobre/hosting/test_reseller_onboarding.py b/src/coulobre/hosting/test_reseller_onboarding.py index c7167da..199cc33 100644 --- a/src/coulobre/hosting/test_reseller_onboarding.py +++ b/src/coulobre/hosting/test_reseller_onboarding.py @@ -1,10 +1,8 @@ -from unittest.mock import patch from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase, override_settings from django.urls import reverse -from django.utils import timezone from .models import ( Customer, @@ -18,7 +16,6 @@ from .models import ( Reseller, ResellerAuditEvent, ) -from .reseller_onboarding import request_reseller_resource PASSWORD = "fixture-password-for-customer" Action = ResellerAuditEvent.Action @@ -170,102 +167,34 @@ class ResellerOnboardingTests(TestCase): reverse("panel:customers"), ) - def test_delegated_resource_management_preserves_limits_and_audits_jobs( + def test_manager_cannot_mutate_hosting_despite_previous_resource_grant( self, ): - database_url = reverse("panel:database_create", args=[self.account.pk]) - mailbox_url = reverse("panel:mailbox_create", args=[self.account.pk]) - detail = self.account.get_absolute_url() - self.assertRedirects( - self.client.post(database_url, {"suffix": "shop"}), detail - ) - self.assertRedirects( - self.client.post(mailbox_url, {"local_part": "info"}), detail - ) - self.assertContains( - self.client.post(database_url, {"suffix": "over"}), - "has reached its database limit", - ) - self.assertContains( - self.client.post(mailbox_url, {"local_part": "over"}), - "has reached its mailbox limit", - ) - database = HostingDatabase.objects.get(account=self.account) - mailbox = HostingMailbox.objects.get(mail_domain__account=self.account) - self.assertEqual(mailbox.quota_mib, 50) - for model, resource in (("database", database), ("mailbox", mailbox)): - url = reverse(f"panel:{model}_provision", args=[resource.pk]) - manifest = reverse(f"panel:{model}_manifest", args=[resource.pk]) - self.assertEqual(resource.provisioning.state, "queued") - self.assertContains(self.client.get(detail), "Queued") - self.assertNotContains( - self.client.get(detail), f"Provision {model}" + for account in (self.account, self.other): + database = HostingDatabase.objects.create( + account=account, suffix="shop" ) - self.assertEqual(self.client.get(manifest).status_code, 403) - for _ in range(2): - self.assertRedirects(self.client.post(url), detail) - self.assertEqual(DatabaseProvisioning.objects.get().database, database) - self.assertEqual(MailboxProvisioning.objects.get().mailbox, mailbox) - self.assertEqual( - list( - self.alice.audit_events.order_by("pk").values_list( - "action", flat=True + domain = HostingMailDomain.objects.create( + account=account, domain=account.primary_domain + ) + mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="info" + ) + for kind, resource, payload in ( + ("database", database, {"suffix": "other"}), + ("mailbox", mailbox, {"local_part": "other"}), + ): + create = reverse(f"panel:{kind}_create", args=[account.pk]) + provision = reverse( + f"panel:{kind}_provision", args=[resource.pk] ) - ), - [Action.RESOURCE_REQUEST, Action.RESOURCE_PROVISION] * 2, - ) - DatabaseProvisioning.objects.update( - finished_at=timezone.now(), problem="Failed" - ) - retry = reverse("panel:database_provision", args=[database.pk]) - self.assertRedirects(self.client.post(retry), detail) - self.assertEqual(DatabaseProvisioning.objects.get().state, "queued") - self.assertEqual( - self.alice.audit_events.filter( - action=Action.RESOURCE_PROVISION - ).count(), - 3, - ) - - def test_resource_scope_and_policy_are_checked_for_each_request(self): - database = HostingDatabase.objects.create( - account=self.other, suffix="shop" - ) - domain = HostingMailDomain.objects.create( - account=self.other, domain="bob.test" - ) - mailbox = HostingMailbox.objects.create( - mail_domain=domain, local_part="info" - ) - for model, resource in (("database", database), ("mailbox", mailbox)): - location = reverse(f"panel:{model}_provision", args=[resource.pk]) - self.assertEqual(self.client.post(location).status_code, 404) - for model, values in ( - ("database", {"suffix": "test"}), - ("mailbox", {"local_part": "test"}), - ): - path = reverse(f"panel:{model}_create", args=[self.other.pk]) - self.assertEqual(self.client.post(path, values).status_code, 404) + self.assertEqual(self.client.get(create).status_code, 403) + self.assertEqual( + self.client.post(create, payload).status_code, 403 + ) + self.assertEqual(self.client.post(provision).status_code, 403) self.assertFalse(DatabaseProvisioning.objects.exists()) self.assertFalse(MailboxProvisioning.objects.exists()) - - original = request_reseller_resource - - def revoke_before_save(*args, **kwargs): - Reseller.objects.filter(pk=self.alice.pk).update( - manage_resources=False - ) - return original(*args, **kwargs) - - path = reverse("panel:database_create", args=[self.account.pk]) - with patch( - "coulobre.hosting.views.request_reseller_resource", - side_effect=revoke_before_save, - ): - self.assertEqual( - self.client.post(path, {"suffix": "test"}).status_code, 403 - ) - self.assertFalse(self.account.databases.exists()) self.assertFalse(self.alice.audit_events.exists()) @override_settings(LOCAL_DATABASE_PROVISIONING=False) @@ -278,5 +207,5 @@ class ResellerOnboardingTests(TestCase): self.client.get(self.account.get_absolute_url()), "Provision database", ) - self.assertEqual(self.client.post(path).status_code, 404) + self.assertEqual(self.client.post(path).status_code, 403) self.assertFalse(DatabaseProvisioning.objects.exists()) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 0091d82..3a55db9 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -33,6 +33,7 @@ from .independent_website_views import ( ) 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_queue_views import MailQueueIndex, MailQueueView, mail_queue_action @@ -85,6 +86,7 @@ from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"), path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), path( "mail-domains//queue/change/", diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 30762be..fbb20d8 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -37,6 +37,7 @@ from coulobre.sftp_keys import public_key_fingerprint from .access import ( OperatorOnlyMixin, TenantScopeMixin, + can_manage_hosting, customer_for_user, is_tenant, manages_account, @@ -138,8 +139,6 @@ from .php_versions import ( from .phpmyadmin import phpmyadmin_available from .reseller_accounts import create_reseller_account, save_operator_account from .reseller_onboarding import ( - provision_reseller_resource, - request_reseller_resource, scoped_customers, ) from .resource_requests import ( @@ -620,8 +619,6 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") and user.has_perm("hosting.view_hostingmaildomain") ) - manage_resources = reseller is not None and reseller.manage_resources - context["reseller_resource_management"] = manage_resources context["reseller_customer_link"] = reseller is not None and ( self.object.customer_id is None and scoped_customers(reseller) @@ -648,7 +645,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): can_manage = ( website_provisioning and not self.object.services_suspended - and (tenant or user.has_perm(CHANGE_ACCOUNTS)) + and can_manage_hosting(user, (CHANGE_ACCOUNTS,)) and getattr(self.request, "impersonation", None) is None ) context["independent_websites"] = [ @@ -846,9 +843,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) ) databases = self.object.databases.select_related("provisioning") - if manage_resources or ( - not tenant and user.has_perms(PROVISION_DATABASE) - ): + if not tenant and user.has_perms(PROVISION_DATABASE): context["manage_database_provisioning"] = True context["local_database_enabled"] = panel_feature_allowed( "LOCAL_DATABASE_PROVISIONING" @@ -856,7 +851,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["databases"] = databases if tenant or user.has_perm(VIEW_DNS_ZONES): zone_list = self.object.dns_zones.all() - if tenant and getattr(self.request, "impersonation", None) is None: + if ( + customer + and getattr(self.request, "impersonation", None) is None + ): zone_list = zone_list.select_related("publication").defer( "publication__manifest" ) @@ -941,9 +939,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object ).select_related("mail_domain", "provisioning") - if manage_resources or ( - not tenant and user.has_perms(PROVISION_MAILBOX) - ): + if not tenant and user.has_perms(PROVISION_MAILBOX): context["manage_mailbox_provisioning"] = True context["local_mailbox_enabled"] = panel_feature_allowed( "LOCAL_MAILBOX_PROVISIONING" @@ -1986,13 +1982,9 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def customer(self): return customer_for_user(self.request.user) - @cached_property - def reseller(self): - return reseller_for_user(self.request.user) - def has_permission(self): - if self.reseller is not None: - return self.reseller.manage_resources + if reseller_for_user(self.request.user) is not None: + return False return self.customer is not None or super().has_permission() @cached_property @@ -2000,8 +1992,6 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): accounts = HostingAccount.objects.filter(retired_at__isnull=True) if self.customer is not None: accounts = accounts.filter(customer=self.customer) - if self.reseller is not None: - accounts = accounts.filter(reseller=self.reseller) return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): @@ -2035,21 +2025,11 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def form_valid(self, form): try: with support_write_session(self.request) as session: - if self.reseller is not None: - self.object = request_reseller_resource( - self.reseller, - self.account.pk, - self.create_request, - form.cleaned_data, - ) - else: - self.object = self.create_request( - self.account.pk, - **form.cleaned_data, - customer_id=self.customer.pk - if self.customer is not None - else None, - ) + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk if self.customer else None, + ) if session is not None: CustomerImpersonationAction.objects.create( session=session, @@ -2095,36 +2075,16 @@ class DownloadDatabaseManifest( ) -class ResourceProvisioningRequest(PermissionRequiredMixin, View): - @cached_property - def reseller(self): - return reseller_for_user(self.request.user) - - def has_permission(self): - if self.reseller is not None: - return self.reseller.manage_resources - return ( - customer_for_user(self.request.user) is None - and super().has_permission() - ) - +class ResourceProvisioningRequest( + OperatorOnlyMixin, PermissionRequiredMixin, View +): def post(self, request, pk): if not panel_feature_allowed(self.enabled_setting): raise Http404 - queryset = self.queryset.all() - if self.reseller is not None: - queryset = queryset.filter( - **{f"{self.account_relation}__reseller": self.reseller} - ) - resource = get_object_or_404(queryset, pk=pk) + resource = get_object_or_404(self.queryset, pk=pk) account = self.get_account(resource) try: - if self.reseller is None: - self.provision(resource) - else: - provision_reseller_resource( - self.reseller, account.pk, self.provision, resource - ) + self.provision(resource) except HostingAccount.DoesNotExist as error: raise Http404 from error except ValidationError as error: @@ -2136,7 +2096,6 @@ class RequestDatabaseProvisioning(ResourceProvisioningRequest): permission_required = PROVISION_DATABASE enabled_setting = "LOCAL_DATABASE_PROVISIONING" queryset = HostingDatabase.objects.select_related("account") - account_relation = "account" provision = staticmethod(queue_database_provisioning) @staticmethod @@ -2248,6 +2207,8 @@ class DnsZoneEdit(DnsZoneEditor): extra_context = {"page_title": "Edit DNS zone"} def has_permission(self): + if reseller_for_user(self.request.user) is not None: + return False if is_tenant(self.request.user): return getattr(self.request, "impersonation", None) is None and ( self.zone.delegate_dns @@ -2396,6 +2357,8 @@ class RequestDnsPublication(PermissionRequiredMixin, View): permission_required = PUBLISH_DNS def has_permission(self): + if reseller_for_user(self.request.user) is not None: + return False if is_tenant(self.request.user): return getattr(self.request, "impersonation", None) is None return super().has_permission() @@ -2486,7 +2449,6 @@ class RequestMailboxProvisioning(ResourceProvisioningRequest): permission_required = PROVISION_MAILBOX enabled_setting = "LOCAL_MAILBOX_PROVISIONING" queryset = HostingMailbox.objects.select_related("mail_domain__account") - account_relation = "mail_domain__account" provision = staticmethod(queue_mailbox_provisioning) @staticmethod diff --git a/src/coulobre/hosting/website_file_views.py b/src/coulobre/hosting/website_file_views.py index e65fc3a..ce6a86f 100644 --- a/src/coulobre/hosting/website_file_views.py +++ b/src/coulobre/hosting/website_file_views.py @@ -19,7 +19,7 @@ from coulobre.website_files import ( directory_parts, ) -from .access import TenantScopeMixin, is_tenant +from .access import TenantScopeMixin, can_manage_hosting from .independent_websites import active_websites from .installation_features import panel_feature_allowed from .models import HostingAccount @@ -36,7 +36,7 @@ def can_manage_website_files(request): return ( panel_feature_allowed("WEB_FILE_MANAGER") and getattr(request, "impersonation", None) is None - and (is_tenant(user) or user.has_perms(MANAGE_FILES)) + and can_manage_hosting(user, MANAGE_FILES) ) diff --git a/src/coulobre/hosting/website_job_views.py b/src/coulobre/hosting/website_job_views.py index 66a8268..bf9d27e 100644 --- a/src/coulobre/hosting/website_job_views.py +++ b/src/coulobre/hosting/website_job_views.py @@ -15,7 +15,7 @@ from django.views.generic.detail import SingleObjectMixin from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command -from .access import TenantScopeMixin, is_tenant +from .access import TenantScopeMixin, can_manage_hosting from .independent_websites import check_actor from .installation_features import panel_feature_allowed from .models import HostingAccount @@ -35,7 +35,7 @@ def can_manage_website_jobs(request): return ( panel_feature_allowed("WEBSITE_JOBS") and getattr(request, "impersonation", None) is None - and (is_tenant(user) or user.has_perms(MANAGE_JOBS)) + and can_manage_hosting(user, MANAGE_JOBS) ) diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 073d2f7..b07e840 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -211,7 +211,15 @@ def groups_for(request, *, customer, manager): ), ], ), - ("Email Manager", hosted("email", "forwarders", "replies")), + ( + "Email Manager", + hosted("email", "forwarders", "replies") + + ( + [link("mail_delivery", "Mail delivery")] + if panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + else [] + ), + ), ( "Advanced Features", [ @@ -250,6 +258,10 @@ def groups_for(request, *, customer, manager): "hosting.view_hostingaccount" ): admin_tools.append(link("mail_queue_index", "Mail Queue")) + if user.is_superuser and panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" + ): + admin_tools.append(link("mail_delivery", "Mail delivery")) if user.has_perm("hosting.view_servicehealth"): admin_tools.append(link("service_health", "System Services")) if user.is_superuser: diff --git a/src/coulobre/mail_delivery.py b/src/coulobre/mail_delivery.py new file mode 100644 index 0000000..6d89896 --- /dev/null +++ b/src/coulobre/mail_delivery.py @@ -0,0 +1,191 @@ +import json +import re +import subprocess +import time +from dataclasses import dataclass + +from .domain_names import canonical_domain + +OPERATION = "inspect_delivery" +MAX_AGE = 7 * 24 * 60 * 60 +MAX_ENTRIES = 10000 +MAX_RESULTS = 40 +SERVICES = {"qmgr", "smtpd", "smtp", "lmtp", "local", "virtual", "pipe"} +LINE = re.compile(r"([A-Za-z0-9]{5,32}): (.*)") +ADDRESS = re.compile(r"[^<>\s\x00-\x1f]{1,254}") +SENDER = re.compile(r"^from=<([^<>]*)>,") +RECIPIENT = re.compile(r"^to=<([^<>]*)>, (?:orig_to=<([^<>]*)>, )?") +SASL = re.compile( + r"^client=[^,]+, sasl_method=[A-Za-z0-9_-]+, sasl_username=([^,\s]+)" +) +STATUS = re.compile(r"(?:^|, )status=(sent|deferred|bounced|expired)\b") + + +@dataclass(frozen=True) +class MailDeliveryRequest: + domain: str + start: int + end: int + sender: str = "" + recipient: str = "" + + def __post_init__(self): + object.__setattr__(self, "domain", canonical_domain(self.domain)) + if ( + type(self.start) is not int + or type(self.end) is not int + or self.start <= 0 + or not 0 < self.end - self.start <= MAX_AGE + ): + raise ValueError( + "Choose a valid time range of at most seven days." + ) + for query in (self.sender, self.recipient): + if not isinstance(query, str) or ( + query and not ADDRESS.fullmatch(query) + ): + raise ValueError("Use an email address for the filter.") + + def manifest(self): + return { + "operation": OPERATION, + "domain": self.domain, + "start": self.start, + "end": self.end, + "sender": self.sender, + "recipient": self.recipient, + } + + @classmethod + def from_manifest(cls, data): + fields = {"operation", "domain", "start", "end", "sender", "recipient"} + if data.keys() != fields or data["operation"] != OPERATION: + raise ValueError("Expected a mail delivery request.") + return cls( + data["domain"], + data["start"], + data["end"], + data["sender"], + data["recipient"], + ) + + +def address(value): + value = value or "" + return value if ADDRESS.fullmatch(value) else "" + + +def domain_of(address): + return address.rpartition("@")[2].lower() if "@" in address else "" + + +def project_delivery(lines, request): + envelopes = {} + authenticated = {} + records = [] + count = 0 + for encoded in lines: + count += 1 + entry = json.loads(encoded) + identity = entry.get("SYSLOG_IDENTIFIER", "") + service = ( + identity.rpartition("/")[2] if isinstance(identity, str) else "" + ) + if service not in SERVICES or entry.get("_EXE") != ( + f"/usr/lib/postfix/sbin/{service}" + ): + continue + message = entry.get("MESSAGE") + timestamp = entry.get("__REALTIME_TIMESTAMP") + if not isinstance(message, str) or not ( + isinstance(timestamp, str) + and timestamp.isdecimal() + and len(timestamp) <= 18 + ): + continue + match = LINE.fullmatch(message) + if not match: + continue + queue_id, text = match.groups() + if service == "qmgr": + if text == "removed": + envelopes.pop(queue_id, None) + authenticated.pop(queue_id, None) + elif sender := SENDER.match(text): + envelopes[queue_id] = address(sender[1]) + continue + if service == "smtpd": + if login := SASL.match(text): + authenticated[queue_id] = address(login[1]) + continue + + addresses = RECIPIENT.match(text) + if not addresses: + continue + status = STATUS.search(text, addresses.end() - 2) + recipient, original = map(address, addresses.groups()) + sender = envelopes.get(queue_id, "") + login = authenticated.get(queue_id, "") + if not status or not recipient: + continue + if request.domain != domain_of(original or recipient) and not ( + login + and login.casefold() == sender.casefold() + and domain_of(login) == request.domain + ): + continue + if request.sender and sender.casefold() != request.sender.casefold(): + continue + if request.recipient and request.recipient.casefold() not in ( + recipient.casefold(), + original.casefold(), + ): + continue + records.append( + { + "queue_id": queue_id, + "timestamp": int(timestamp) // 1000000, + "sender": sender, + "recipient": recipient, + "original_recipient": original, + "status": status[1], + } + ) + return { + "events": list(reversed(records[-MAX_RESULTS:])), + "partial": count > MAX_ENTRIES or len(records) > MAX_RESULTS, + } + + +def inspect_delivery(request): + now = int(time.time()) + if request.end > now + 300 or request.start < now - MAX_AGE - 300: + raise ValueError("Delivery tracking covers the last seven days.") + arguments = [ + "/usr/bin/journalctl", + "--no-pager", + "--quiet", + "--output=json", + "--output-fields=MESSAGE,SYSLOG_IDENTIFIER,_EXE", + f"--since=@{request.start}", + f"--until=@{request.end}", + f"--lines={MAX_ENTRIES + 1}", + ] + for prefix in ("postfix", "postfix/submission", "postfix/smtps"): + for service in sorted(SERVICES): + arguments.append(f"--identifier={prefix}/{service}") + try: + result = subprocess.run( + arguments, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=20, + check=True, + env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"}, + ) + except (subprocess.SubprocessError, OSError): + raise ValueError( + "The receiver could not read the mail journal." + ) from None + return project_delivery(result.stdout.splitlines(), request) diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index 4f40fe4..8251302 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -166,9 +166,12 @@ class MailboxSigningRequest: def parse_mailbox_request(data): + from .mail_delivery import OPERATION, MailDeliveryRequest from .mail_policy import OPERATIONS, parse_mail_policy from .mail_queue import MailQueueAction, MailQueueRequest + if isinstance(data, dict) and data.get("operation") == OPERATION: + return MailDeliveryRequest.from_manifest(data) if isinstance(data, dict) and data.get("operation") in { "inspect_queue", "inspect_queue_entries", @@ -210,6 +213,7 @@ def mailbox_request_identity(spec): def apply_mailbox_request(request): + from .mail_delivery import MailDeliveryRequest, inspect_delivery from .mail_policy import MailRouting, MailVacation from .mail_queue import ( MailQueueAction, @@ -218,6 +222,8 @@ def apply_mailbox_request(request): inspect_queue, ) + if isinstance(request, MailDeliveryRequest): + return inspect_delivery(request) if isinstance(request, MailQueueRequest): return inspect_queue(request) if isinstance(request, MailQueueAction): From 0263aa4bfa4168ff0dd5c63d3f27a28ff2828ae1 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 22:41:57 +0100 Subject: [PATCH 4/9] Manage website TLS certificates from customer workspaces --- src/coulobre/hosting/certificate_uploads.py | 97 ++++++ src/coulobre/hosting/certificate_views.py | 202 ++++++++++++ .../0068_website_certificate_jobs.py | 67 ++++ .../migrations/0069_certificate_uploads.py | 17 + src/coulobre/hosting/models.py | 18 ++ src/coulobre/hosting/tasks.py | 70 ++++ .../hosting/customer_certificates.html | 63 ++++ .../hosting/operator_certificates.html | 27 ++ .../hosting/test_certificate_workspace.py | 96 ++++++ .../hosting/test_reseller_onboarding.py | 1 - src/coulobre/hosting/urls.py | 7 + src/coulobre/hosting/workspaces.py | 10 +- src/coulobre/web_certificates.py | 298 ++++++++++++++++++ src/coulobre/web_node.py | 31 +- src/coulobre/web_node_tls.py | 74 +++-- 15 files changed, 1056 insertions(+), 22 deletions(-) create mode 100644 src/coulobre/hosting/certificate_uploads.py create mode 100644 src/coulobre/hosting/certificate_views.py create mode 100644 src/coulobre/hosting/migrations/0068_website_certificate_jobs.py create mode 100644 src/coulobre/hosting/migrations/0069_certificate_uploads.py create mode 100644 src/coulobre/hosting/templates/hosting/customer_certificates.html create mode 100644 src/coulobre/hosting/templates/hosting/operator_certificates.html create mode 100644 src/coulobre/hosting/test_certificate_workspace.py create mode 100644 src/coulobre/web_certificates.py diff --git a/src/coulobre/hosting/certificate_uploads.py b/src/coulobre/hosting/certificate_uploads.py new file mode 100644 index 0000000..1ad3b87 --- /dev/null +++ b/src/coulobre/hosting/certificate_uploads.py @@ -0,0 +1,97 @@ +import json +from base64 import urlsafe_b64encode +from hashlib import sha256 + +from cryptography.fernet import Fernet, InvalidToken, MultiFernet +from django import forms +from django.conf import settings +from django.views.decorators.debug import sensitive_variables + +from coulobre.web_certificates import ( + MAX_CERTIFICATE_BYTES, + MAX_KEY_BYTES, + validated_pem, +) + +UPLOAD_LIFETIME = 60 * 60 + + +class CertificateUploadForm(forms.Form): + chain = forms.FileField( + label="Certificate chain (PEM)", + help_text="Include the website certificate followed by intermediates.", + ) + key = forms.FileField( + label="Private key (PEM)", + help_text="Use its matching unencrypted private key.", + ) + + @sensitive_variables() + def clean(self): + data = super().clean() + if self.errors: + return data + try: + chain, key = ( + read_upload(data[name], limit) + for name, limit in ( + ("chain", MAX_CERTIFICATE_BYTES), + ("key", MAX_KEY_BYTES), + ) + ) + data["chain_pem"], data["key_pem"] = validated_pem(chain, key) + except (UnicodeError, ValueError) as error: + raise forms.ValidationError( + "Provide a valid PEM certificate chain and matching key." + ) from error + return data + + +def read_upload(upload, limit): + data = upload.read(limit + 1) + if len(data) > limit: + raise ValueError("The uploaded file exceeds the size limit.") + return data.decode("ascii") + + +def upload_encryption(): + return MultiFernet( + [ + Fernet( + urlsafe_b64encode( + sha256( + b"coulobre-website-certificate\0" + + secret.encode("utf-8") + ).digest() + ) + ) + for secret in (settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS) + ] + ) + + +@sensitive_variables() +def seal_upload(site, customer_id, form): + response = json.dumps( + [ + site.manifest(), + customer_id, + form.cleaned_data["chain_pem"], + form.cleaned_data["key_pem"], + ] + ).encode("utf-8") + return upload_encryption().encrypt(response).decode("ascii") + + +@sensitive_variables() +def open_upload(job): + try: + payload = upload_encryption().decrypt( + job.encrypted_upload.encode("ascii"), ttl=UPLOAD_LIFETIME + ) + site, customer_id, chain, key = json.loads(payload) + if site == job.site and customer_id == job.requested_customer_id: + return chain, key + except (InvalidToken, UnicodeError, ValueError): + pass + raise ValueError("The certificate upload expired. Upload the files again.") diff --git a/src/coulobre/hosting/certificate_views.py b/src/coulobre/hosting/certificate_views.py new file mode 100644 index 0000000..ed724c2 --- /dev/null +++ b/src/coulobre/hosting/certificate_views.py @@ -0,0 +1,202 @@ +from datetime import timedelta + +from django.conf import settings +from django.core.exceptions import PermissionDenied, ValidationError +from django.core.paginator import Paginator +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.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 coulobre.domain_names import canonical_domain +from coulobre.web_certificates import ACTIONS +from coulobre.web_node import WebSite + +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 .resource_requests import lock_hosting_account, require_active_services +from .sftp import site_is_active + + +def account_certificate_sites(account): + sites = [ + website.spec + for website in active_websites(account).filter(suspended=False) + ] + if site_is_active(account): + sites.insert(0, WebSite(account.pk, account.primary_domain)) + return {site.domain: site for site in sites} + + +@transaction.atomic +def queue_certificate( + account, site, actor, action, customer_id, *, encrypted_upload="" +): + account = lock_hosting_account(account.pk, customer_id) + require_active_services(account) + if account_certificate_sites(account).get(site.domain) != site: + raise ValidationError("This website is no longer active.") + 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() + ): + raise ValidationError( + "Wait 12 hours before requesting another reissue." + ) + WebsiteCertificateJob.objects.create( + account=account, + site=site.manifest(), + actor=actor, + requested_customer_id=customer_id, + action=action, + encrypted_upload=encrypted_upload, + ) + + +@never_cache +@sensitive_variables("encrypted_upload", "upload_form") +@require_http_methods(("GET", "HEAD", "POST")) +def customer_certificates(request, pk): + customer = customer_for_user(request.user) + if customer is None: + raise PermissionDenied + account = get_object_or_404( + HostingAccount, pk=pk, customer=customer, retired_at__isnull=True + ) + sites = account_certificate_sites(account) + try: + domain = canonical_domain( + request.GET.get( + "domain", next(iter(sites), account.primary_domain) + ) + ) + except ValueError as error: + raise Http404 from error + site = sites.get(domain) + if "domain" in request.GET and site is None: + raise Http404 + tab = request.GET.get("tab", "manage") + if tab not in {"manage", "acme", "history"}: + raise Http404 + enabled = panel_feature_allowed("LOCAL_WEB_HTTPS") + problem = "" + is_upload = ( + request.method == "POST" and request.POST.get("action") == "upload" + ) + upload_form = CertificateUploadForm( + 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()): + if not site or not enabled: + raise Http404 + action = request.POST.get("action") + if action not in ACTIONS: + raise Http404 + try: + encrypted_upload = ( + seal_upload(site, customer.pk, upload_form) + if is_upload + else "" + ) + queue_certificate( + account, + site, + request.user, + action, + customer.pk, + encrypted_upload=encrypted_upload, + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + problem = " ".join(error.messages) + else: + return redirect( + reverse( + "panel:customer_certificates", + args=[account.pk], + query={"domain": domain, "tab": "history"}, + ) + ) + history = [] + certificate = None + if site: + jobs = account.certificate_jobs.filter( + site=site.manifest(), + requested_customer_id=customer.pk, + ) + history = list(jobs.order_by("-pk")[:25]) + certificate = jobs.exclude(certificate={}).order_by("-pk").first() + return render( + request, + "hosting/customer_certificates.html", + { + "account": account, + "sites": sites, + "domain": domain, + "tab": tab, + "certificate": certificate, + "upload_form": upload_form, + "history": history, + "enabled": enabled, + "problem": problem, + "site": site, + }, + ) + + +@never_cache +@require_safe +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 + accounts = HostingAccount.objects.filter(retired_at__isnull=True).order_by( + "primary_domain" + ) + page_obj = Paginator(accounts, 30).get_page(request.GET.get("page")) + sites = ( + [ + ( + site.domain, + account, + account.certificate_jobs.filter(site=site.manifest()) + .exclude(certificate={}) + .order_by("-pk") + .first(), + ) + for account in page_obj + for site in account_certificate_sites(account).values() + ] + if mode == "websites" + else [] + ) + return render( + request, + "hosting/operator_certificates.html", + { + "mode": mode, + "sites": sites, + "page_obj": page_obj, + "is_paginated": page_obj.has_other_pages, + "panel_origin": settings.PASSWORD_RESET_ORIGIN, + "imap_host": settings.MAIL_IMAP_HOST, + "submission_host": settings.MAIL_SUBMISSION_HOST, + }, + ) diff --git a/src/coulobre/hosting/migrations/0068_website_certificate_jobs.py b/src/coulobre/hosting/migrations/0068_website_certificate_jobs.py new file mode 100644 index 0000000..511c7b5 --- /dev/null +++ b/src/coulobre/hosting/migrations/0068_website_certificate_jobs.py @@ -0,0 +1,67 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:38 + +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", "0067_mail_delivery_search"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="WebsiteCertificateJob", + 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)), + ("site", models.JSONField()), + ("action", models.CharField(max_length=12)), + ( + "requested_customer_id", + models.PositiveBigIntegerField(null=True), + ), + ("certificate", models.JSONField(default=dict)), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="certificate_jobs", + to="hosting.hostingaccount", + ), + ), + ( + "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/0069_certificate_uploads.py b/src/coulobre/hosting/migrations/0069_certificate_uploads.py new file mode 100644 index 0000000..9996833 --- /dev/null +++ b/src/coulobre/hosting/migrations/0069_certificate_uploads.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0068_website_certificate_jobs"), + ] + + operations = [ + migrations.AddField( + model_name="websitecertificatejob", + name="encrypted_upload", + field=models.TextField(blank=True, default=""), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index f759da4..f100706 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1019,6 +1019,24 @@ class WebHTTPS(ProvisioningJob): verbose_name = "website HTTPS request" +class WebsiteCertificateJob(ProvisioningJob): + account = models.ForeignKey( + HostingAccount, + on_delete=models.CASCADE, + related_name="certificate_jobs", + ) + site = models.JSONField() + action = models.CharField(max_length=12) + actor = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.SET_NULL, + null=True, + ) + requested_customer_id = models.PositiveBigIntegerField(null=True) + encrypted_upload = models.TextField(blank=True, default="") + certificate = models.JSONField(default=dict) + + class WebsiteAlias(ProvisioningJob): wait_for_website = models.BooleanField(default=False) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index aba4cfe..0715366 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -64,6 +64,7 @@ from .models import ( WebHTTPS, WebProvisioningPlan, WebsiteAlias, + WebsiteCertificateJob, WebsiteRestoreJob, WebsiteScheduledJob, ) @@ -221,7 +222,15 @@ def dispatch_site_storage_limits(): @shared_task def dispatch_web_https(): + from .certificate_uploads import UPLOAD_LIFETIME + + WebsiteCertificateJob.objects.filter( + requested_at__lte=timezone.now() - timedelta(seconds=UPLOAD_LIFETIME) + ).exclude(encrypted_upload="").update(encrypted_upload="") if settings.LOCAL_WEB_HTTPS: + dispatch_provisioning_jobs( + WebsiteCertificateJob, apply_certificate_job, WEB_HTTPS_QUEUE + ) dispatch_provisioning_jobs( IndependentWebsite, provision_independent_website, @@ -1392,3 +1401,64 @@ def search_mail_delivery(job_id): apply, "The mail node did not return a delivery report.", ) + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def apply_certificate_job(job_id): + from django.views.decorators.debug import sensitive_variables + + from coulobre.web_certificates import WebCertificateRequest + + from .certificate_uploads import open_upload + from .certificate_views import account_certificate_sites + from .node_client import apply_on_local_node + + @sensitive_variables() + def apply(job): + site = WebSite.from_manifest(job.site) + with transaction.atomic(): + try: + account = lock_hosting_account( + job.account_id, job.requested_customer_id + ) + except HostingAccount.DoesNotExist: + raise ValueError( + "This hosting account is no longer available." + ) from None + if ( + account.services_suspended + or account.retired_at is not None + or account_certificate_sites(account).get(site.domain) != site + ): + raise ValueError("This website is no longer active.") + spec = WebCertificateRequest( + site, + job.action, + *(open_upload(job) if job.action == "upload" else ()), + ) + reply = apply_on_local_node( + spec, + "/run/coulobre-https-apply.sock", + "web node", + "certificate operation", + identity=spec.identity(), + ) + certificate = reply.get("certificate") + if ( + not isinstance(certificate, dict) + or type(certificate.get("installed")) is not bool + ): + raise ValueError("The web node did not return certificate status.") + return {"certificate": certificate} + + if settings.LOCAL_WEB_HTTPS: + run_provisioning_job( + WebsiteCertificateJob.objects.all(), + job_id, + apply, + "The HTTPS worker did not confirm the certificate operation.", + ) + + WebsiteCertificateJob.objects.filter( + pk=job_id, finished_at__isnull=False + ).exclude(encrypted_upload="").update(encrypted_upload="") diff --git a/src/coulobre/hosting/templates/hosting/customer_certificates.html b/src/coulobre/hosting/templates/hosting/customer_certificates.html new file mode 100644 index 0000000..d6ccd1b --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_certificates.html @@ -0,0 +1,63 @@ +{% extends "hosting/base.html" %} +{% block title %}SSL Certificates · Coulobre Panel{% endblock %} +{% block content %} +

SSL Certificates

{{ account.primary_domain }}

+ {% if sites %} +
+
+ + + + +
+
+ + {% if problem %}{% endif %} + {% if tab == 'manage' %} +
+

Last observed certificate

+ {% if certificate.certificate.installed %} +
+
Issuer
{{ certificate.certificate.issuer }}
+
Names
{{ certificate.certificate.names|join:", " }}
+
Expires
{{ certificate.certificate.not_after }}
+
Checked
{{ certificate.finished_at|date:"j M Y H:i" }} UTC
+
+ {% elif certificate %}

No HTTPS certificate was installed when last checked.

+ {% else %}

Check the website to see its current certificate.

{% endif %} + {% if enabled %} +
+ {% csrf_token %} + + {% if certificate.certificate.source == "acme" %} + {% elif not certificate.certificate.installed %}{% endif %} +
+ {% endif %} +
+ {% if enabled %} +
+ Upload certificate +
{% csrf_token %}{{ upload_form.as_div }} + +
+
+ {% endif %} + {% elif tab == 'acme' %} +
+
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.

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

    {{ job.problem }}

    {% endif %}
  • + {% empty %}
  • No certificate operations yet.
  • {% endfor %}
+
+ {% endif %} + {% else %}

Activate a website to manage its certificate.

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

SSL Overview

+ + {% if mode == 'server' %} +
+

Configured endpoints

+
Panel origin
{{ panel_origin|default:"Unavailable" }}
+
IMAP
{{ imap_host|default:"Unavailable" }}
+
SMTP submission
{{ submission_host|default:"Unavailable" }}
+
+ Service health +
+ {% else %} +
+ + {% for domain, account, job in sites %} + + + {% empty %}{% endfor %} +
WebsiteAccountLast known issuerExpiry
{{ domain }}{{ account.name }}{{ job.certificate.issuer|default:"Unavailable" }}{{ job.certificate.not_after|default:"Unavailable" }}
No active websites on this page.
{% include "hosting/pagination.html" %}
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/test_certificate_workspace.py b/src/coulobre/hosting/test_certificate_workspace.py new file mode 100644 index 0000000..3cd7820 --- /dev/null +++ b/src/coulobre/hosting/test_certificate_workspace.py @@ -0,0 +1,96 @@ +from datetime import UTC, datetime, timedelta +from unittest.mock import patch + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.x509.oid import NameOID +from django.contrib.auth import get_user_model +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from .models import ( + Customer, + HostingAccount, + WebActivation, + WebProvisioningPlan, + WebsiteCertificateJob, +) +from .tasks import apply_certificate_job + + +def certificate_files(domain): + key = Ed25519PrivateKey.generate() + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, domain)]) + now = datetime.now(UTC) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(days=1)) + .not_valid_after(now + timedelta(days=60)) + .add_extension( + x509.SubjectAlternativeName([x509.DNSName(domain)]), + critical=False, + ) + .sign(key, None) + ) + return ( + certificate.public_bytes(serialization.Encoding.PEM), + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ), + ) + + +@override_settings(LOCAL_WEB_HTTPS=True) +class CertificateWorkspaceTests(TestCase): + def test_upload_is_scoped_encrypted_and_erased_after_worker_use(self): + users = get_user_model().objects + customer = Customer.objects.create(user=users.create_user("customer")) + outsider = Customer.objects.create(user=users.create_user("outsider")) + account = HostingAccount.objects.create( + name="Shop", primary_domain="shop.example.test", customer=customer + ) + plan = WebProvisioningPlan.objects.create( + account=account, + primary_domain=account.primary_domain, + apache_config="Installed", + completed_at=timezone.now(), + ) + WebActivation.objects.create(plan=plan, finished_at=timezone.now()) + url = reverse("panel:customer_certificates", args=[account.pk]) + self.client.force_login(outsider.user) + self.assertEqual(self.client.get(url).status_code, 404) + self.client.force_login(customer.user) + self.assertContains(self.client.get(url), "Upload certificate") + chain, key = certificate_files(account.primary_domain) + upload = self.client.post( + url, + { + "action": "upload", + "chain": SimpleUploadedFile("chain.pem", chain), + "key": SimpleUploadedFile("key.pem", key), + }, + ) + self.assertEqual(upload.status_code, 302) + job = WebsiteCertificateJob.objects.get() + self.assertTrue(job.encrypted_upload) + self.assertNotIn("PRIVATE KEY", job.encrypted_upload) + with patch( + "coulobre.hosting.node_client.apply_on_local_node", + return_value={"certificate": {"installed": True}}, + ) as apply: + apply_certificate_job(job.pk) + job.refresh_from_db() + self.assertEqual(job.state, "configured") + self.assertEqual(job.encrypted_upload, "") + spec = apply.call_args.args[0] + self.assertEqual(spec.key.encode("ascii"), key) + self.assertNotIn("key", apply.call_args.kwargs["identity"]) diff --git a/src/coulobre/hosting/test_reseller_onboarding.py b/src/coulobre/hosting/test_reseller_onboarding.py index 199cc33..3380746 100644 --- a/src/coulobre/hosting/test_reseller_onboarding.py +++ b/src/coulobre/hosting/test_reseller_onboarding.py @@ -1,4 +1,3 @@ - from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase, override_settings diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 3a55db9..a8ba4a2 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -20,6 +20,7 @@ from .account_security import ( VerifyEmailView, ) from .backup_restores import RestoreKind +from .certificate_views import customer_certificates, operator_certificates from .credential_views import DatabaseCredentialView, MailboxCredentialView from .customer_backup_views import CustomerBackupView, CustomerRestoreView from .dns_defaults_views import DnsDefaultsView @@ -86,6 +87,12 @@ from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path("ssl/", operator_certificates, name="operator_certificates"), + path( + "hosting//certificates/", + customer_certificates, + name="customer_certificates", + ), 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/workspaces.py b/src/coulobre/hosting/workspaces.py index b07e840..2a47345 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -21,6 +21,7 @@ CUSTOMER_PAGES = { "dns": ("DNS Editor", "account", "domains-dns"), "php": ("PHP Settings", "account", "websites"), "files": ("File Manager", "website_files", ""), + "certificates": ("SSL Certificates", "customer_certificates", ""), "sftp": ("SFTP Users", "sftp_keys", ""), "databases": ("Databases", "account", "databases"), "email": ("Email Accounts", "account", "email"), @@ -207,7 +208,13 @@ def groups_for(request, *, customer, manager): [ link("accounts", "My hosting"), *hosted( - "domains", "dns", "sftp", "databases", "php", "files" + "domains", + "dns", + "certificates", + "sftp", + "databases", + "php", + "files", ), ], ), @@ -284,6 +291,7 @@ def groups_for(request, *, customer, manager): link("theme_management", "Themes"), link("announcements", "Message"), link("directadmin_guide", "Import"), + link("operator_certificates", "SSL Overview"), ) ) if user.is_superuser: diff --git a/src/coulobre/web_certificates.py b/src/coulobre/web_certificates.py new file mode 100644 index 0000000..d9ffdf8 --- /dev/null +++ b/src/coulobre/web_certificates.py @@ -0,0 +1,298 @@ +import fcntl +import os +import shutil +from dataclasses import dataclass, field +from pathlib import Path +from tempfile import TemporaryDirectory +from uuid import uuid4 + +from cryptography import x509 +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives import serialization + +from .node_files import ( + check_root_file, + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) +from .web_node import WebSite +from .web_node_apply import ( + SitePaths, + check_configuration, + check_site_link, + enable_apache_site, + locked_web_node, + run, +) +from .web_node_tls import ( + certificate_lineage, + check_https_prerequisites, + custom_lineage, + https_paths, + install_https_configuration, + provision_https, + render_https_configuration, + request_certificate, + resolved_certificate_files, + validate_certificate_files, +) + +ACTIONS = ("inspect", "issue", "reissue", "upload") +MAX_CERTIFICATE_BYTES = 32768 +MAX_KEY_BYTES = 8192 +CERTIFICATE_REQUEST_LIMIT = 65536 + + +@dataclass(frozen=True) +class WebCertificateRequest: + site: WebSite + action: str + chain: str = field(default="", repr=False) + key: str = field(default="", repr=False) + + def __post_init__(self): + if self.action not in ACTIONS: + raise ValueError("Choose a supported certificate operation.") + if self.action == "upload": + check_pem_size(self.chain, MAX_CERTIFICATE_BYTES) + check_pem_size(self.key, MAX_KEY_BYTES) + elif self.chain or self.key: + raise ValueError("This operation does not accept uploaded files.") + + def identity(self): + return { + "operation": "manage_certificate", + "site": self.site.manifest(), + "action": self.action, + } + + def manifest(self): + return self.identity() | ( + {"chain": self.chain, "key": self.key} + if self.action == "upload" + else {} + ) + + @classmethod + def from_manifest(cls, data): + fields = {"operation", "site", "action"} + if data.get("action") == "upload": + fields |= {"chain", "key"} + if data.keys() != fields: + raise ValueError("Expected a certificate operation.") + return cls( + WebSite.from_manifest(data["site"]), + data["action"], + data.get("chain", ""), + data.get("key", ""), + ) + + +def check_pem_size(value, limit): + if ( + not isinstance(value, str) + or not value.isascii() + or not 1 <= len(value) <= limit + ): + raise ValueError("Upload a supported PEM file within the size limit.") + + +def validated_pem(chain, key): + check_pem_size(chain, MAX_CERTIFICATE_BYTES) + check_pem_size(key, MAX_KEY_BYTES) + try: + chain_data = x509.load_pem_x509_certificates(chain.encode("ascii")) + private = serialization.load_pem_private_key( + key.encode("ascii"), password=None + ) + public_format = serialization.PublicFormat.SubjectPublicKeyInfo + encoding = serialization.Encoding.PEM + if ( + not chain_data + or len(chain_data) > 16 + or chain_data[0].public_key().public_bytes(encoding, public_format) + != private.public_key().public_bytes(encoding, public_format) + ): + raise ValueError("The certificate and private key must match.") + return ( + "".join( + cert.public_bytes(encoding).decode("ascii") + for cert in chain_data + ), + private.private_bytes( + encoding, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ).decode("ascii"), + ) + except (TypeError, ValueError, UnsupportedAlgorithm, AttributeError): + raise ValueError( + "Provide a valid certificate chain and matching " + "unencrypted private key." + ) from None + + +def certificate_details(site): + paths = SitePaths.for_site(site) + config, enabled = https_paths(paths) + for directory in (config.parent, enabled.parent): + require_root_directory(directory) + if not config.exists() or not os.path.lexists(enabled): + return {"installed": False} + check_site_link(enabled, Path("../sites-available") / config.name) + check_configuration( + config, + render_https_configuration(site, socket_path=paths.apache_socket), + ) + path, _ = resolved_certificate_files(site) + check_root_file(path) + with path.open("rb") as source: + data = source.read(65537) + if len(data) > 65536: + raise ValueError("The website certificate is too large.") + try: + certificate = x509.load_pem_x509_certificate(data) + names = certificate.extensions.get_extension_for_class( + x509.SubjectAlternativeName + ).value.get_values_for_type(x509.DNSName) + except (ValueError, x509.ExtensionNotFound) as error: + raise ValueError( + "The website certificate could not be read." + ) from error + return { + "installed": True, + "source": "uploaded" + if certificate_lineage(site).name == "active" + else "acme", + "issuer": certificate.issuer.rfc4514_string()[:350], + "names": [name[:253] for name in names[:60]], + "not_after": certificate.not_valid_after_utc.isoformat(), + } + + +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": + provision_https(site) + elif request.action == "reissue": + reissue_certificate(site) + elif request.action == "upload": + install_uploaded_certificate( + site, *validated_pem(request.chain, request.key) + ) + with locked_web_node(fcntl.LOCK_SH): + check_https_prerequisites(site, SitePaths.for_site(site)) + return {"certificate": certificate_details(site)} + + +def replace_symlink(path, target): + with TemporaryDirectory(dir=path.parent) as directory: + staged = Path(directory) / "link" + staged.symlink_to(target) + staged.replace(path) + + +def reload_apache(): + run("/usr/sbin/apache2ctl", "configtest") + run("/usr/sbin/service", "apache2", "reload") + + +def reissue_certificate(site): + with locked_web_node(fcntl.LOCK_EX): + paths = SitePaths.for_site(site) + check_https_prerequisites(site, paths) + lineage = certificate_lineage(site) + if lineage.name == "active": + raise ValueError("This website uses an uploaded certificate.") + previous = {} + if lineage.exists(): + resolved_certificate_files(site) + previous = { + path: path.readlink() + for name in ("fullchain", "privkey", "cert", "chain") + if (path := lineage / f"{name}.pem").is_symlink() + } + try: + request_certificate(site, force=True) + apache, enabled = https_paths(paths) + install_https_configuration( + site, apache, enabled, socket_path=paths.apache_socket + ) + except (OSError, ValueError, KeyboardInterrupt): + for path, target in previous.items(): + replace_symlink(path, target) + if previous: + reload_apache() + raise + + +def install_uploaded_certificate(site, chain, key): + with locked_web_node(fcntl.LOCK_EX): + paths = SitePaths.for_site(site) + check_https_prerequisites(site, paths) + apache, enabled = https_paths(paths) + previous_config = None + if os.path.lexists(apache): + check_configuration( + apache, + render_https_configuration( + site, socket_path=paths.apache_socket + ), + ) + previous_config = read_root_file(apache) + root = custom_lineage(site) + require_root_directory(root.parent, create_mode=0o700) + require_root_directory(root, create_mode=0o700) + active = root / "active" + previous = None + if os.path.lexists(active): + resolved_certificate_files(site) + previous = active.readlink() + revision = root / str(uuid4()) + revision.mkdir(mode=0o700) + installed = False + created = [] + tried_reload = False + try: + certificate, private = ( + revision / "fullchain.pem", + revision / "privkey.pem", + ) + write_new_file(certificate, chain, mode=0o600) + write_new_file(private, key, mode=0o600) + validate_certificate_files(site, certificate, private) + replace_symlink(active, revision.name) + new_config = render_https_configuration( + site, socket_path=paths.apache_socket + ) + if previous_config is None: + write_new_file(apache, new_config, mode=0o644) + created.append(apache) + else: + replace_configuration(apache, new_config) + enable_apache_site(apache, enabled, created) + run("/usr/sbin/apache2ctl", "configtest") + tried_reload = True + run("/usr/sbin/service", "apache2", "reload") + installed = True + except (OSError, ValueError, KeyboardInterrupt): + if previous is None: + active.unlink(missing_ok=True) + else: + replace_symlink(active, previous) + for path in reversed(created): + path.unlink(missing_ok=True) + if previous_config is not None: + replace_configuration(apache, previous_config) + if tried_reload: + reload_apache() + raise + finally: + if not installed: + shutil.rmtree(revision) + if previous is not None: + shutil.rmtree(root / previous) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 8d9e8f5..ae2a100 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -194,6 +194,13 @@ class WebAliasRequest: def parse_https_request(data): + if ( + isinstance(data, dict) + and data.get("operation") == "manage_certificate" + ): + from .web_certificates import WebCertificateRequest + + return WebCertificateRequest.from_manifest(data) if isinstance(data, dict) and "site" in data: return WebAlias.from_manifest(data) return WebSite.from_manifest(data) @@ -536,10 +543,32 @@ def main(argv=None): ) if args.command == "https-request": + from .web_certificates import ( + CERTIFICATE_REQUEST_LIMIT, + WebCertificateRequest, + apply_website_certificate, + ) from .web_node_tls import provision_https + def certificate_request(spec): + if isinstance(spec, WebCertificateRequest): + return apply_website_certificate(spec) + return provision_https(spec) + + def certificate_identity(spec): + return ( + spec.identity() + if isinstance(spec, WebCertificateRequest) + else spec.manifest() + ) + return serve_apply_request( - MANIFEST_VERSION, parse_https_request, provision_https + MANIFEST_VERSION, + parse_https_request, + certificate_request, + identity=certificate_identity, + include_result=True, + limit=CERTIFICATE_REQUEST_LIMIT, ) if args.command == "sftp-keys-request": diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index 0486405..f9dd743 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -2,6 +2,7 @@ import fcntl import os import ssl import subprocess +import uuid from pathlib import Path from .node_files import check_root_file, require_root_directory @@ -41,7 +42,7 @@ def provision_https(site): def ensure_certificate(site): - if os.path.lexists(certbot_lineage(site)): + if os.path.lexists(certificate_lineage(site)): return try: require_root_directory(CERTBOT_ROOT) @@ -59,12 +60,12 @@ def ensure_certificate(site): request_certificate(site) -def request_certificate(site): +def request_certificate(site, *, force=False): command = ( "/usr/bin/certbot", "certonly", "--non-interactive", - "--keep-until-expiring", + "--force-renewal" if force else "--keep-until-expiring", "--webroot", "--webroot-path", str(ACME_WEBROOT), @@ -162,27 +163,64 @@ def certbot_lineage(site): return CERTBOT_ROOT / "live" / name -def https_configuration(site, *, socket_path=None): - lineage = certbot_lineage(site) - name = lineage.name - archive = CERTBOT_ROOT / "archive" / name - for directory in (lineage, archive): +def custom_lineage(site): + from .web_node_apply import STATE_DIRECTORY + + return STATE_DIRECTORY / "certificates" / site.service_user + + +def certificate_lineage(site): + if not isinstance(site, WebAlias): + active = custom_lineage(site) / "active" + if os.path.lexists(active): + return active + return certbot_lineage(site) + + +def resolved_certificate_files(site): + lineage = certificate_lineage(site) + if lineage.name == "active": + require_root_directory(lineage.parent) + info = lineage.lstat() + try: + revision = uuid.UUID(os.readlink(lineage)) + except (OSError, ValueError): + raise ValueError( + "The uploaded certificate directory is unexpected." + ) from None + if info.st_uid != 0 or str(revision) != os.readlink(lineage): + raise ValueError( + "The uploaded certificate directory is unexpected." + ) + archive = lineage.parent / str(revision) + lineage = archive + else: + archive = CERTBOT_ROOT / "archive" / lineage.name + for directory in {lineage, archive}: try: require_root_directory(directory) except FileNotFoundError: raise ValueError( - f"Obtain the Certbot certificate named {name}." + f"Obtain the certificate for {site.domain}." ) from None - - certificate = lineage / "fullchain.pem" - private_key = lineage / "privkey.pem" resolved = [] - for source in (certificate, private_key): + for source in (lineage / "fullchain.pem", lineage / "privkey.pem"): target = source.resolve(strict=True) if target.parent != archive: - raise ValueError(f"Expected {source} to point into {archive}.") + raise ValueError( + "Expected certificate files to point into a managed folder." + ) resolved.append(target) - chain_file, key_file = resolved + return tuple(resolved) + + +def https_configuration(site, *, socket_path=None): + chain_file, key_file = resolved_certificate_files(site) + validate_certificate_files(site, chain_file, key_file) + return render_https_configuration(site, socket_path=socket_path) + + +def validate_certificate_files(site, chain_file, key_file): check_root_file(chain_file) check_root_file(key_file, mode=0o600) try: @@ -191,7 +229,7 @@ def https_configuration(site, *, socket_path=None): ) except ssl.SSLError: raise ValueError( - "Could not load the Certbot certificate and private key." + "Could not load the certificate and private key." ) from None run( "/usr/bin/openssl", @@ -206,11 +244,9 @@ def https_configuration(site, *, socket_path=None): str(chain_file), ) - return render_https_configuration(site, socket_path=socket_path) - def render_https_configuration(site, *, socket_path=None): - lineage = certbot_lineage(site) + lineage = certificate_lineage(site) certificate = lineage / "fullchain.pem" private_key = lineage / "privkey.pem" return site.render( From 4b606638218b266c60d475686a8f409ecbd946cf Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:02:32 +0100 Subject: [PATCH 5/9] Add scoped redirects, database logins and SFTP folder access --- .../coulobre-folder-sftp-mounts.service | 16 + deploy/systemd/coulobre-folder-sftp.socket | 16 + deploy/systemd/coulobre-folder-sftp@.service | 15 + docs/deployment.md | 41 +++ pyproject.toml | 1 + src/coulobre/account_backup_request.py | 45 ++- src/coulobre/customer_backup_export.py | 22 +- src/coulobre/database_login.py | 78 +++++ src/coulobre/database_node.py | 9 + src/coulobre/database_node_apply.py | 6 + src/coulobre/database_node_logins.py | 253 ++++++++++++++++ src/coulobre/folder_sftp.py | 83 ++++++ src/coulobre/hosting/account_backups.py | 31 +- src/coulobre/hosting/account_retirement.py | 4 + src/coulobre/hosting/customer_backup_views.py | 3 +- src/coulobre/hosting/database_login_views.py | 216 ++++++++++++++ src/coulobre/hosting/folder_sftp_views.py | 156 ++++++++++ src/coulobre/hosting/mail_policy_views.py | 34 ++- .../0070_website_redirect_policy.py | 68 +++++ .../hosting/migrations/0071_database_login.py | 74 +++++ .../migrations/0072_database_export.py | 17 ++ .../migrations/0073_folder_sftp_login.py | 61 ++++ src/coulobre/hosting/models.py | 82 +++++ src/coulobre/hosting/phpmyadmin.py | 79 ++++- src/coulobre/hosting/redirect_views.py | 218 ++++++++++++++ src/coulobre/hosting/reseller_accounts.py | 7 + src/coulobre/hosting/service_credentials.py | 7 +- src/coulobre/hosting/tasks.py | 171 ++++++++++- .../templates/hosting/apache-vhost.conf | 1 + .../templates/hosting/customer_databases.html | 19 ++ .../templates/hosting/customer_redirects.html | 36 +++ .../templates/hosting/database_logins.html | 43 +++ .../templates/hosting/folder_sftp_users.html | 35 +++ src/coulobre/hosting/test_mail_policies.py | 8 +- .../hosting/test_panel_authentication.py | 5 +- src/coulobre/hosting/urls.py | 43 +++ src/coulobre/hosting/workspaces.py | 7 +- src/coulobre/mail_node_vacation.py | 4 +- src/coulobre/mail_policy.py | 23 +- src/coulobre/service_credentials.py | 24 +- src/coulobre/settings.py | 3 + src/coulobre/web_node.py | 19 ++ src/coulobre/web_node_access.py | 42 ++- src/coulobre/web_node_aliases.py | 6 + src/coulobre/web_node_apply.py | 4 +- src/coulobre/web_node_folder_sftp.py | 281 ++++++++++++++++++ src/coulobre/web_node_redirects.py | 82 +++++ src/coulobre/web_node_retirement.py | 5 + src/coulobre/web_node_runtime.py | 9 +- src/coulobre/web_redirects.py | 185 ++++++++++++ 50 files changed, 2640 insertions(+), 57 deletions(-) create mode 100644 deploy/systemd/coulobre-folder-sftp-mounts.service create mode 100644 deploy/systemd/coulobre-folder-sftp.socket create mode 100644 deploy/systemd/coulobre-folder-sftp@.service create mode 100644 src/coulobre/database_login.py create mode 100644 src/coulobre/database_node_logins.py create mode 100644 src/coulobre/folder_sftp.py create mode 100644 src/coulobre/hosting/database_login_views.py create mode 100644 src/coulobre/hosting/folder_sftp_views.py create mode 100644 src/coulobre/hosting/migrations/0070_website_redirect_policy.py create mode 100644 src/coulobre/hosting/migrations/0071_database_login.py create mode 100644 src/coulobre/hosting/migrations/0072_database_export.py create mode 100644 src/coulobre/hosting/migrations/0073_folder_sftp_login.py create mode 100644 src/coulobre/hosting/redirect_views.py create mode 100644 src/coulobre/hosting/templates/hosting/customer_databases.html create mode 100644 src/coulobre/hosting/templates/hosting/customer_redirects.html create mode 100644 src/coulobre/hosting/templates/hosting/database_logins.html create mode 100644 src/coulobre/hosting/templates/hosting/folder_sftp_users.html create mode 100644 src/coulobre/web_node_folder_sftp.py create mode 100644 src/coulobre/web_node_redirects.py create mode 100644 src/coulobre/web_redirects.py diff --git a/deploy/systemd/coulobre-folder-sftp-mounts.service b/deploy/systemd/coulobre-folder-sftp-mounts.service new file mode 100644 index 0000000..2448463 --- /dev/null +++ b/deploy/systemd/coulobre-folder-sftp-mounts.service @@ -0,0 +1,16 @@ +[Unit] +Description=Restore authorized Coulobre SFTP filesystem mounts +RequiresMountsFor=/srv/coulobre /var/lib/coulobre/web-node +After=local-fs.target +Before=ssh.service sshd.service + +[Service] +Type=oneshot +User=root +ExecStart=/opt/coulobre/bin/coulobre-folder-sftp restore-mounts +UMask=0077 +RemainAfterExit=yes +NoNewPrivileges=true + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/coulobre-folder-sftp.socket b/deploy/systemd/coulobre-folder-sftp.socket new file mode 100644 index 0000000..e4b82b8 --- /dev/null +++ b/deploy/systemd/coulobre-folder-sftp.socket @@ -0,0 +1,16 @@ +[Unit] +Description=Coulobre folder SFTP management socket +Wants=coulobre-folder-sftp-mounts.service +After=coulobre-folder-sftp-mounts.service + +[Socket] +ListenStream=/run/coulobre-folder-sftp.sock +SocketUser=root +SocketGroup=coulobre-sftp-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=2 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-folder-sftp@.service b/deploy/systemd/coulobre-folder-sftp@.service new file mode 100644 index 0000000..9c39e02 --- /dev/null +++ b/deploy/systemd/coulobre-folder-sftp@.service @@ -0,0 +1,15 @@ +[Unit] +Description=Coulobre folder SFTP management request +After=local-fs.target +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +ExecStart=/opt/coulobre/bin/coulobre-folder-sftp apply +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=2min +UMask=0077 +NoNewPrivileges=true diff --git a/docs/deployment.md b/docs/deployment.md index 63eebb1..36a3019 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2918,3 +2918,44 @@ For upgrades with local backups already enabled, install the current `coulobre-account-backup@.service` from the release before relying on SFTP exports. The unit needs write access to the managed web and web-node directories to publish the customer copy. + +## Enable folder-scoped SFTP logins + +Folder logins use the existing key-only SSH policy and a separate chroot for +each login. The web node exposes the approved website directory through an +ID-mapped bind mount. Uploads are owned by the original website user on +disk, so the hosting account's filesystem quota still applies. The primary +hosting login retains access to its backup directory. + +Use a kernel and filesystem that support ID-mapped mounts. Install these +units from the same release as the existing local SFTP worker. + +```bash +sudo install -m 0644 deploy/systemd/coulobre-folder-sftp.socket \ + deploy/systemd/coulobre-folder-sftp@.service \ + deploy/systemd/coulobre-folder-sftp-mounts.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now coulobre-folder-sftp-mounts.service \ + coulobre-folder-sftp.socket +``` + +Set `COULOBRE_LOCAL_FOLDER_SFTP=1` in the panel environment and restart the +panel and workers. Customers can add and remove logins in **SFTP Users**. +An empty folder selects the website document root. A changed or missing +directory leaves the login unavailable until its access is recreated. +Remove folder logins before changing the customer, changing the primary +domain or retiring the account. + +## Manage database logins and SQL exports + +Customers can add read-only or read-write logins for individual provisioned +databases. The read-write mode grants record-level changes. The primary +managed login retains its existing schema permissions and authentication. +Additional logins follow account suspension and can launch phpMyAdmin when +the existing bridge and credential service are enabled. + +With account backups and SFTP enabled, use **Databases → Manage logins → +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. diff --git a/pyproject.toml b/pyproject.toml index 77216f1..e0f977b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,6 +33,7 @@ coulobre-node-setup = "coulobre.node_setup:main" coulobre-service-credentials = "coulobre.service_credentials:main" coulobre-service-health = "coulobre.service_health:main" coulobre-update = "coulobre.local_update:main" +coulobre-folder-sftp = "coulobre.web_node_folder_sftp:main" coulobre-web-node = "coulobre.web_node:main" [project.optional-dependencies] diff --git a/src/coulobre/account_backup_request.py b/src/coulobre/account_backup_request.py index 1b737ba..f3b3377 100644 --- a/src/coulobre/account_backup_request.py +++ b/src/coulobre/account_backup_request.py @@ -18,6 +18,7 @@ from .node_requests import serve_apply_request REQUEST_VERSION = 1 REMOTE_MAIL_VERSION = 2 CUSTOMER_EXPORT_VERSION = 3 +DATABASE_EXPORT_VERSION = 4 BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups") BACKUP_SOCKET = "/run/coulobre-account-backup.sock" BACKUP_TIMEOUT_SECONDS = 30 * 60 @@ -29,6 +30,21 @@ class AccountBackupRequest: backup: AccountBackup remote_mail: bool = False publish_to_customer: bool = False + database_suffix: str = "" + + def __post_init__(self): + if self.database_suffix and ( + not self.publish_to_customer + or self.remote_mail + or self.backup.include_website + or self.backup.additional_websites + or self.backup.mailboxes is not None + or tuple(database.suffix for database in self.backup.databases) + != (self.database_suffix,) + ): + raise ValueError( + "A database export must contain one matching database." + ) @classmethod def from_manifest(cls, data): @@ -36,7 +52,9 @@ class AccountBackupRequest: raise ValueError("Expected a local account backup request.") version = data["version"] fields = {"version", "backup_id", "backup"} - if version == CUSTOMER_EXPORT_VERSION: + if version == DATABASE_EXPORT_VERSION: + fields.add("database_suffix") + if version in (CUSTOMER_EXPORT_VERSION, DATABASE_EXPORT_VERSION): fields.add("remote_mail") if ( data.keys() != fields @@ -45,6 +63,7 @@ class AccountBackupRequest: REQUEST_VERSION, REMOTE_MAIL_VERSION, CUSTOMER_EXPORT_VERSION, + DATABASE_EXPORT_VERSION, ) or not isinstance(data["backup_id"], str) or type(data.get("remote_mail", False)) is not bool @@ -61,8 +80,17 @@ class AccountBackupRequest: raise ValueError( "Expected mailboxes in the remote backup request." ) + database_suffix = data.get("database_suffix", "") + if version == DATABASE_EXPORT_VERSION and ( + not isinstance(database_suffix, str) or not database_suffix + ): + raise ValueError("Expected a database suffix for this export.") return cls( - backup_id, backup, remote_mail, version == CUSTOMER_EXPORT_VERSION + backup_id, + backup, + remote_mail, + version in (CUSTOMER_EXPORT_VERSION, DATABASE_EXPORT_VERSION), + database_suffix, ) def manifest(self): @@ -70,6 +98,11 @@ class AccountBackupRequest: "version": self.version, "backup_id": str(self.backup_id), "backup": self.backup.manifest(), + **( + {"database_suffix": self.database_suffix} + if self.database_suffix + else {} + ), **( {"remote_mail": self.remote_mail} if self.publish_to_customer @@ -86,6 +119,8 @@ class AccountBackupRequest: @property def version(self): + if self.database_suffix: + return DATABASE_EXPORT_VERSION if self.publish_to_customer: return CUSTOMER_EXPORT_VERSION return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION @@ -146,7 +181,11 @@ def create_requested_backup(request): if request.publish_to_customer: from .customer_backup_export import export_latest_backup - export_latest_backup(request.backup.website, archive) + export_latest_backup( + request.backup.website, + archive, + database_suffix=request.database_suffix, + ) return {"archive_bytes": archive.stat().st_size} diff --git a/src/coulobre/customer_backup_export.py b/src/coulobre/customer_backup_export.py index c97ae4f..ed8057e 100644 --- a/src/coulobre/customer_backup_export.py +++ b/src/coulobre/customer_backup_export.py @@ -4,7 +4,9 @@ import shutil import stat from pathlib import Path from tempfile import NamedTemporaryFile +from zipfile import ZipFile +from .database_node import DatabaseSpec from .node_files import check_root_file, require_root_directory from .web_node_apply import ( SitePaths, @@ -14,7 +16,9 @@ from .web_node_apply import ( ) -def export_latest_backup(site, archive): +def export_latest_backup(site, archive, *, database_suffix=""): + if database_suffix: + DatabaseSpec(site.account_id, database_suffix) # A root-owned directory protects the published export. with locked_web_node(fcntl.LOCK_EX): check_reservation(site) @@ -47,7 +51,10 @@ def export_latest_backup(site, archive): raise ValueError( "The backup directory has unexpected ownership or permissions." ) - latest = destination / "latest.zip" + component = ( + f"database-{database_suffix}.sql.gz" if database_suffix else None + ) + latest = destination / (component or "latest.zip") if os.path.lexists(latest): info = latest.lstat() if ( @@ -63,8 +70,15 @@ def export_latest_backup(site, archive): with NamedTemporaryFile(dir=destination, delete=False) as staged: temporary = Path(staged.name) try: - with archive.open("rb") as source: - shutil.copyfileobj(source, staged, length=1024 * 1024) + if component: + with ( + ZipFile(archive) as bundle, + bundle.open(component) as source, + ): + shutil.copyfileobj(source, staged, length=1024 * 1024) + else: + with archive.open("rb") as source: + shutil.copyfileobj(source, staged, length=1024 * 1024) staged.flush() os.fchown(staged.fileno(), user.pw_uid, user.pw_gid) os.fchmod(staged.fileno(), 0o400) diff --git a/src/coulobre/database_login.py b/src/coulobre/database_login.py new file mode 100644 index 0000000..7d1f3c5 --- /dev/null +++ b/src/coulobre/database_login.py @@ -0,0 +1,78 @@ +from dataclasses import dataclass + +from .database_node import DatabaseSpec + +LOGIN_KIND = "mariadb_database_login" +PRIVILEGES = { + "read": ("SELECT",), + "write": ("SELECT", "INSERT", "UPDATE", "DELETE"), +} + + +@dataclass(frozen=True) +class DatabaseLoginSpec: + database: DatabaseSpec + login_id: int + + def __post_init__(self): + if ( + type(self.login_id) is not int + or not 1 <= self.login_id <= 2**63 - 1 + ): + raise ValueError("Expected a valid managed MariaDB login.") + + @property + def name(self): + return f"coulobre_g_{self.login_id}" + + def manifest(self): + return { + "kind": LOGIN_KIND, + "database": self.database.manifest(), + "login_id": self.login_id, + } + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or data.keys() != {"kind", "database", "login_id"} + or data["kind"] != LOGIN_KIND + ): + raise ValueError("Expected a managed MariaDB login.") + return cls( + DatabaseSpec.from_manifest(data["database"]), data["login_id"] + ) + + +@dataclass(frozen=True) +class DatabaseLoginRequest: + login: DatabaseLoginSpec + access: str + operation: str + + def __post_init__(self): + if self.access not in PRIVILEGES or self.operation not in ( + "grant", + "remove", + ): + raise ValueError("Choose a supported MariaDB login operation.") + + def manifest(self): + return { + "operation": self.operation, + "login": self.login.manifest(), + "access": self.access, + } + + @classmethod + def from_manifest(cls, data): + if data.keys() != {"operation", "login", "access"} or not isinstance( + data["access"], str + ): + raise ValueError("Expected a managed MariaDB login operation.") + return cls( + DatabaseLoginSpec.from_manifest(data["login"]), + data["access"], + data["operation"], + ) diff --git a/src/coulobre/database_node.py b/src/coulobre/database_node.py index c138b8f..bf48af2 100644 --- a/src/coulobre/database_node.py +++ b/src/coulobre/database_node.py @@ -110,13 +110,20 @@ def main(argv=None): args = parser.parse_args(argv) if args.command == "apply-request": + from .database_login import DatabaseLoginRequest from .database_node_apply import ( apply_database, retire_database, set_database_access, ) + from .database_node_logins import apply_database_login def parse(data): + if isinstance(data, dict) and data.get("operation") in ( + "grant", + "remove", + ): + return DatabaseLoginRequest.from_manifest(data) return parse_retirement( data, DatabaseSpec.from_manifest, @@ -126,6 +133,8 @@ def main(argv=None): ) def apply(request): + if isinstance(request, DatabaseLoginRequest): + return apply_database_login(request, DEFAULT_SOCKET) if isinstance(request, RetirementRequest): return retire_database(request, DEFAULT_SOCKET) if isinstance(request, ServiceAccessRequest): diff --git a/src/coulobre/database_node_apply.py b/src/coulobre/database_node_apply.py index 41944c9..b59bcb6 100644 --- a/src/coulobre/database_node_apply.py +++ b/src/coulobre/database_node_apply.py @@ -553,6 +553,9 @@ def set_database_access(database, socket, suspended): raise ValueError( "MariaDB did not apply the requested login state." ) + from .database_node_logins import set_secondary_access + + set_secondary_access(cursor, database, record["ownership"], suspended) if not suspended: marker.unlink() @@ -572,7 +575,10 @@ def retire_database(request, socket): raise ValueError( "Suspend the managed database login before retirement." ) + from .database_node_logins import retire_secondary_logins + retirement.begin() + retire_secondary_logins(cursor, database, record["ownership"]) cursor.execute("KILL USER %s", (database.name,)) marker = record_path.with_suffix(".retired") if not os.path.lexists(marker): diff --git a/src/coulobre/database_node_logins.py b/src/coulobre/database_node_logins.py new file mode 100644 index 0000000..b703425 --- /dev/null +++ b/src/coulobre/database_node_logins.py @@ -0,0 +1,253 @@ +import json +import os +from secrets import token_urlsafe + +from . import database_node_apply as node +from .database_login import PRIVILEGES, DatabaseLoginSpec +from .database_node_backup import managed_database +from .node_files import read_root_file, require_root_directory, write_new_file + + +def login_directory(database): + return node.STATE_DIRECTORY / "logins" / database.name + + +def login_record(login, path, ownership): + record = json.loads(read_root_file(path, mode=0o600)) + if ( + not isinstance(record, dict) + or record.get("login") != login.manifest() + or record.get("ownership") != ownership + or record.get("access") not in PRIVILEGES + or record.get("plugin") + not in (node.NATIVE_PASSWORD, node.SHA2_PASSWORD) + or not isinstance(record.get("password"), str) + or len(record["password"]) != 43 + ): + raise ValueError("This login conflicts with its credentials record.") + return record + + +def login_users(cursor, login, plugin): + _, users = node.read_resources( + cursor, login.name, sha2=plugin == node.SHA2_PASSWORD + ) + return users + + +def validate_login(cursor, login, record, *, allow_missing=False): + users = login_users(cursor, login, record["plugin"]) + if not users and allow_missing: + return False + if record["plugin"] == node.SHA2_PASSWORD: + verifier, _ = node.sha2_login(users) + if ( + record.get("verifier") is not None + and verifier != record["verifier"] + ): + raise ValueError( + "The MariaDB login password has changed on the host." + ) + elif users != ( + ( + "localhost", + node.NATIVE_PASSWORD, + node.native_password_hash(record["password"]), + ), + ): + raise ValueError( + "The existing login does not match managed credentials." + ) + return True + + +def validate_grants(cursor, login, access): + cursor.execute("SHOW GRANTS FOR %s@'localhost'", (login.name,)) + grantee = f"`{login.name}`@`localhost`" + expected_scope = ( + f" ON {node.grant_scope(login.database.name)} TO {grantee}" + ) + actual = [] + for (grant,) in cursor.fetchall(): + if ( + grant.startswith( + ( + f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED VIA ", + f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD ", + ) + ) + and "WITH GRANT OPTION" not in grant + ): + continue + if grant.startswith("GRANT ") and grant.endswith(expected_scope): + actual.append(set(grant[6 : -len(expected_scope)].split(", "))) + else: + raise ValueError("The MariaDB login has unmanaged grants.") + if actual != [set(PRIVILEGES[access])]: + raise ValueError("The MariaDB login has unmanaged grants.") + + +def apply_database_login(request, socket): + if os.geteuid() != 0: + raise ValueError( + "Run the login operation as root on the MariaDB node." + ) + login = request.login + with managed_database(login.database, socket) as (cursor, primary, path): + if os.path.lexists(path.with_suffix(".suspended")) or os.path.lexists( + path.with_suffix(".retired") + ): + raise ValueError("The MariaDB database is suspended or retired.") + directory = login_directory(login.database) + for folder in (directory.parent, directory): + require_root_directory(folder, create_mode=0o700) + target = directory / f"{login.name}.json" + plugin = primary.get("authentication_plugin", node.NATIVE_PASSWORD) + if not os.path.lexists(target): + if login_users(cursor, login, plugin): + raise ValueError( + "This login is already used outside Coulobre." + ) + if request.operation == "remove": + return + if len(list(directory.glob("*.json"))) >= 25: + raise ValueError( + "This database already has 25 supported logins." + ) + record = { + "login": login.manifest(), + "ownership": primary["ownership"], + "access": request.access, + "plugin": plugin, + "password": token_urlsafe(32), + } + write_new_file(target, json.dumps(record), mode=0o600) + else: + record = login_record(login, target, primary["ownership"]) + exists = validate_login(cursor, login, record, allow_missing=True) + if request.operation == "remove": + if exists: + cursor.execute("KILL USER %s", (login.name,)) + cursor.execute("DROP USER %s@'localhost'", (login.name,)) + target.unlink() + return + if record["access"] != request.access: + raise ValueError( + "The login has a different recorded access policy." + ) + expected = { + "database": login.database.name, + "user": login.name, + "host": "localhost", + "socket": str(socket.resolve()), + "password": record["password"], + } + if not exists: + if record["plugin"] == node.SHA2_PASSWORD: + cursor.execute( + "CREATE USER %s@'localhost' IDENTIFIED VIA " + "caching_sha2_password USING PASSWORD(%s)", + (login.name, record["password"]), + ) + else: + cursor.execute( + "CREATE USER %s@'localhost' IDENTIFIED VIA " + "mysql_native_password USING %s", + ( + login.name, + node.native_password_hash(record["password"]), + ), + ) + privileges = ", ".join(PRIVILEGES[record["access"]]) + cursor.execute( + f"GRANT {privileges} ON {node.grant_scope(login.database.name)} " + "TO %s@'localhost'", + (login.name,), + ) + validate_grants(cursor, login, record["access"]) + if record["plugin"] == node.SHA2_PASSWORD: + verifier, _ = node.sha2_login( + login_users(cursor, login, record["plugin"]) + ) + node.save_credential_record( + target, record | {"verifier": verifier} + ) + verify_mariadb_login(expected) + + +def secondary_credentials(login, socket): + with managed_database(login.database, socket) as (cursor, primary, path): + if os.path.lexists(path.with_suffix(".suspended")) or os.path.lexists( + path.with_suffix(".retired") + ): + raise ValueError("The MariaDB database is suspended or retired.") + directory = login_directory(login.database) + require_root_directory(directory) + record = login_record( + login, directory / f"{login.name}.json", primary["ownership"] + ) + validate_login(cursor, login, record) + validate_grants(cursor, login, record["access"]) + return { + "database": login.database.name, + "user": login.name, + "host": "localhost", + "socket": str(socket.resolve()), + "password": record["password"], + } + + +def existing_logins(database, ownership): + directory = login_directory(database) + if not os.path.lexists(directory): + return + require_root_directory(directory) + for path in sorted(directory.glob("*.json")): + record = json.loads(read_root_file(path, mode=0o600)) + login = DatabaseLoginSpec.from_manifest(record.get("login")) + if login.database != database or path.stem != login.name: + raise ValueError("A secondary login has an unexpected identity.") + yield login, login_record(login, path, ownership), path + + +def verify_mariadb_login(credentials): + import MySQLdb + + if not node.can_sign_in(MySQLdb, credentials, credentials["password"]): + raise ValueError("The secondary MariaDB login could not sign in.") + + +def set_secondary_access(cursor, database, ownership, suspended): + for login, record, path in existing_logins(database, ownership): + if not validate_login(cursor, login, record, allow_missing=True): + continue + checkpoint = path.with_suffix(".suspended") + if suspended and not checkpoint.exists(): + state = ( + "locked" + if node.login_is_locked(cursor, login.name) + else "unlocked" + ) + write_new_file(checkpoint, state, mode=0o600) + if checkpoint.exists(): + state = read_root_file(checkpoint, mode=0o600) + if state not in {"locked", "unlocked"}: + raise ValueError( + "A secondary login has an invalid suspension record." + ) + action = "LOCK" if suspended or state == "locked" else "UNLOCK" + cursor.execute( + f"ALTER USER %s@'localhost' ACCOUNT {action}", (login.name,) + ) + if not suspended: + checkpoint.unlink() + + +def retire_secondary_logins(cursor, database, ownership): + for login, record, _ in existing_logins(database, ownership): + if validate_login(cursor, login, record, allow_missing=True): + if not node.login_is_locked(cursor, login.name): + raise ValueError( + "Suspend secondary logins before database retirement." + ) + cursor.execute("KILL USER %s", (login.name,)) diff --git a/src/coulobre/folder_sftp.py b/src/coulobre/folder_sftp.py new file mode 100644 index 0000000..3b23889 --- /dev/null +++ b/src/coulobre/folder_sftp.py @@ -0,0 +1,83 @@ +from dataclasses import dataclass, field + +from .sftp_keys import MAX_KEYS_BYTES, normalize_public_keys +from .web_node import WebSite +from .website_files import directory_parts + +FOLDER_SOCKET = "/run/coulobre-folder-sftp.sock" +FOLDER_LIMIT = MAX_KEYS_BYTES + 32 * 1024 + + +def base36(number): + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + while number: + number, digit = divmod(number, 36) + result = digits[digit] + result + return result + + +def folder_user_prefix(site): + return f"cbf-{base36(site.account_id)}-" + + +@dataclass(frozen=True) +class FolderSftpRequest: + site: WebSite + login_id: int + folder: str + action: str + public_keys: str = field(default="", repr=False) + + def __post_init__(self): + if self.site.site_id is not None: + raise ValueError("Choose the primary hosting website.") + if ( + type(self.login_id) is not int + or not 1 <= self.login_id <= 2**63 - 1 + ): + raise ValueError("Choose a valid SFTP login.") + directory_parts(self.folder) + if self.action not in ("create", "keys", "remove"): + raise ValueError("Choose an available SFTP action.") + normalized = normalize_public_keys(self.public_keys) + if (self.action == "remove") == bool(normalized): + raise ValueError( + "Provide at least one key when granting SFTP access." + ) + object.__setattr__(self, "public_keys", normalized) + + @property + def username(self): + return folder_user_prefix(self.site) + base36(self.login_id) + + def scope(self): + return { + "site": self.site.manifest(), + "login_id": self.login_id, + "folder": self.folder, + } + + def identity(self): + return self.scope() | {"action": self.action} + + def manifest(self): + return self.identity() | {"public_keys": self.public_keys} + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "site", + "login_id", + "folder", + "action", + "public_keys", + }: + raise ValueError("Expected a folder SFTP request.") + return cls( + WebSite.from_manifest(data["site"]), + data["login_id"], + data["folder"], + data["action"], + data["public_keys"], + ) diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index 8a0fbba..e8525c9 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -31,6 +31,7 @@ def account_backup_manifest( include_mailboxes=False, include_website=True, include_databases=True, + database_suffix="", ): mailboxes = None if include_mailboxes: @@ -40,7 +41,14 @@ def account_backup_manifest( mailboxes = tuple(mailbox.spec for mailbox in requests) return AccountBackup( WebSite(account.pk, account.primary_domain), - tuple(database.spec for database in account.databases.all()) + tuple( + database.spec + for database in ( + account.databases.filter(suffix=database_suffix) + if database_suffix + else account.databases.all() + ) + ) if include_databases else (), mailboxes, @@ -59,17 +67,31 @@ def queue_account_backup( customer_id=None, include_website=True, include_databases=True, + database_suffix="", ): account = lock_hosting_account(account_id, customer_id=customer_id) require_open_account(account) + if database_suffix and not ( + customer_id is not None + and include_databases + and not include_website + and not include_mailboxes + and account.databases.filter( + suffix=database_suffix, + provisioning__finished_at__isnull=False, + provisioning__problem="", + ).exists() + ): + raise ValidationError("Choose a provisioned database to export.") if not any((include_mailboxes, include_website, include_databases)): raise ValidationError("Select at least one backup component.") - _enqueue_backup( + return _enqueue_backup( account, include_mailboxes=include_mailboxes, include_website=include_website, include_databases=include_databases, export_customer_id=customer_id, + database_suffix=database_suffix, ) @@ -82,6 +104,7 @@ def _enqueue_backup( include_website=True, include_databases=True, export_customer_id=None, + database_suffix="", ): if not account.backup_jobs.filter(finished_at__isnull=True).exists(): job = account.backup_jobs.create( @@ -90,16 +113,20 @@ def _enqueue_backup( include_mailboxes=include_mailboxes, include_website=include_website, include_databases=include_databases, + database_suffix=database_suffix, ), remote_mail=include_mailboxes and settings.REMOTE_ACCOUNT_BACKUP_MAIL, scheduled_for=scheduled_for, export_customer_id=export_customer_id, + export_database_suffix=database_suffix, ) if scheduled_for is not None and offsite_destination: OffsiteBackupTransfer.objects.create( backup=job, destination=offsite_destination ) + return job + return None def _next_backup_run(schedule, now): diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index 7d6160d..9e18e0f 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -232,6 +232,10 @@ def request_retirement(account_id, policy, confirmation, digest, actor): raise ValidationError("Choose a retirement policy.") if retirement is not None and policy != Policy.RELEASE: return retirement + if account.folder_sftp_logins.exists(): + raise ValidationError( + "Remove folder SFTP logins before retiring the hosting account." + ) targets = cleanup_targets(account) if policy == Policy.RELEASE: for kind, target, _ in targets: diff --git a/src/coulobre/hosting/customer_backup_views.py b/src/coulobre/hosting/customer_backup_views.py index e0b4124..bcd0e0c 100644 --- a/src/coulobre/hosting/customer_backup_views.py +++ b/src/coulobre/hosting/customer_backup_views.py @@ -67,7 +67,8 @@ class CustomerBackupView(UserPassesTestMixin, FormView): def get_context_data(self, **kwargs): backups = ( self.account.backup_jobs.filter( - export_customer_id=self.account.customer_id + export_customer_id=self.account.customer_id, + export_database_suffix="", ) .select_related("expiration") .order_by("-requested_at")[:30] diff --git a/src/coulobre/hosting/database_login_views.py b/src/coulobre/hosting/database_login_views.py new file mode 100644 index 0000000..fade595 --- /dev/null +++ b/src/coulobre/hosting/database_login_views.py @@ -0,0 +1,216 @@ +from django import forms +from django.conf import settings +from django.contrib import messages +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.views.decorators.cache import never_cache +from django.views.decorators.http import ( + require_http_methods, + require_POST, + require_safe, +) + +from .access import customer_for_user +from .account_backups import queue_account_backup +from .credential_views import DatabaseCredentialView +from .installation_features import panel_feature_allowed +from .models import DatabaseLogin, HostingAccount, HostingDatabase +from .phpmyadmin import phpmyadmin_available +from .resource_requests import lock_hosting_account, require_active_services +from .service_credentials import CredentialKind, enabled_credential_access +from .sftp import site_is_active + + +class AddDatabaseLoginForm(forms.Form): + label = forms.CharField(max_length=80) + access = forms.ChoiceField(choices=DatabaseLogin.Access.choices) + + +def signed_in_customer(request): + customer = customer_for_user(request.user) + if customer is None or getattr(request, "impersonation", None) is not None: + raise PermissionDenied + return customer + + +@require_safe +@never_cache +def customer_databases(request, pk): + customer = signed_in_customer(request) + account = get_object_or_404( + HostingAccount, pk=pk, customer=customer, retired_at__isnull=True + ) + can_reveal = enabled_credential_access(request, CredentialKind.DATABASE) + return render( + request, + "hosting/customer_databases.html", + { + "account": account, + "databases": account.databases.select_related( + "provisioning" + ).prefetch_related("logins"), + "show_sso": phpmyadmin_available(request), + "can_reveal": can_reveal, + }, + ) + + +@transaction.atomic +def update_database_login( + database, customer, action, *, login_id=None, data=None +): + account = lock_hosting_account(database.account_id, customer.pk) + require_active_services(account) + if ( + getattr(getattr(database, "provisioning", None), "state", "") + != "configured" + ): + raise ValidationError("Finish provisioning the database first.") + if action == "add": + if database.logins.count() >= 25: + raise ValidationError( + "This database already has 25 managed logins." + ) + DatabaseLogin.objects.create( + database=database, + requested_customer_id=customer.pk, + **data, + ) + return + if ( + not login_id + or not login_id.isascii() + or not login_id.isdecimal() + or len(login_id) > 18 + ): + raise Http404 + login = get_object_or_404(database.logins, pk=int(login_id)) + if login.finished_at is None: + raise ValidationError("Wait for the current login operation.") + DatabaseLogin.objects.requeue( + database.logins.filter(pk=login.pk), + action="remove", + requested_customer_id=customer.pk, + ) + + +@require_http_methods(("GET", "HEAD", "POST")) +@never_cache +def database_login_editor(request, pk): + customer = signed_in_customer(request) + if not panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"): + raise Http404 + database = get_object_or_404( + HostingDatabase.objects.select_related("account", "provisioning"), + account__retired_at__isnull=True, + account__customer=customer, + pk=pk, + ) + action = request.POST.get("action") + form = AddDatabaseLoginForm(request.POST if action == "add" else None) + problem = "" + if request.method == "POST": + if action not in {"add", "remove"}: + raise Http404 + if action == "remove" or form.is_valid(): + try: + update_database_login( + database, + customer, + action, + login_id=request.POST.get("login"), + data=form.cleaned_data if action == "add" else None, + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + problem = " ".join(error.messages) + else: + return redirect("panel:database_logins", pk=pk) + return render( + request, + "hosting/database_logins.html", + { + "database": database, + "form": form, + "problem": problem, + "logins": database.logins.order_by("label"), + "can_export": can_export_database(database), + "export_job": database.account.backup_jobs.filter( + export_database_suffix=database.suffix, + export_customer_id=customer.pk, + ) + .order_by("-pk") + .first(), + "show_sso": phpmyadmin_available(request), + "can_reveal": enabled_credential_access( + request, CredentialKind.DATABASE + ), + }, + ) + + +def can_export_database(database): + return ( + panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS") + and settings.LOCAL_WEB_SFTP + and site_is_active(database.account) + and not database.account.services_suspended + and getattr(getattr(database, "provisioning", None), "state", "") + == "configured" + ) + + +@require_POST +@never_cache +def database_sql_export(request, pk): + customer = signed_in_customer(request) + database = get_object_or_404( + HostingDatabase.objects.select_related("account", "provisioning"), + pk=pk, + account__customer=customer, + account__retired_at__isnull=True, + ) + if not can_export_database(database): + raise Http404 + try: + job = queue_account_backup( + database.account_id, + customer_id=customer.pk, + include_website=False, + database_suffix=database.suffix, + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + messages.error(request, " ".join(error.messages)) + else: + if job: + messages.success(request, "SQL export queued.") + else: + messages.error( + request, "Wait for the current account backup to finish." + ) + return redirect("panel:database_logins", pk=database.pk) + + +class DatabaseLoginCredentialView(DatabaseCredentialView): + queryset = DatabaseLogin.objects.filter( + finished_at__isnull=False, + problem="", + action="grant", + database__account__retired_at__isnull=True, + database__account__services_suspended=False, + ).select_related("database__account") + customer_relation = "database__account__customer" + + @property + def account(self): + return self.resource.database.account + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context.pop("rotation_url", None) + return context diff --git a/src/coulobre/hosting/folder_sftp_views.py b/src/coulobre/hosting/folder_sftp_views.py new file mode 100644 index 0000000..909617a --- /dev/null +++ b/src/coulobre/hosting/folder_sftp_views.py @@ -0,0 +1,156 @@ +from django import forms +from django.conf import settings +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_http_methods + +from coulobre.sftp_keys import normalize_public_keys +from coulobre.website_files import directory_parts + +from .access import customer_for_user +from .models import FolderSftpLogin, HostingAccount +from .resource_requests import ( + lock_hosting_account, + require_active_services, + require_open_account, +) +from .sftp import site_is_active + + +class FolderLoginForm(forms.Form): + label = forms.CharField(max_length=80) + folder = forms.CharField( + label="Folder relative to the website document root", + required=False, + max_length=1024, + help_text="Leave blank for the entire website document root.", + ) + public_keys = forms.CharField( + label="SSH public keys", + widget=forms.Textarea(attrs={"rows": 4, "spellcheck": "false"}), + help_text="Paste one public key per line.", + ) + + def __init__(self, *args, edit=False, **kwargs): + super().__init__(*args, **kwargs) + if edit: + self.fields.pop("label") + self.fields.pop("folder") + + def clean_folder(self): + folder = self.cleaned_data["folder"] + try: + directory_parts(folder) + except ValueError as error: + raise ValidationError(str(error)) from error + return folder + + def clean_public_keys(self): + try: + keys = normalize_public_keys(self.cleaned_data["public_keys"]) + except ValueError as error: + raise ValidationError(str(error)) from error + if not keys: + raise ValidationError("Provide at least one SSH public key.") + return keys + + +@transaction.atomic +def save_folder_login(account_id, customer_id, action, login, data): + account = lock_hosting_account(account_id, customer_id) + require_open_account(account) + if action != "remove": + require_active_services(account) + if not site_is_active(account): + raise ValidationError( + "Activate the website before granting SFTP access." + ) + if action == "create": + if account.folder_sftp_logins.count() >= 10: + raise ValidationError("This account has ten folder SFTP logins.") + account.folder_sftp_logins.create( + requested_customer_id=customer_id, + domain=account.primary_domain, + **data, + ) + else: + jobs = account.folder_sftp_logins.filter(pk=login.pk) + current = jobs.get() + if current.finished_at is None: + raise ValidationError("Wait for the current login operation.") + FolderSftpLogin.objects.requeue( + jobs, + action=action, + requested_customer_id=customer_id, + **data, + ) + + +@never_cache +@require_http_methods(("GET", "HEAD", "POST")) +def folder_sftp_users(request, pk): + customer = customer_for_user(request.user) + if customer is None or getattr(request, "impersonation", None) is not None: + raise PermissionDenied + if not settings.LOCAL_WEB_SFTP: + raise Http404 + account = get_object_or_404( + HostingAccount, pk=pk, customer=customer, retired_at__isnull=True + ) + action = request.POST.get("action", "create") + login = None + if (login_id := request.GET.get("login")) is not None: + if ( + not login_id.isascii() + or not login_id.isdecimal() + or len(login_id) > 18 + ): + raise Http404 + login = get_object_or_404(account.folder_sftp_logins, pk=int(login_id)) + edit = login is not None + form = FolderLoginForm( + request.POST + if action != "remove" and request.method == "POST" + else None, + edit=edit, + initial={"public_keys": login.public_keys} if edit else {}, + ) + enabled = settings.LOCAL_FOLDER_SFTP + problem = "" + if request.method == "POST": + if ( + not enabled + or action not in {"create", "keys", "remove"} + or ((action != "create") != edit) + ): + raise Http404 + if action == "remove" or form.is_valid(): + try: + save_folder_login( + pk, + customer.pk, + action, + login, + {} if action == "remove" else form.cleaned_data, + ) + except (HostingAccount.DoesNotExist, FolderSftpLogin.DoesNotExist): + raise Http404 from None + except ValidationError as error: + problem = " ".join(error.messages) + else: + return redirect("panel:folder_sftp_users", pk=pk) + return render( + request, + "hosting/folder_sftp_users.html", + { + "account": account, + "form": form, + "login": login, + "enabled": enabled, + "logins": account.folder_sftp_logins.order_by("label"), + "problem": problem, + }, + ) diff --git a/src/coulobre/hosting/mail_policy_views.py b/src/coulobre/hosting/mail_policy_views.py index 7492026..2e8c29b 100644 --- a/src/coulobre/hosting/mail_policy_views.py +++ b/src/coulobre/hosting/mail_policy_views.py @@ -11,9 +11,15 @@ from django.views.decorators.cache import never_cache from django.views.generic import FormView from django.views.generic.detail import SingleObjectMixin -from coulobre.mail_policy import MailRouting, MailVacation, parse_mail_policy +from coulobre.mail_policy import ( + DEFAULT_REPEAT_DAYS, + MAX_REPEAT_DAYS, + MailRouting, + MailVacation, + parse_mail_policy, +) -from .access import TenantScopeMixin, can_manage_hosting +from .access import TenantScopeMixin, can_manage_hosting, reseller_for_user from .mail_policies import ( mail_policy_available, policy_account, @@ -131,6 +137,17 @@ class MailVacationForm(MailPolicyForm): ), ) + repeat_days = forms.IntegerField( + label="Days between replies to the same sender", + min_value=1, + max_value=MAX_REPEAT_DAYS, + initial=DEFAULT_REPEAT_DAYS, + required=False, + help_text=( + "Leave blank for seven days. The mail node enforces its limits." + ), + ) + def make_spec(self, cleaned): values = { key: cleaned[key] for key in ("enabled", "subject", "message") @@ -142,7 +159,11 @@ class MailVacationForm(MailPolicyForm): if timestamp else "" ) - return MailVacation(self.resource.spec, **values) + return MailVacation( + self.resource.spec, + repeat_days=cleaned.get("repeat_days") or DEFAULT_REPEAT_DAYS, + **values, + ) @method_decorator(never_cache, name="dispatch") @@ -152,8 +173,10 @@ class MailPolicyEditor( template_name = "hosting/mail_policy_form.html" def has_permission(self): - return getattr(self.request, "impersonation", None) is None and ( - super().has_permission() + return ( + reseller_for_user(self.request.user) is None + and getattr(self.request, "impersonation", None) is None + and super().has_permission() ) def get_permission_required(self): @@ -190,6 +213,7 @@ class MailPolicyEditor( initial["catchall"] = spec.catchall else: initial.update(spec.manifest()) + initial["repeat_days"] = spec.repeat_days for name in ("starts_at", "ends_at"): initial[name] = initial[name].removesuffix("+00:00") return initial diff --git a/src/coulobre/hosting/migrations/0070_website_redirect_policy.py b/src/coulobre/hosting/migrations/0070_website_redirect_policy.py new file mode 100644 index 0000000..59a9edf --- /dev/null +++ b/src/coulobre/hosting/migrations/0070_website_redirect_policy.py @@ -0,0 +1,68 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:44 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + +import coulobre.hosting.fields + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0069_certificate_uploads"), + ] + + operations = [ + migrations.CreateModel( + name="WebsiteRedirectPolicy", + 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)), + ( + "domain", + coulobre.hosting.fields.DomainNameField(max_length=253), + ), + ("website", models.JSONField()), + ("requested_rules", models.JSONField(default=list)), + ("applied_rules", models.JSONField(default=list)), + ( + "requested_customer_id", + models.PositiveBigIntegerField(null=True), + ), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="redirect_policies", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "constraints": [ + models.UniqueConstraint( + fields=("account", "domain"), + name="website_redirect_per_domain", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/migrations/0071_database_login.py b/src/coulobre/hosting/migrations/0071_database_login.py new file mode 100644 index 0000000..afd87b6 --- /dev/null +++ b/src/coulobre/hosting/migrations/0071_database_login.py @@ -0,0 +1,74 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:52 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0070_website_redirect_policy"), + ] + + operations = [ + migrations.CreateModel( + name="DatabaseLogin", + 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)), + ("label", models.CharField(max_length=80)), + ( + "access", + models.CharField( + choices=[ + ("read", "Read only"), + ("write", "Read and write"), + ], + default="read", + max_length=6, + ), + ), + ("action", models.CharField(default="grant", max_length=6)), + ("requested_customer_id", models.PositiveBigIntegerField()), + ( + "database", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="logins", + to="hosting.hostingdatabase", + ), + ), + ], + options={ + "abstract": False, + }, + ), + migrations.AddField( + model_name="phpmyadmingrant", + name="database_login", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="hosting.databaselogin", + ), + ), + ] diff --git a/src/coulobre/hosting/migrations/0072_database_export.py b/src/coulobre/hosting/migrations/0072_database_export.py new file mode 100644 index 0000000..61d9c59 --- /dev/null +++ b/src/coulobre/hosting/migrations/0072_database_export.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:53 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0071_database_login"), + ] + + operations = [ + migrations.AddField( + model_name="accountbackupjob", + name="export_database_suffix", + field=models.CharField(blank=True, default="", max_length=24), + ), + ] diff --git a/src/coulobre/hosting/migrations/0073_folder_sftp_login.py b/src/coulobre/hosting/migrations/0073_folder_sftp_login.py new file mode 100644 index 0000000..7e4876e --- /dev/null +++ b/src/coulobre/hosting/migrations/0073_folder_sftp_login.py @@ -0,0 +1,61 @@ +# Generated by Django 5.2.19 on 2026-11-23 21:59 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + +import coulobre.hosting.fields + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0072_database_export"), + ] + + operations = [ + migrations.CreateModel( + name="FolderSftpLogin", + 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)), + ( + "domain", + coulobre.hosting.fields.DomainNameField(max_length=253), + ), + ("label", models.CharField(max_length=80)), + ("folder", models.CharField(blank=True, max_length=1024)), + ("public_keys", models.TextField()), + ("action", models.CharField(default="create", max_length=6)), + ("requested_customer_id", models.PositiveBigIntegerField()), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="folder_sftp_logins", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index f100706..ec65b8d 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -14,6 +14,7 @@ from django.utils import timezone from coulobre.account_backup_request import backup_archive from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES +from coulobre.database_login import DatabaseLoginSpec from coulobre.database_node import ( DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, @@ -594,6 +595,12 @@ class ServiceSignOnGrant(models.Model): class PhpMyAdminGrant(ServiceSignOnGrant): database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE) + database_login = models.ForeignKey( + "DatabaseLogin", + null=True, + blank=True, + on_delete=models.CASCADE, + ) class RoundcubeGrant(ServiceSignOnGrant): @@ -828,6 +835,57 @@ class ProvisioningJob(models.Model): return "running" if self.started_at else "queued" +class FolderSftpLogin(ProvisioningJob): + account = models.ForeignKey( + HostingAccount, + on_delete=models.CASCADE, + related_name="folder_sftp_logins", + ) + domain = DomainNameField(max_length=253) + label = models.CharField(max_length=80) + folder = models.CharField(max_length=1024, blank=True) + public_keys = models.TextField() + action = models.CharField(max_length=6, default="create") + requested_customer_id = models.PositiveBigIntegerField() + + @property + def spec(self): + from coulobre.folder_sftp import FolderSftpRequest + + return FolderSftpRequest( + WebSite(self.account_id, self.domain), + self.pk, + self.folder, + self.action, + self.public_keys if self.action != "remove" else "", + ) + + +class DatabaseLogin(ProvisioningJob): + class Access(models.TextChoices): + READ = "read", "Read only" + WRITE = "write", "Read and write" + + database = models.ForeignKey( + HostingDatabase, + related_name="logins", + on_delete=models.CASCADE, + ) + label = models.CharField(max_length=80) + access = models.CharField( + max_length=6, choices=Access, default=Access.READ + ) + action = models.CharField(max_length=6, default="grant") + requested_customer_id = models.PositiveBigIntegerField() + + def __str__(self): + return self.spec.name + + @property + def spec(self): + return DatabaseLoginSpec(self.database.spec, self.pk) + + class OperatorOperation(ProvisioningJob): actor = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True @@ -1037,6 +1095,27 @@ class WebsiteCertificateJob(ProvisioningJob): certificate = models.JSONField(default=dict) +class WebsiteRedirectPolicy(ProvisioningJob): + account = models.ForeignKey( + HostingAccount, + on_delete=models.CASCADE, + related_name="redirect_policies", + ) + domain = DomainNameField(max_length=253) + website = models.JSONField() + requested_rules = models.JSONField(default=list) + applied_rules = models.JSONField(default=list) + requested_customer_id = models.PositiveBigIntegerField(null=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["account", "domain"], + name="website_redirect_per_domain", + ) + ] + + class WebsiteAlias(ProvisioningJob): wait_for_website = models.BooleanField(default=False) @@ -1166,6 +1245,9 @@ class AccountBackupJob(ProvisioningJob): manifest = models.JSONField() remote_mail = models.BooleanField(default=False) export_customer_id = models.PositiveBigIntegerField(null=True, blank=True) + export_database_suffix = models.CharField( + max_length=24, blank=True, default="" + ) scheduled_for = models.DateTimeField(null=True, blank=True) archive_bytes = models.PositiveBigIntegerField(null=True, blank=True) retention_protected = models.BooleanField(default=False) diff --git a/src/coulobre/hosting/phpmyadmin.py b/src/coulobre/hosting/phpmyadmin.py index 5ce089c..93c5ab5 100644 --- a/src/coulobre/hosting/phpmyadmin.py +++ b/src/coulobre/hosting/phpmyadmin.py @@ -1,7 +1,8 @@ from django.conf import settings from django.contrib.auth import get_user_model from django.http import Http404, JsonResponse -from django.shortcuts import render +from django.shortcuts import get_object_or_404, render +from django.utils.functional import cached_property from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt from django.views.decorators.debug import ( @@ -13,7 +14,12 @@ from django.views.decorators.http import require_POST from .access import customer_for_user from .credential_views import DatabaseCredentialView from .installation_features import panel_feature_allowed -from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess +from .models import ( + DatabaseLogin, + HostingDatabase, + PhpMyAdminGrant, + ServiceCredentialAccess, +) from .service_credentials import ( CredentialKind, CredentialOutcome, @@ -37,8 +43,35 @@ def phpmyadmin_available(request): ) +def active_database_logins(): + return DatabaseLogin.objects.filter( + finished_at__isnull=False, problem="", action="grant" + ) + + class PhpMyAdminLaunch(DatabaseCredentialView): http_method_names = ["post"] + secondary = False + + @cached_property + def selected_login(self): + if not self.secondary: + return None + return get_object_or_404( + active_database_logins().select_related("database__account"), + pk=self.kwargs["pk"], + database__in=self.get_queryset().filter( + account__services_suspended=False + ), + ) + + @cached_property + def resource(self): + return ( + self.selected_login.database + if self.secondary + else super().resource + ) def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) @@ -50,7 +83,10 @@ class PhpMyAdminLaunch(DatabaseCredentialView): if not phpmyadmin_available(request): raise Http404 token = issue_signon_grant( - PhpMyAdminGrant, request.user, database=self.resource + PhpMyAdminGrant, + request.user, + database=self.resource, + database_login=self.selected_login, ) return render( request, @@ -60,7 +96,11 @@ class PhpMyAdminLaunch(DatabaseCredentialView): + "/coulobre-signon.php", "ticket": token, "product": "phpMyAdmin", - "resource": self.resource.spec.name, + "resource": ( + self.selected_login.spec.name + if self.secondary + else self.resource.spec.name + ), "ticket_field": "ticket", "account": self.account, }, @@ -68,8 +108,10 @@ class PhpMyAdminLaunch(DatabaseCredentialView): def actor_has_database_access(actor, database): - if database.account.retired_at is not None or not can_reveal_credentials( - actor, CredentialKind.DATABASE + if ( + database.account.retired_at is not None + or database.account.services_suspended + or not can_reveal_credentials(actor, CredentialKind.DATABASE) ): return False customer = customer_for_user(actor) @@ -85,7 +127,9 @@ def redeem_phpmyadmin(request): if not phpmyadmin_available(request): raise Http404 token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY) - grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account") + grant = consume_signon_grant( + PhpMyAdminGrant, token, "database__account", "database_login" + ) if grant is None: raise Http404 actor = signon_actor(grant, grant.actor) @@ -93,17 +137,28 @@ def redeem_phpmyadmin(request): raise Http404 database = grant.database + resource = database.spec + if grant.database_login_id is not None: + login = ( + active_database_logins() + .filter(pk=grant.database_login_id, database=database) + .select_related("database") + .first() + ) + if login is None: + raise Http404 + resource = login.spec audit = ServiceCredentialAccess.objects.create( actor=grant.actor, actor_username=grant.actor.get_username(), hosting_account_id=database.account_id, kind=CredentialKind.DATABASE, - resource=database.spec.name, + resource=resource.name, method=ServiceCredentialAccess.Method.PHPMYADMIN, outcome=CredentialOutcome.REQUESTED, ) try: - credentials = fetch_service_credentials(database.spec) + credentials = fetch_service_credentials(resource) except (OSError, ValueError): audit.outcome = CredentialOutcome.UNAVAILABLE audit.save(update_fields=["outcome"]) @@ -123,6 +178,12 @@ def redeem_phpmyadmin(request): or actor is None or current.spec != database.spec or not actor_has_database_access(actor, current) + or ( + grant.database_login_id is not None + and not active_database_logins() + .filter(pk=grant.database_login_id, database=current) + .exists() + ) ): audit.outcome = CredentialOutcome.UNAVAILABLE audit.save(update_fields=["outcome"]) diff --git a/src/coulobre/hosting/redirect_views.py b/src/coulobre/hosting/redirect_views.py new file mode 100644 index 0000000..8e6f0b8 --- /dev/null +++ b/src/coulobre/hosting/redirect_views.py @@ -0,0 +1,218 @@ +from django import forms +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.views.decorators.cache import never_cache +from django.views.decorators.http import require_http_methods + +from coulobre.domain_names import canonical_domain +from coulobre.web_node import WebAlias, WebSite +from coulobre.web_redirects import ( + MAX_DESTINATION, + RedirectConfiguration, + RedirectRule, +) + +from .access import customer_for_user +from .certificate_views import account_certificate_sites +from .installation_features import panel_feature_allowed +from .models import HostingAccount, WebsiteAlias, WebsiteRedirectPolicy +from .resource_requests import lock_hosting_account, require_active_services + + +class RedirectForm(forms.Form): + source = forms.CharField( + label="Path", + max_length=181, + help_text="Enter the exact path, such as /old-page.", + ) + destination = forms.CharField( + label="Destination URL", + max_length=MAX_DESTINATION, + ) + status = forms.TypedChoiceField( + label="HTTP status", + choices=[ + (301, "301 Moved permanently"), + (302, "302 Temporary redirect"), + (307, "307 Temporary redirect, keep request method"), + (308, "308 Permanent redirect, keep request method"), + ], + initial=302, + coerce=int, + ) + + def __init__(self, *args, kind, **kwargs): + super().__init__(*args, **kwargs) + self.kind = kind + if kind == "domain": + del self.fields["source"] + + def clean(self): + data = super().clean() + if not self.errors: + try: + self.rule = RedirectRule( + data.get("source", "*"), + data["destination"], + data["status"], + ) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + return data + + +def hosted_redirect_targets(account): + targets = account_certificate_sites(account) + if account.primary_domain not in targets: + return targets + for alias in ( + WebsiteAlias.objects.filter( + reservation__account=account, + primary_domain=account.primary_domain, + http_active=True, + ) + .exclude(operation=WebsiteAlias.Operation.REMOVE) + .select_related("reservation") + ): + domain = alias.reservation.domain + targets[domain] = WebAlias( + WebSite(account.pk, account.primary_domain), domain + ) + return targets + + +@transaction.atomic +def request_redirect_change( + account, website, actor, *, rule=None, source=None +): + account = lock_hosting_account(account.pk, actor) + require_active_services(account) + if hosted_redirect_targets(account).get(website.domain) != website: + raise ValidationError("This website is no longer available.") + job = account.redirect_policies.filter(domain=website.domain).first() + if job is not None and job.finished_at is None: + raise ValidationError("Wait for the current redirect change.") + applied = ( + job.applied_rules if job and job.website == website.manifest() else [] + ) + current = { + item["source"]: RedirectRule.from_manifest(item) for item in applied + } + if rule is not None: + if rule.source in current: + raise ValidationError( + "Remove the existing redirect for this path first." + ) + current[rule.source] = rule + elif source in current: + del current[source] + else: + raise ValidationError("This redirect no longer exists.") + try: + desired = RedirectConfiguration(website, tuple(current.values())) + except ValueError as error: + raise ValidationError(str(error)) from error + if job is None: + WebsiteRedirectPolicy.objects.create( + account=account, + domain=website.domain, + website=website.manifest(), + requested_rules=desired.manifest()["rules"], + requested_customer_id=actor, + ) + else: + WebsiteRedirectPolicy.objects.requeue( + WebsiteRedirectPolicy.objects.filter(pk=job.pk), + website=website.manifest(), + requested_rules=desired.manifest()["rules"], + requested_customer_id=actor, + applied_rules=applied, + ) + + +@never_cache +@require_http_methods(("GET", "HEAD", "POST")) +def customer_redirects(request, pk): + customer = customer_for_user(request.user) + if customer is None or getattr(request, "impersonation", None) is not None: + raise PermissionDenied + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): + raise Http404 + account = get_object_or_404( + HostingAccount, pk=pk, customer=customer, retired_at__isnull=True + ) + sites = hosted_redirect_targets(account) + try: + domain = canonical_domain( + request.GET.get( + "domain", next(iter(sites), account.primary_domain) + ) + ) + except ValueError as error: + raise Http404 from error + website = sites.get(domain) + if "domain" in request.GET and website is None: + raise Http404 + kind = request.GET.get("tab", "site") + if kind not in {"site", "domain"}: + raise Http404 + action = request.POST.get("action") + problem = "" + form = RedirectForm( + request.POST if action == "create" else None, + kind=kind, + ) + if request.method == "POST": + if website is None or action not in {"create", "remove"}: + raise Http404 + if action == "remove" or form.is_valid(): + try: + request_redirect_change( + account, + website, + customer.pk, + rule=form.rule if action == "create" else None, + source=request.POST.get("source"), + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + except ValidationError as error: + problem = " ".join(error.messages) + else: + return redirect( + reverse( + "panel:customer_redirects", + args=[pk], + query={"domain": domain, "tab": kind}, + ) + ) + job = ( + account.redirect_policies.filter( + domain=domain, website=website.manifest() + ).first() + if website + else None + ) + return render( + request, + "hosting/customer_redirects.html", + { + "account": account, + "sites": sites, + "domain": domain, + "kind": kind, + "form": form, + "problem": problem, + "job": job, + "redirects": [ + rule + for rule in job.applied_rules + if (rule["source"] == "*") == (kind == "domain") + ] + if job + else [], + }, + ) diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index 974c781..87a78bf 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -165,6 +165,13 @@ def save_operator_account(account, actor, *, changed_fields=None): require_open_account(previous) if "primary_domain" in changed_fields: require_active_services(previous) + if {"customer", "primary_domain"}.intersection( + changed_fields + ) and previous.folder_sftp_logins.exists(): + raise ValidationError( + "Remove folder SFTP logins before changing the customer " + "or primary domain." + ) previous_reseller_id = previous.reseller_id reseller_id = ( account.reseller_id diff --git a/src/coulobre/hosting/service_credentials.py b/src/coulobre/hosting/service_credentials.py index 1b7c16e..e8bb723 100644 --- a/src/coulobre/hosting/service_credentials.py +++ b/src/coulobre/hosting/service_credentials.py @@ -12,6 +12,7 @@ from django.utils import timezone from django.views.decorators.debug import sensitive_variables from coulobre.credential_rotation import valid_generation +from coulobre.database_login import DatabaseLoginSpec from coulobre.service_credentials import ( CREDENTIAL_SOCKET, CREDENTIAL_TIMEOUT_SECONDS, @@ -172,7 +173,11 @@ def fetch_service_credentials(resource, rotation=None): if spec.kind == CredentialKind.DATABASE: keys += ("database", "host", "socket") expected = { - "database": resource.name, + "database": ( + resource.database.name + if isinstance(resource, DatabaseLoginSpec) + else resource.name + ), "user": resource.name, "host": "localhost", } diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 0715366..0c39d7b 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -44,8 +44,10 @@ from .models import ( AccountRetirementJob, AccountServiceJob, ComponentRestoreJob, + DatabaseLogin, DatabaseProvisioning, DnsPublication, + FolderSftpLogin, HostingAccount, HostingMailDomain, IndependentWebsite, @@ -65,6 +67,7 @@ from .models import ( WebProvisioningPlan, WebsiteAlias, WebsiteCertificateJob, + WebsiteRedirectPolicy, WebsiteRestoreJob, WebsiteScheduledJob, ) @@ -170,6 +173,11 @@ def render_web_plan(plan_id): @shared_task def dispatch_web_activations(): if settings.LOCAL_WEB_ACTIVATION: + dispatch_provisioning_jobs( + WebsiteRedirectPolicy, + deploy_website_redirects, + WEB_ACTIVATION_QUEUE, + ) dispatch_provisioning_jobs( IndependentWebsite, provision_independent_website, @@ -250,12 +258,21 @@ def dispatch_web_https(): @shared_task def dispatch_web_sftp(): if settings.LOCAL_WEB_SFTP: + if settings.LOCAL_FOLDER_SFTP: + dispatch_provisioning_jobs( + FolderSftpLogin, apply_folder_sftp_job, WEB_SFTP_QUEUE + ) dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE) @shared_task def dispatch_database_provisioning(): if settings.LOCAL_DATABASE_PROVISIONING: + dispatch_provisioning_jobs( + DatabaseLogin, + provision_database_login, + DATABASE_PROVISIONING_QUEUE, + ) dispatch_provisioning_jobs( DatabaseProvisioning, provision_database, @@ -828,6 +845,23 @@ def create_account_backup(job_id): def apply_account_backup(job): + if job.export_customer_id is None: + return create_backup_job_archive(job) + with transaction.atomic(): + try: + job.account = lock_hosting_account( + job.account_id, job.export_customer_id + ) + except HostingAccount.DoesNotExist: + raise ValueError( + "The hosting account's customer assignment changed." + ) from None + if job.account.retired_at is not None: + raise ValueError("The hosting account is retired.") + return create_backup_job_archive(job) + + +def create_backup_job_archive(job): backup = AccountBackup.from_manifest(job.manifest) if backup.website.account_id != job.account_id: raise ValueError("The backup manifest belongs to a different account.") @@ -855,17 +889,13 @@ def apply_account_backup(job): raise ValueError( "Enable local mailbox backups before trying again." ) - if ( - job.export_customer_id is not None - and job.export_customer_id != job.account.customer_id - ): - raise ValueError("The hosting account's customer assignment changed.") size = create_local_account_backup( AccountBackupRequest( job.backup_id, backup, remote_mail=job.remote_mail, publish_to_customer=job.export_customer_id is not None, + database_suffix=job.export_database_suffix, ) ) return {"archive_bytes": size} @@ -1462,3 +1492,134 @@ def apply_certificate_job(job_id): WebsiteCertificateJob.objects.filter( pk=job_id, finished_at__isnull=False ).exclude(encrypted_upload="").update(encrypted_upload="") + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def deploy_website_redirects(job_id): + from coulobre.web_redirects import OPERATION, RedirectConfiguration + + from .node_client import apply_on_local_node + from .redirect_views import hosted_redirect_targets + + def apply(job): + with transaction.atomic(): + try: + account = lock_hosting_account( + job.account_id, job.requested_customer_id + ) + except HostingAccount.DoesNotExist: + raise ValueError( + "The hosting account is no longer available." + ) from None + request = RedirectConfiguration.from_manifest( + { + "operation": OPERATION, + "website": job.website, + "rules": job.requested_rules, + } + ) + if ( + account.retired_at is not None + or account.services_suspended + or hosted_redirect_targets(account).get(job.domain) + != request.website + ): + raise ValueError("The website is no longer available.") + apply_on_local_node( + request, + "/run/coulobre-web-apply.sock", + "web node", + "redirect update", + ) + return {"applied_rules": job.requested_rules} + + if settings.LOCAL_WEB_ACTIVATION: + run_provisioning_job( + WebsiteRedirectPolicy.objects.all(), + job_id, + apply, + "The web node did not confirm the website redirect update.", + ) + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def provision_database_login(job_id): + from coulobre.database_login import DatabaseLoginRequest + + from .node_client import apply_on_local_node + + def apply(job): + with transaction.atomic(): + try: + account = lock_hosting_account( + job.database.account_id, job.requested_customer_id + ) + except HostingAccount.DoesNotExist: + raise ValueError( + "The hosting account is no longer available." + ) from None + if account.retired_at is not None or account.services_suspended: + raise ValueError("The hosting account is inactive.") + spec = DatabaseLoginRequest(job.spec, job.access, job.action) + apply_on_local_node( + spec, + "/run/coulobre-database-apply.sock", + "MariaDB node", + "database login", + ) + return {} + + if settings.LOCAL_DATABASE_PROVISIONING: + run_provisioning_job( + DatabaseLogin.objects.select_related("database"), + job_id, + apply, + "The MariaDB node did not confirm the login operation.", + ) + DatabaseLogin.objects.filter( + pk=job_id, action="remove", problem="", finished_at__isnull=False + ).delete() + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def apply_folder_sftp_job(job_id): + from coulobre.folder_sftp import FOLDER_SOCKET + + from .node_client import apply_on_local_node + + def apply(job): + with transaction.atomic(): + try: + account = lock_hosting_account( + job.account_id, job.requested_customer_id + ) + except HostingAccount.DoesNotExist: + raise ValueError( + "The hosting account is no longer available." + ) from None + if ( + account.retired_at is not None + or account.primary_domain != job.domain + or (account.services_suspended and job.action != "remove") + ): + raise ValueError("The hosting account is inactive.") + spec = job.spec + apply_on_local_node( + spec, + FOLDER_SOCKET, + "web node", + "folder SFTP login", + identity=spec.identity(), + ) + return {} + + if settings.LOCAL_FOLDER_SFTP: + run_provisioning_job( + FolderSftpLogin.objects.all(), + job_id, + apply, + "The hosting node did not confirm the folder SFTP operation.", + ) + FolderSftpLogin.objects.filter( + pk=job_id, action="remove", problem="", finished_at__isnull=False + ).delete() diff --git a/src/coulobre/hosting/templates/hosting/apache-vhost.conf b/src/coulobre/hosting/templates/hosting/apache-vhost.conf index 33f5ca9..a677317 100644 --- a/src/coulobre/hosting/templates/hosting/apache-vhost.conf +++ b/src/coulobre/hosting/templates/hosting/apache-vhost.conf @@ -1,6 +1,7 @@ ServerName $domain DocumentRoot "$document_root" + IncludeOptional "$redirect_rules" $tls_settings $usage_logs diff --git a/src/coulobre/hosting/templates/hosting/customer_databases.html b/src/coulobre/hosting/templates/hosting/customer_databases.html new file mode 100644 index 0000000..36d9108 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_databases.html @@ -0,0 +1,19 @@ +{% extends "hosting/base.html" %} +{% block title %}Databases · Coulobre Panel{% endblock %} +{% block content %} +
+

Databases

{{ account.primary_domain }}

+ Add database +
+
+ + {% for db in databases %} + + {% empty %}{% endfor %} +
DatabaseStatePrimary loginAdditional logins
{{ db.spec.name }}{{ db.provisioning.state|default:"Requested"|capfirst }} + {% if db.provisioning.state == 'configured' %} + {% if can_reveal %}Credentials{% endif %} + {% if show_sso %}
{% csrf_token %}
{% endif %} + {% endif %} +
{{ db.logins.count }} · Manage logins
No databases in this hosting account.
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/customer_redirects.html b/src/coulobre/hosting/templates/hosting/customer_redirects.html new file mode 100644 index 0000000..a4c32a2 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_redirects.html @@ -0,0 +1,36 @@ +{% extends "hosting/base.html" %} +{% block title %}Redirects · Coulobre Panel{% endblock %} +{% block content %} +

Redirects

{{ account.primary_domain }}

+ {% if sites %} +
+
+ + + + +
+
+ + {% if job and not job.finished_at %}

{{ job.state|capfirst }} · Refresh status

{% endif %} + {% if problem %}{% endif %} + {% if job.problem %}{% endif %} +
+ + {% for row in redirects %} + + + + {% empty %}{% endfor %} +
FromToStatusActions
{{ domain }}{% if kind == 'site' %}{{ row.source }}{% endif %}{{ row.destination }}{{ row.status }}
{% csrf_token %}
No redirects of this type.
+
+

Add {% if kind == 'domain' %}domain{% else %}site{% endif %} redirect

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

Activate a website or an alias before adding redirects.

{% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/database_logins.html b/src/coulobre/hosting/templates/hosting/database_logins.html new file mode 100644 index 0000000..1b23faa --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/database_logins.html @@ -0,0 +1,43 @@ +{% extends "hosting/base.html" %} +{% block title %}Database logins · Coulobre Panel
+

SQL export

+ {% if export_job %}

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

{% endif %} + {% if export_job.state == 'configured' %}

Download over SFTP at /backups/database-{{ database.suffix }}.sql.gz.

{% endif %} + {% if export_job.problem %}

{{ export_job.problem }}

{% endif %} + {% if can_export %}
{% csrf_token %} + +
{% else %}

SQL exports require the account's SFTP and backup services.

{% endif %} +
+{% endblock %} +{% block content %} + ← Databases +

Database logins

{{ database.spec.name }}

+ {% for message in messages %}

{{ message }}

{% endfor %} + {% if problem %}{% endif %} +
+ + {% for login in logins %} + + + {% empty %}{% endfor %} +
LoginAccessStateActions
{{ login.label }}
{{ login.spec.name }}
{{ login.get_access_display }}{{ login.state|capfirst }}{% if login.problem %}

{{ login.problem }}

{% endif %}
+ {% if login.state == 'configured' and login.action == 'grant' %} + {% if can_reveal %}Credentials{% endif %} + {% if show_sso %}
{% csrf_token %}
{% endif %} + {% endif %} + {% if login.finished_at %}
{% csrf_token %}
{% endif %} +
No additional logins.
+
+

Add database login

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

SQL export

+ {% if export_job %}

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

{% endif %} + {% if export_job.state == 'configured' %}

Download over SFTP at /backups/database-{{ database.suffix }}.sql.gz.

{% endif %} + {% if export_job.problem %}

{{ export_job.problem }}

{% endif %} + {% if can_export %}
{% csrf_token %} + +
{% else %}

SQL exports require the account's SFTP and backup services.

{% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/folder_sftp_users.html b/src/coulobre/hosting/templates/hosting/folder_sftp_users.html new file mode 100644 index 0000000..f352677 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/folder_sftp_users.html @@ -0,0 +1,35 @@ +{% extends "hosting/base.html" %} +{% block title %}SFTP Users · Coulobre Panel{% endblock %} +{% block content %} +

SFTP Users

{{ account.primary_domain }}

+ {% if problem %}{% endif %} +
+

Primary hosting login

Access to the hosting account, including files in /backups.

+ Manage SSH keys
+
+
+ + {% for entry in logins %} + + + + + {% empty %}{% endfor %} +
Folder loginWebsite folderStateActions
{{ entry.label }}
{{ entry.spec.username }}
{{ entry.folder|default:"Entire website" }}{{ entry.state|capfirst }}{% if entry.problem %}

{{ entry.problem }}

{% endif %}
{% if enabled and entry.finished_at %} + Manage keys +
{% csrf_token %} + +
+ {% endif %}
No folder logins.
+ {% if enabled %} +
+

{% if login %}SSH keys for {{ login.label }}{% else %}Add folder login{% endif %}

+
{% csrf_token %}{{ form.as_div }} +
+ + {% if login %}Cancel{% endif %} +
+
+
+ {% else %}

Folder logins require the scoped SFTP worker on the web server.

{% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/test_mail_policies.py b/src/coulobre/hosting/test_mail_policies.py index a770dd5..d830024 100644 --- a/src/coulobre/hosting/test_mail_policies.py +++ b/src/coulobre/hosting/test_mail_policies.py @@ -136,7 +136,7 @@ class MailPolicyTests(TestCase): self.client.post(self.routing, data), self.routing ) - def test_reseller_can_schedule_replies_and_an_outsider_cannot_access_them( + def test_customer_replies_respect_account_scope_and_repeat_interval( self, ): data = { @@ -145,12 +145,17 @@ class MailPolicyTests(TestCase): "message": "Back Monday.\n— Alice", "starts_at": "2026-11-25T07:30", "ends_at": "2026-11-30T10:30", + "repeat_days": "3", } self.client.force_login(self.outsider) for url in (self.vacation, self.routing): self.assertEqual(self.client.get(url).status_code, 404) self.assertEqual(self.client.post(url, data).status_code, 404) self.client.force_login(self.reseller) + self.assertEqual( + self.client.post(self.vacation, data).status_code, 403 + ) + self.client.force_login(self.customer) self.assertContains( self.client.post( self.vacation, data | {"ends_at": "2026-11-25T07:00"} @@ -165,6 +170,7 @@ class MailPolicyTests(TestCase): spec = parse_mail_policy(job.manifest) self.assertEqual(spec.starts_at, "2026-11-25T07:30:00+00:00") self.assertEqual(spec.ends_at, "2026-11-30T10:30:00+00:00") + self.assertEqual(spec.repeat_days, 3) with patch( "coulobre.hosting.mail_policies.apply_on_local_node" ) as node: diff --git a/src/coulobre/hosting/test_panel_authentication.py b/src/coulobre/hosting/test_panel_authentication.py index e9629ba..f88f19a 100644 --- a/src/coulobre/hosting/test_panel_authentication.py +++ b/src/coulobre/hosting/test_panel_authentication.py @@ -377,7 +377,10 @@ class SignInLimitsTests(TestCase): self.assertEqual(client_address(request), "unknown") @override_settings(TRUST_APACHE_CLIENT_IP=False) - def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header(self): + @patch("coulobre.hosting.sign_in_limits.current_window", return_value=1) + def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header( + self, _window + ): url = reverse("panel:login") for attempt in range(9): response = self.client.post( diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index a8ba4a2..6f8679e 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -23,9 +23,16 @@ from .backup_restores import RestoreKind from .certificate_views import customer_certificates, operator_certificates from .credential_views import DatabaseCredentialView, MailboxCredentialView from .customer_backup_views import CustomerBackupView, CustomerRestoreView +from .database_login_views import ( + DatabaseLoginCredentialView, + customer_databases, + database_login_editor, + database_sql_export, +) from .dns_defaults_views import DnsDefaultsView from .dns_replica_views import DnsReplicaView from .domain_services import domain_workspace +from .folder_sftp_views import folder_sftp_users from .health_views import ServiceHealthView from .independent_website_views import ( IndependentWebsiteCreate, @@ -55,6 +62,7 @@ from .password_reset import ( CustomerResetDoneView, ) from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin +from .redirect_views import customer_redirects from .reseller_onboarding_views import ( ResellerCustomerCreate, ResellerCustomerLink, @@ -87,12 +95,47 @@ from .workspaces import customer_workspace, system_workspace app_name = "panel" urlpatterns = [ + path( + "hosting//databases/", + customer_databases, + name="customer_databases", + ), + path( + "databases//logins/", + database_login_editor, + name="database_logins", + ), + path( + "database-logins//credentials/", + DatabaseLoginCredentialView.as_view(), + name="database_login_credentials", + ), + path( + "database-logins//phpmyadmin/", + PhpMyAdminLaunch.as_view(secondary=True), + name="phpmyadmin_login", + ), + path( + "databases//export/", + database_sql_export, + name="database_export", + ), + path( + "hosting//sftp/", + folder_sftp_users, + name="folder_sftp_users", + ), path("ssl/", operator_certificates, name="operator_certificates"), path( "hosting//certificates/", customer_certificates, name="customer_certificates", ), + path( + "hosting//redirects/", + customer_redirects, + name="customer_redirects", + ), 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/workspaces.py b/src/coulobre/hosting/workspaces.py index 2a47345..c233f9e 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -19,11 +19,12 @@ CUSTOMER_ACCOUNT = "coulobre_active_hosting_account" CUSTOMER_PAGES = { "domains": ("Domains", "account", "websites"), "dns": ("DNS Editor", "account", "domains-dns"), + "redirects": ("Redirects", "customer_redirects", ""), "php": ("PHP Settings", "account", "websites"), "files": ("File Manager", "website_files", ""), "certificates": ("SSL Certificates", "customer_certificates", ""), - "sftp": ("SFTP Users", "sftp_keys", ""), - "databases": ("Databases", "account", "databases"), + "sftp": ("SFTP Users", "folder_sftp_users", ""), + "databases": ("Databases", "customer_databases", ""), "email": ("Email Accounts", "account", "email"), "forwarders": ("Forwarders", "account", "email"), "replies": ("Automatic replies", "account", "email"), @@ -54,6 +55,7 @@ def customer_pages(request): pages = CUSTOMER_PAGES.copy() for key, enabled in ( ("files", panel_feature_allowed("WEB_FILE_MANAGER")), + ("redirects", panel_feature_allowed("LOCAL_WEB_ACTIVATION")), ("sftp", settings.LOCAL_WEB_SFTP), ("backups", panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")), ("tasks", panel_feature_allowed("WEBSITE_JOBS")), @@ -211,6 +213,7 @@ def groups_for(request, *, customer, manager): "domains", "dns", "certificates", + "redirects", "sftp", "databases", "php", diff --git a/src/coulobre/mail_node_vacation.py b/src/coulobre/mail_node_vacation.py index 5d48643..0954821 100644 --- a/src/coulobre/mail_node_vacation.py +++ b/src/coulobre/mail_node_vacation.py @@ -29,7 +29,9 @@ def vacation_script(spec): for line in spec.message.split("\n") ) reply = ( - f"vacation :days 7 :subject {sieve_string(spec.subject)} text:\n" + f"vacation :days {spec.repeat_days} " + f":subject {sieve_string(spec.subject)} " + "text:\n" f"{body}\n.\n;\n" ) if not dates: diff --git a/src/coulobre/mail_policy.py b/src/coulobre/mail_policy.py index 39fabed..62215e0 100644 --- a/src/coulobre/mail_policy.py +++ b/src/coulobre/mail_policy.py @@ -8,6 +8,8 @@ from .domain_names import canonical_domain from .mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec MAIL_POLICY_LIMIT = 64 * 1024 +DEFAULT_REPEAT_DAYS = 7 +MAX_REPEAT_DAYS = 60 MAX_ALIASES = 100 MAX_DESTINATIONS = 10 OPERATIONS = ("set_mail_routing", "set_mail_vacation") @@ -122,8 +124,14 @@ class MailVacation(MailPolicy): message: str = "" starts_at: str = "" ends_at: str = "" + repeat_days: int = DEFAULT_REPEAT_DAYS def __post_init__(self): + if ( + type(self.repeat_days) is not int + or not 1 <= self.repeat_days <= MAX_REPEAT_DAYS + ): + raise ValueError("Choose a reply interval between 1 and 60 days.") if type(self.enabled) is not bool: raise ValueError("Choose whether to enable the autoresponder.") if not isinstance(self.subject, str) or not isinstance( @@ -168,7 +176,11 @@ class MailVacation(MailPolicy): "message": self.message, "starts_at": self.starts_at, "ends_at": self.ends_at, - } + } | ( + {"repeat_days": self.repeat_days} + if self.repeat_days != DEFAULT_REPEAT_DAYS + else {} + ) def parse_mail_policy(data): @@ -184,14 +196,18 @@ def parse_mail_policy(data): return MailRouting( data["domain"], data["aliases"], data["catchall"] ) - if data.get("operation") == "set_mail_vacation" and fields == { + vacation_fields = { "mailbox", "enabled", "subject", "message", "starts_at", "ends_at", - }: + } + if data.get("operation") == "set_mail_vacation" and fields in ( + vacation_fields, + vacation_fields | {"repeat_days"}, + ): return MailVacation( MailboxSpec.from_manifest(data["mailbox"]), data["enabled"], @@ -199,5 +215,6 @@ def parse_mail_policy(data): data["message"], data["starts_at"], data["ends_at"], + data.get("repeat_days", DEFAULT_REPEAT_DAYS), ) raise ValueError("Expected a version 1 mail policy.") diff --git a/src/coulobre/service_credentials.py b/src/coulobre/service_credentials.py index 8e1bb0f..58ec7bd 100644 --- a/src/coulobre/service_credentials.py +++ b/src/coulobre/service_credentials.py @@ -3,6 +3,7 @@ import os from dataclasses import dataclass from .credential_rotation import valid_generation +from .database_login import LOGIN_KIND, DatabaseLoginSpec from .database_node import DEFAULT_SOCKET, DatabaseSpec from .mail_node import MailboxSpec from .node_requests import serve_apply_request @@ -18,12 +19,17 @@ CREDENTIALS_UNAVAILABLE = "The service credentials are currently unavailable." @dataclass(frozen=True) class ServiceCredentialRequest: - resource: DatabaseSpec | MailboxSpec + resource: DatabaseSpec | DatabaseLoginSpec | MailboxSpec operation: str = "read" rotation_id: str | None = None previous_id: str | None = None def __post_init__(self): + if ( + isinstance(self.resource, DatabaseLoginSpec) + and self.operation != "read" + ): + raise ValueError("This login supports credential retrieval only.") if self.operation in ("read", "generation"): if self.rotation_id is None and self.previous_id is None: return @@ -41,7 +47,7 @@ class ServiceCredentialRequest: def kind(self): return ( "database" - if isinstance(self.resource, DatabaseSpec) + if isinstance(self.resource, (DatabaseSpec, DatabaseLoginSpec)) else "mailbox" ) @@ -70,8 +76,16 @@ class ServiceCredentialRequest: raise ValueError( "Expected a database or mailbox credential request." ) + resource = data["resource"] + parser = parsers[kind] + if ( + kind == "database" + and isinstance(resource, dict) + and resource.get("kind") == LOGIN_KIND + ): + parser = DatabaseLoginSpec.from_manifest return cls( - parsers[kind](data["resource"]), + parser(resource), operation, data.get("rotation_id"), data.get("previous_id"), @@ -123,6 +137,10 @@ def read_service_credentials(request): raise ValueError(CREDENTIALS_UNAVAILABLE) try: + if isinstance(request.resource, DatabaseLoginSpec): + from .database_node_logins import secondary_credentials + + return secondary_credentials(request.resource, DEFAULT_SOCKET) if request.operation == "rotate": return rotate_service_credentials(request) read = ( diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index cbd7dc7..b2228c4 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -222,6 +222,9 @@ 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" +LOCAL_FOLDER_SFTP = ( + LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1" +) LOCAL_DATABASE_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" ) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index ae2a100..c90d61d 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -123,12 +123,14 @@ class WebSite: + options.render_overrides() ) from .web_node_usage import apache_log_directives + from .web_redirects import redirect_include return template.substitute( values, port=port, tls_settings=tls_settings, usage_logs=apache_log_directives(self).rstrip(), + redirect_rules=redirect_include(self.node_key, values["domain"]), ) @@ -259,6 +261,14 @@ class WebPhpRequest: def parse_web_request(data): + if ( + isinstance(data, dict) + and data.get("operation") == "set_website_redirects" + ): + from .web_redirects import RedirectConfiguration + + return RedirectConfiguration.from_manifest(data) + return parse_retirement(data, WebSite.from_manifest, parse_web_apply) @@ -363,6 +373,14 @@ class WebPhpVersionRequest: def apply_web_request(request): + from .web_redirects import RedirectConfiguration + + if isinstance(request, RedirectConfiguration): + from .web_node_redirects import apply_redirects + + apply_redirects(request) + return None + if isinstance(request, WebActivationRequest): from .web_node_apply import apply_site_with_runtime @@ -539,6 +557,7 @@ def main(argv=None): MANIFEST_VERSION, parse_web_request, apply_web_request, + limit=32768, include_result=True, ) diff --git a/src/coulobre/web_node_access.py b/src/coulobre/web_node_access.py index ea8d6ee..93f115d 100644 --- a/src/coulobre/web_node_access.py +++ b/src/coulobre/web_node_access.py @@ -3,7 +3,12 @@ import os from pathlib import Path from . import web_node_apply as web -from .node_files import read_root_file, require_root_directory, write_new_file +from .node_files import ( + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) APACHE_CONFIG = Path("/etc/apache2/conf-enabled") SSH_CONFIG = Path("/etc/ssh/sshd_config.d") @@ -44,6 +49,14 @@ def set_sftp_access(site, suspended): user = site.configuration()["service_user"] path = sftp_suspension_path(site) + names = {user} + previous = {f"DenyUsers {user}\n"} + if site.site_id is None: + from .folder_sftp import folder_user_prefix + + names.add(folder_user_prefix(site) + "*") + config = f"DenyUsers {' '.join(sorted(names))}\n" + def validate(): configuration = web.run( "/usr/sbin/sshd", @@ -57,17 +70,25 @@ def set_sftp_access(site, suspended): if line.startswith("denyusers ") for name in line.split()[1:] } - if suspended and user not in denied: + if suspended and not names.issubset(denied): raise ValueError( "OpenSSH did not include the suspension configuration." ) set_configuration( - site, suspended, path, f"DenyUsers {user}\n", validate, "ssh" + site, + suspended, + path, + config, + validate, + "ssh", + previous=previous, ) -def set_configuration(site, suspended, path, config, validate, service): +def set_configuration( + site, suspended, path, config, validate, service, *, previous=() +): if os.geteuid() != 0: raise ValueError( "Run the service access request as root on the web node." @@ -76,13 +97,20 @@ def set_configuration(site, suspended, path, config, validate, service): with web.locked_web_node(fcntl.LOCK_EX): web.check_reservation(site) existed = os.path.lexists(path) - if existed and read_root_file(path, mode=0o644) != config: + actual = read_root_file(path, mode=0o644) if existed else None + if existed and actual not in (config, *previous): raise ValueError(f"Unexpected configuration at {path}.") - write_access_configuration(path, config, existed, suspended) + if existed and suspended and actual != config: + replace_configuration(path, config) + else: + write_access_configuration(path, config, existed, suspended) try: validate() except (OSError, ValueError): - write_access_configuration(path, config, suspended, existed) + if actual is None: + path.unlink(missing_ok=True) + else: + replace_configuration(path, actual) raise # A reload may have taken effect even if the result was lost. # Keep the requested file state so retry can reload it again. diff --git a/src/coulobre/web_node_aliases.py b/src/coulobre/web_node_aliases.py index 1c7d8f5..7895c78 100644 --- a/src/coulobre/web_node_aliases.py +++ b/src/coulobre/web_node_aliases.py @@ -174,6 +174,12 @@ def remove_alias(alias): disable_alias_vhosts(links) for apache, _ in paths: apache.unlink(missing_ok=True) + from .web_redirects import redirect_include + + rules = Path(redirect_include(alias.site.node_key, alias.domain)) + if os.path.lexists(rules): + read_root_file(rules) + rules.unlink() delete_alias_certificate(alias) marker.unlink() diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 1e8648c..8dd848e 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -496,9 +496,9 @@ def configuration_installation(): def check_configuration(path, content): - from .web_node_usage import without_usage_logs + from .web_redirects import compatible_configs - if read_root_file(path) not in (content, without_usage_logs(content)): + if read_root_file(path) not in compatible_configs(content): raise ValueError(f"Existing configuration differs at {path}.") diff --git a/src/coulobre/web_node_folder_sftp.py b/src/coulobre/web_node_folder_sftp.py new file mode 100644 index 0000000..919715c --- /dev/null +++ b/src/coulobre/web_node_folder_sftp.py @@ -0,0 +1,281 @@ +import argparse +import fcntl +import json +import os +import subprocess +from contextlib import contextmanager +from pathlib import Path + +from . import web_node_apply as web +from .folder_sftp import FOLDER_LIMIT, FolderSftpRequest, folder_user_prefix +from .node_files import ( + check_root_file, + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) +from .node_requests import serve_apply_request +from .web_node_access import sftp_suspension_path +from .web_node_sftp import ( + AUTHORIZED_KEYS, + SFTP_GROUP, + check_sshd, + validate_public_key, +) +from .website_files import directory_parts + +JAIL_ROOT = Path("/srv/coulobre/folder-sftp") +DIRECTORY_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + + +def folder_state(): + return web.STATE_DIRECTORY / "folder-sftp" + + +@contextmanager +def open_scoped_folder(public, folder): + fd = os.open(public, DIRECTORY_FLAGS) + try: + for component in directory_parts(folder): + child = os.open(component, DIRECTORY_FLAGS, dir_fd=fd) + os.close(fd) + fd = child + yield fd, os.fstat(fd) + finally: + os.close(fd) + + +def is_bound(mountpoint): + with open("/proc/self/mountinfo", encoding="utf-8") as mounts: + return any(line.split()[4] == str(mountpoint) for line in mounts) + + +def run_mount(*args, bind_fd=None): + try: + result = subprocess.run( + args, + pass_fds=(bind_fd,) if bind_fd is not None else (), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + timeout=10, + env={ + "PATH": "/usr/sbin:/usr/bin", + "LIBMOUNT_FORCE_MOUNT2": "never", + }, + ) + except (OSError, subprocess.TimeoutExpired): + raise ValueError( + "The SFTP filesystem operation did not complete." + ) from None + if result.returncode: + raise ValueError( + "The filesystem could not apply the scoped SFTP mount." + ) + + +def bind_folder(fd, info, mountpoint, uid, gid): + if not is_bound(mountpoint): + mapping = ( + f"X-mount.idmap=u:{info.st_uid}:{uid}:1 g:{info.st_gid}:{gid}:1" + ) + run_mount( + "/usr/bin/mount", + "--no-canonicalize", + "--bind", + "-o", + f"nosuid,nodev,noexec,{mapping}", + f"/proc/self/fd/{fd}", + str(mountpoint), + bind_fd=fd, + ) + target = mountpoint.stat() + if (target.st_uid, target.st_gid) != (uid, gid) or ( + target.st_dev, + target.st_ino, + ) != (info.st_dev, info.st_ino): + run_mount("/usr/bin/umount", str(mountpoint)) + raise ValueError("The SFTP mount did not match the approved folder.") + + +def current_scope(request, marker): + saved = json.loads(read_root_file(marker, mode=0o600)) + if ( + not isinstance(saved, dict) + or saved.keys() != {"scope", "device", "inode"} + or saved["scope"] != request.scope() + or type(saved["device"]) is not int + or type(saved["inode"]) is not int + ): + raise ValueError("The folder login has a different node registration.") + return saved + + +def prepare_jail(request, marker, jail): + public, owner, web_group = web.site_storage(request.site) + require_root_directory(jail, create_mode=0o755) + mountpoint = jail / "public" + if not os.path.lexists(mountpoint): + mountpoint.mkdir(mode=0o000) + if not is_bound(mountpoint): + require_root_directory(mountpoint) + if mountpoint.stat().st_mode & 0o777: + raise ValueError("The unmounted jail must be inaccessible.") + username = request.username + with open_scoped_folder(public, request.folder) as (fd, info): + if ( + info.st_uid != owner + or info.st_gid + not in { + web_group, + web.current_user(request.site.service_user).pw_gid, + } + or info.st_dev != public.stat().st_dev + ): + raise ValueError("Choose a folder owned by the hosting account.") + state = { + "scope": request.scope(), + "device": info.st_dev, + "inode": info.st_ino, + } + if not marker.exists(): + if web.current_user(username) is not None: + raise ValueError( + "The SFTP login already exists outside Coulobre." + ) + write_new_file(marker, json.dumps(state), mode=0o600) + elif state != current_scope(request, marker): + raise ValueError( + "The original authorized folder is no longer available." + ) + web.ensure_system_account(username, jail) + user = web.current_user(username) + group = web.current_group(SFTP_GROUP) + if group is None: + raise ValueError("Set up the Coulobre OpenSSH policy first.") + if username not in group.gr_mem: + web.run("/usr/sbin/usermod", "-a", "-G", SFTP_GROUP, username) + check_sshd(username) + bind_folder(fd, info, mountpoint, user.pw_uid, user.pw_gid) + + +def remove_jail(request, marker, jail, keys): + if not marker.exists(): + if web.current_user(request.username) is not None: + raise ValueError("The SFTP user is outside the managed registry.") + return + current_scope(request, marker) + if os.path.lexists(keys): + check_root_file(keys, mode=0o644) + keys.unlink() + user = web.current_user(request.username) + if user: + web.check_system_account(request.username, jail) + try: + subprocess.run( + ["/usr/bin/pkill", "-KILL", "-u", str(user.pw_uid)], + check=False, + timeout=10, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + except subprocess.TimeoutExpired: + raise ValueError( + "The active SFTP sessions could not be closed." + ) from None + mountpoint = jail / "public" + if is_bound(mountpoint): + run_mount("/usr/bin/umount", str(mountpoint)) + if user: + web.run("/usr/sbin/userdel", request.username) + for directory in (mountpoint, jail): + if os.path.lexists(directory): + require_root_directory(directory) + directory.rmdir() + marker.unlink() + + +def apply_folder_sftp(request): + if os.geteuid() != 0: + raise ValueError("Run folder SFTP operations as root on the web node.") + with web.locked_web_node(fcntl.LOCK_EX): + web.check_reservation(request.site) + require_root_directory(AUTHORIZED_KEYS) + require_root_directory(folder_state(), create_mode=0o700) + require_root_directory(JAIL_ROOT, create_mode=0o755) + keys = AUTHORIZED_KEYS / request.username + marker = folder_state() / f"{request.username}.json" + jail = JAIL_ROOT / request.username + if request.action == "remove": + return remove_jail(request, marker, jail, keys) + if any( + path.exists() for path in (sftp_suspension_path(request.site),) + ): + raise ValueError( + "Resume the hosting account before granting access." + ) + if request.action == "keys" or os.path.lexists(keys): + current_scope(request, marker) + for number, key in enumerate(request.public_keys.splitlines(), 1): + validate_public_key(key, number) + prepare_jail(request, marker, jail) + if os.path.lexists(keys): + check_root_file(keys, mode=0o644) + replace_configuration(keys, request.public_keys) + + +def restore_folder_mounts(): + if not folder_state().exists(): + return + require_root_directory(folder_state()) + require_root_directory(JAIL_ROOT) + for marker in sorted(folder_state().glob("cbf-*.json")): + try: + with web.locked_web_node(fcntl.LOCK_EX): + saved = json.loads(read_root_file(marker, mode=0o600)) + scope = saved["scope"] + path = AUTHORIZED_KEYS / marker.stem + if not path.exists(): + continue + request = FolderSftpRequest.from_manifest( + scope + | { + "action": "keys", + "public_keys": read_root_file(path, mode=0o644), + } + ) + if marker.stem != request.username: + raise ValueError( + "Unexpected folder SFTP registry identity." + ) + prepare_jail(request, marker, JAIL_ROOT / request.username) + except (OSError, KeyError, ValueError) as error: + print( + f"Folder SFTP identity {marker.stem} is unavailable: {error}" + ) + + +def folder_login_exists(site): + directory = folder_state() + if not directory.exists(): + return False + require_root_directory(directory) + return any(directory.glob(folder_user_prefix(site) + "*.json")) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("apply", "restore-mounts")) + arguments = parser.parse_args() + if arguments.action == "restore-mounts": + restore_folder_mounts() + return 0 + return serve_apply_request( + 1, + FolderSftpRequest.from_manifest, + apply_folder_sftp, + identity=lambda request: request.identity(), + limit=FOLDER_LIMIT, + ) diff --git a/src/coulobre/web_node_redirects.py b/src/coulobre/web_node_redirects.py new file mode 100644 index 0000000..7953200 --- /dev/null +++ b/src/coulobre/web_node_redirects.py @@ -0,0 +1,82 @@ +import fcntl +import os +from pathlib import Path + +from . import web_node_apply as web +from .node_files import ( + read_root_file, + replace_configuration, + require_root_directory, +) +from .web_node import WebAlias +from .web_node_aliases import alias_marker, alias_paths, read_alias +from .web_node_tls import https_paths, render_https_configuration +from .web_redirects import redirect_include + + +def apply_redirects(spec): + resource = spec.website + site = resource.site if isinstance(resource, WebAlias) else resource + with web.locked_web_node(fcntl.LOCK_EX): + web.check_reservation(site) + paths = web.SitePaths.for_site(site) + web.check_installation(site, paths) + if isinstance(resource, WebAlias): + if read_alias(alias_marker(resource)) != resource: + raise ValueError( + "This alias is no longer reserved by the website." + ) + http, https = ( + alias_paths(resource), + alias_paths(resource, https=True), + ) + else: + http, https = (paths.apache, paths.enabled), https_paths(paths) + for directory in (paths.apache.parent, paths.enabled.parent): + require_root_directory(directory) + changes = [] + for (available, enabled), rendered in ( + (http, resource.render("apache", socket_path=paths.apache_socket)), + ( + https, + render_https_configuration( + resource, socket_path=paths.apache_socket + ), + ), + ): + if (available, enabled) == https and not ( + os.path.lexists(available) or os.path.lexists(enabled) + ): + continue + web.check_configuration(available, rendered) + web.check_site_link( + enabled, Path("../sites-available") / available.name + ) + previous = read_root_file(available) + if previous != rendered: + changes.append((available, previous, rendered)) + config = Path(redirect_include(site.node_key, resource.domain)) + require_root_directory(config.parent, create_mode=0o755) + previous_rules = ( + read_root_file(config) if os.path.lexists(config) else None + ) + updated = [] + reload_attempted = False + try: + replace_configuration(config, spec.render()) + for path, previous, rendered in changes: + replace_configuration(path, rendered) + updated.append((path, previous)) + web.run("/usr/sbin/apache2ctl", "configtest") + reload_attempted = True + web.run("/usr/sbin/service", "apache2", "reload") + except (ValueError, OSError, KeyboardInterrupt): + for path, previous in reversed(updated): + replace_configuration(path, previous) + if previous_rules is None: + config.unlink(missing_ok=True) + else: + replace_configuration(config, previous_rules) + if reload_attempted: + web.run("/usr/sbin/service", "apache2", "reload") + raise diff --git a/src/coulobre/web_node_retirement.py b/src/coulobre/web_node_retirement.py index 42ddd4e..a04c473 100644 --- a/src/coulobre/web_node_retirement.py +++ b/src/coulobre/web_node_retirement.py @@ -116,6 +116,11 @@ def finish_site_retirement(reservation, retirement): def check_aliases(site): + if site.site_id is None: + from .web_node_folder_sftp import folder_login_exists + + if folder_login_exists(site): + raise ValueError("Remove the website's folder SFTP users first.") directory = alias_directory() if not os.path.lexists(directory): return diff --git a/src/coulobre/web_node_runtime.py b/src/coulobre/web_node_runtime.py index a974b35..7a7822f 100644 --- a/src/coulobre/web_node_runtime.py +++ b/src/coulobre/web_node_runtime.py @@ -93,14 +93,9 @@ def route_legacy_site(site, paths): for socket in (legacy.socket, paths.route) ) actual = read_root_file(config) - from .web_node_usage import without_usage_logs + from .web_redirects import compatible_configs - if actual not in ( - before, - after, - without_usage_logs(before), - without_usage_logs(after), - ): + if actual not in compatible_configs(before, after): raise ValueError(f"Existing configuration differs at {config}.") if actual != after: changes.append((config, actual, after)) diff --git a/src/coulobre/web_redirects.py b/src/coulobre/web_redirects.py new file mode 100644 index 0000000..724b38e --- /dev/null +++ b/src/coulobre/web_redirects.py @@ -0,0 +1,185 @@ +import re +from dataclasses import dataclass +from hashlib import sha256 +from typing import TYPE_CHECKING +from urllib.parse import unquote, urlsplit + +from .domain_names import canonical_domain + +if TYPE_CHECKING: + from .web_node import WebAlias, WebSite + +OPERATION = "set_website_redirects" +MAX_RULES = 25 +MAX_DESTINATION = 500 +REDIRECT_TYPES = {301, 302, 307, 308} +SOURCE = re.compile(r"/[A-Za-z0-9/._~-]{0,180}") +DESTINATION = re.compile(r"[A-Za-z0-9._~:/?\[\]@!&'()*+,;=%#-]+") +CHALLENGE = "/.well-known/acme-challenge" + + +def redirect_include(node_key, domain): + domain = canonical_domain(domain) + digest = sha256(f"{node_key}:{domain}".encode("ascii")).hexdigest() + return f"/etc/apache2/coulobre-redirects/{digest}.conf" + + +def valid_destination(url): + if ( + not isinstance(url, str) + or len(url) > MAX_DESTINATION + or not DESTINATION.fullmatch(url) + or any( + ord(character) < 32 or ord(character) >= 127 + for character in unquote(url) + ) + ): + raise ValueError("Enter a valid absolute HTTP or HTTPS address.") + try: + parts = urlsplit(url) + canonical_domain(parts.hostname or "") + port = parts.port + except ValueError: + raise ValueError( + "Enter a valid absolute HTTP or HTTPS address." + ) from None + if ( + parts.scheme not in {"http", "https"} + or parts.username is not None + or parts.password is not None + or port == 0 + ): + raise ValueError("Enter a valid absolute HTTP or HTTPS address.") + return parts + + +@dataclass(frozen=True) +class RedirectRule: + source: str + destination: str + status: int + + def __post_init__(self): + if not isinstance(self.source, str) or ( + self.source != "*" + and ( + not SOURCE.fullmatch(self.source) + or "//" in self.source + or any(part in {".", ".."} for part in self.source.split("/")) + or self.source == CHALLENGE + or self.source.startswith(CHALLENGE + "/") + ) + ): + raise ValueError( + "Use a website path outside the ACME challenge directory." + ) + valid_destination(self.destination) + if type(self.status) is not int or self.status not in REDIRECT_TYPES: + raise ValueError("Choose a supported HTTP redirect status.") + + def manifest(self): + return { + "source": self.source, + "destination": self.destination, + "status": self.status, + } + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "source", + "destination", + "status", + }: + raise ValueError("Expected a redirect rule.") + return cls(**data) + + def render(self): + pattern = ( + r"^/(?![.]well-known/acme-challenge(?:/|$)).*$" + if self.source == "*" + else "^" + self.source.replace(".", "[.]") + "$" + ) + return ( + f'RedirectMatch {self.status} "{pattern}" "{self.destination}"\n' + ) + + +@dataclass(frozen=True) +class RedirectConfiguration: + website: "WebSite | WebAlias" + rules: tuple[RedirectRule, ...] + + def __post_init__(self): + if len(self.rules) > MAX_RULES or len( + {x.source for x in self.rules} + ) != len(self.rules): + raise ValueError( + "Choose up to 25 rules with distinct source paths." + ) + if ( + any(rule.source == "*" for rule in self.rules) + and len(self.rules) != 1 + ): + raise ValueError( + "Remove site redirects before adding a domain redirect." + ) + for rule in self.rules: + target = valid_destination(rule.destination) + if canonical_domain(target.hostname) == self.website.domain and ( + rule.source == "*" or rule.source == (target.path or "/") + ): + raise ValueError( + "The redirect destination would point back to the source." + ) + + def identity(self): + return {"operation": OPERATION, "website": self.website.manifest()} + + def manifest(self): + return self.identity() | { + "rules": [rule.manifest() for rule in self.rules] + } + + @classmethod + def from_manifest(cls, data): + from .web_node import WebAlias, WebSite + + if data.keys() != {"operation", "website", "rules"} or not isinstance( + data["rules"], list + ): + raise ValueError("Expected a website redirect configuration.") + target = data["website"] + if not isinstance(target, dict): + raise ValueError("Expected a website redirect configuration.") + site = ( + WebAlias.from_manifest(target) + if "site" in target + else WebSite.from_manifest(target) + ) + return cls( + site, + tuple(RedirectRule.from_manifest(rule) for rule in data["rules"]), + ) + + def render(self): + return "".join(rule.render() for rule in self.rules) + + +def compatible_configs(*contents): + from .web_node_usage import without_usage_logs + + for content in contents: + no_redirects = "".join( + line + for line in content.splitlines(keepends=True) + if not re.fullmatch( + r' IncludeOptional "/etc/apache2/coulobre-redirects/' + r'[a-f0-9]{64}[.]conf"\n', + line, + ) + ) + yield content + yield no_redirects + yield without_usage_logs(content) + yield without_usage_logs(no_redirects) From 5bddcd5512c38da6dec0575ad8273dff1d64e073 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:27:02 +0100 Subject: [PATCH 6/9] 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( From 10e8a9d90dae3b2fd434ab489125ac539938927e Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:32:12 +0100 Subject: [PATCH 7/9] Respect operator permissions in system summaries --- docs/deployment.md | 4 +- src/coulobre/hosting/account_metrics.py | 5 ++- src/coulobre/hosting/test_workspaces.py | 55 ++++++++++++++++++++++++- src/coulobre/hosting/workspaces.py | 30 +++++++------- 4 files changed, 74 insertions(+), 20 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 14daf48..bb70586 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -623,8 +623,8 @@ missing a dependency required by the target version. From 0.11 onward, the updater checks installed dependencies before stopping panel services. Markdown release notes require `markdown-it-py` in the panel's virtual -environment. To use the web updater for the first release with this feature, -install the dependency before starting the update. The in-place procedure +environment. When upgrading from 0.11.1 to 0.12 through the panel, install it +first if the existing environment does not have it. The in-place procedure installs it with the panel package. ```sh diff --git a/src/coulobre/hosting/account_metrics.py b/src/coulobre/hosting/account_metrics.py index 1f6ebab..7ee0582 100644 --- a/src/coulobre/hosting/account_metrics.py +++ b/src/coulobre/hosting/account_metrics.py @@ -12,7 +12,7 @@ from .models import ( ) -def account_metrics(accounts, *, databases=True, mailboxes=True): +def account_metrics(accounts, *, databases=True, mailboxes=True, usage=True): accounts = list(accounts) metrics = { account.pk: { @@ -40,6 +40,8 @@ def account_metrics(accounts, *, databases=True, mailboxes=True): .order_by() ): metrics[row[field]][key] = row["total"] + if not usage: + return metrics month = timezone.now().strftime("%Y-%m") for item in WebsiteUsage.objects.filter( account_id__in=metrics, observed_at__isnull=False @@ -76,6 +78,7 @@ def customer_metrics(customers, *, manager=None, operator=None): or operator.has_perm("hosting.view_hostingdatabase"), mailboxes=not operator or operator.has_perm("hosting.view_hostingmailbox"), + usage=not operator or operator.has_perm("hosting.view_websiteusage"), ) rows = defaultdict(list) for account in accounts: diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py index a8b3e92..209a59e 100644 --- a/src/coulobre/hosting/test_workspaces.py +++ b/src/coulobre/hosting/test_workspaces.py @@ -1,13 +1,64 @@ from unittest.mock import patch from django.contrib.auth import get_user_model -from django.test import TestCase +from django.contrib.auth.models import Permission +from django.test import TestCase, override_settings from django.urls import reverse +from django.utils import timezone -from .models import Customer, HostingAccount, HostingPlan, Reseller +from .models import ( + Customer, + HostingAccount, + HostingPlan, + Reseller, + WebsiteScheduledJob, + WebsiteUsage, +) class WorkspaceTests(TestCase): + @override_settings(WEBSITE_USAGE=True) + def test_operator_summary_respects_usage_and_task_permissions(self): + operator = get_user_model().objects.create_user( + "limited-operator", is_staff=True + ) + operator.user_permissions.add( + Permission.objects.get(codename="view_hostingaccount") + ) + account = HostingAccount.objects.create( + name="Hosting", primary_domain="example.test" + ) + WebsiteUsage.objects.create( + account=account, + node_key="site", + domain=account.primary_domain, + report={"storage_bytes": 1024}, + observed_at=timezone.now(), + ) + WebsiteScheduledJob.objects.create( + account=account, + domain=account.primary_domain, + name="Application update", + command="php update.php", + expression="0 * * * *", + ) + self.client.force_login(operator) + statistics = reverse("panel:system_workspace", args=["statistics"]) + tasks = reverse("panel:system_workspace", args=["tasks"]) + self.assertIsNone( + self.client.get(statistics).context["rows"][0][1]["storage"] + ) + self.assertNotContains(self.client.get(tasks), "Application update") + operator.user_permissions.add( + *Permission.objects.filter( + codename__in=("view_websiteusage", "manage_website_jobs") + ) + ) + self.assertEqual( + self.client.get(statistics).context["rows"][0][1]["storage"], 1024 + ) + self.assertContains(self.client.get(tasks), "Application update") + def test_operator_has_its_own_manager_workspace(self): operator = get_user_model().objects.create_superuser("operator") self.client.force_login(operator) diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 36186a8..58479a9 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -12,6 +12,7 @@ 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 +from .website_job_views import can_manage_website_jobs CUSTOMER_ACCOUNT = "coulobre_active_hosting_account" @@ -184,24 +185,22 @@ def system_workspace(request, page): raise Http404 title, target = SYSTEM_PAGES[page] accounts = workspace_accounts(request.user).order_by("primary_domain") - if page == "tasks": - may_open = ( - panel_feature_allowed("WEBSITE_JOBS") - and reseller_for_user(request.user) is None - ) - else: - may_open = settings.WEBSITE_USAGE and ( - customer_for_user(request.user) is not None - or reseller_for_user(request.user) is not None - or request.user.has_perm("hosting.view_websiteusage") - ) - pagination = Paginator(accounts, 25) - page_obj = pagination.get_page(request.GET.get("page")) - month = timezone.now().strftime("%Y-%m") operator = ( customer_for_user(request.user) is None and reseller_for_user(request.user) is None ) + if page == "tasks": + may_open = can_manage_website_jobs(request) + may_view_tasks = not operator or request.user.has_perm( + "hosting.manage_website_jobs" + ) + else: + may_open = settings.WEBSITE_USAGE and ( + not operator or request.user.has_perm("hosting.view_websiteusage") + ) + pagination = Paginator(accounts, 25) + page_obj = pagination.get_page(request.GET.get("page")) + month = timezone.now().strftime("%Y-%m") measures = ( account_metrics( page_obj.object_list, @@ -209,6 +208,7 @@ def system_workspace(request, page): or request.user.has_perm("hosting.view_hostingdatabase"), mailboxes=not operator or request.user.has_perm("hosting.view_hostingmailbox"), + usage=may_open, ) if page == "statistics" else {} @@ -216,7 +216,7 @@ def system_workspace(request, page): rows = [(account, measures.get(account.pk, {})) for account in page_obj] tasks = () task_accounts = {account.pk for account, _ in rows} - if page == "tasks": + if page == "tasks" and may_view_tasks: tasks = ( WebsiteScheduledJob.objects.filter(account_id__in=task_accounts) .select_related("account") From 469c1817ffb860ad41c553c124270b9f691dbc94 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:41:31 +0100 Subject: [PATCH 8/9] Reuse the installer worker group when creating its service user --- deploy/panel_installer/engine.py | 7 +++-- tests/test_panel_installer.py | 45 +++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index 1383d47..9f09a13 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -148,10 +148,12 @@ def identity(name, home="/nonexistent"): try: account = pwd.getpwnam(name) except KeyError: + private_group = group(name) run( "useradd", "--system", - "--user-group", + "--gid", + str(private_group.gr_gid), "--no-create-home", "--home-dir", home, @@ -184,8 +186,9 @@ def install_unit(unit): def install_worker(group_name, user, socket_unit, worker_unit): - group(group_name) identity(user) + if group_name != user: + group(group_name) for unit in ( f"{socket_unit}.socket", f"{socket_unit}@.service", diff --git a/tests/test_panel_installer.py b/tests/test_panel_installer.py index a0fc166..6846080 100644 --- a/tests/test_panel_installer.py +++ b/tests/test_panel_installer.py @@ -14,7 +14,7 @@ from deploy.panel_installer.config import ( read_password, read_plan, ) -from deploy.panel_installer.engine import Installer +from deploy.panel_installer.engine import Installer, install_worker from deploy.panel_installer.web import Wizard, WizardHandler, form_plan PROXY = { @@ -27,6 +27,49 @@ ADMIN = {"username": "operator", "email": "ops@example.net"} class InstallerParametersTests(unittest.TestCase): + def test_worker_can_join_its_existing_private_group(self): + name = "coulobre-operator" + service = f"{name}-worker.service" + account = SimpleNamespace( + pw_gid=983, + pw_uid=984, + pw_dir="/nonexistent", + pw_shell="/usr/sbin/nologin", + ) + with ( + patch( + "deploy.panel_installer.engine.pwd.getpwnam", + side_effect=[KeyError, account], + ), + patch( + "deploy.panel_installer.engine.grp.getgrnam", + return_value=SimpleNamespace(gr_gid=983), + ), + patch( + "deploy.panel_installer.engine.os.getgrouplist", + return_value=[983], + ), + patch("deploy.panel_installer.engine.run") as run, + patch("deploy.panel_installer.engine.install_unit"), + ): + self.assertEqual( + install_worker(name, name, f"{name}-apply", service), + service, + ) + run.assert_called_once_with( + "useradd", + "--system", + "--gid", + "983", + "--no-create-home", + "--home-dir", + "/nonexistent", + "--shell", + "/usr/sbin/nologin", + name, + label=f"Create service user {name}", + ) + def test_default_health_targets_follow_locally_installed_roles(self): cases = ( ({}, None, []), From 7647072c002b7c167b2ee0025cdeb7429b861141 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 23:42:45 +0100 Subject: [PATCH 9/9] Keep the MariaDB version separate from the operator protocol version --- .../templates/hosting/operator_tools.html | 4 +-- .../hosting/test_operator_workspaces.py | 30 ++++++++++++++++++- src/coulobre/operator_node.py | 2 +- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/coulobre/hosting/templates/hosting/operator_tools.html b/src/coulobre/hosting/templates/hosting/operator_tools.html index e761e9f..bcc2316 100644 --- a/src/coulobre/hosting/templates/hosting/operator_tools.html +++ b/src/coulobre/hosting/templates/hosting/operator_tools.html @@ -19,8 +19,8 @@ {% if job.action == 'package-preview' and job.result.fingerprint %}

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

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

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

+ {% elif job.action == 'database-report' and job.result.database_version %} +

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

{% for key, value in job.result.counters.items %}
{{ key }}
{{ value }}
{% endfor %}
{% endif %}
diff --git a/src/coulobre/hosting/test_operator_workspaces.py b/src/coulobre/hosting/test_operator_workspaces.py index dbc32d1..9f5a5ac 100644 --- a/src/coulobre/hosting/test_operator_workspaces.py +++ b/src/coulobre/hosting/test_operator_workspaces.py @@ -1,4 +1,6 @@ import json +from io import BytesIO, StringIO +from types import SimpleNamespace from unittest.mock import patch from django.contrib.auth import get_user_model @@ -8,12 +10,38 @@ from django.urls import reverse from django_otp.plugins.otp_totp.models import TOTPDevice from coulobre.mail_queue import MailQueueAction, change_queue_entry -from coulobre.operator_node import OperatorRequest, packages +from coulobre.operator_node import OperatorRequest, main, packages from .models import PanelTheme class OperatorRequestTests(SimpleTestCase): + def test_database_report_preserves_the_request_protocol_version(self): + request = OperatorRequest("database-report").manifest() + source = BytesIO(json.dumps(request).encode()) + response = StringIO() + with ( + patch("sys.stdin", SimpleNamespace(buffer=source)), + patch("sys.stdout", response), + patch("coulobre.operator_node.os.geteuid", return_value=0), + patch( + "coulobre.operator_node.command", + return_value="11.8.6-MariaDB\t0\nSlow_queries\t7\n", + ), + ): + self.assertEqual(main(), 0) + self.assertEqual( + json.loads(response.getvalue()), + request + | { + "state": "configured", + "problem": None, + "database_version": "11.8.6-MariaDB", + "slow_logging": False, + "counters": {"Slow_queries": "7"}, + }, + ) + def test_unknown_services_and_changed_package_plans_are_rejected(self): with self.assertRaises(ValueError): OperatorRequest("restart", "ssh.service") diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py index 4c79dd7..3599ff9 100644 --- a/src/coulobre/operator_node.py +++ b/src/coulobre/operator_node.py @@ -160,7 +160,7 @@ def database_report(): version, slow_log = rows[0] counters = {key: value for key, value in rows[1:] if value.isdecimal()} return { - "version": version[:80], + "database_version": version[:80], "slow_logging": slow_log == "1", "counters": counters, }