From fbe6571afc0772f07978210ceac89a44e42d355c Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 24 Nov 2026 14:52:11 +0100 Subject: [PATCH 1/2] Allow operators to delete detached panel users --- .../hosting/account_administration.py | 121 +++++++++++++++++- .../hosting/templates/hosting/all_users.html | 13 +- .../templates/hosting/user_delete.html | 24 ++++ src/coulobre/hosting/test_workspaces.py | 110 +++++++++++++++- src/coulobre/hosting/urls.py | 4 + src/coulobre/hosting/workspaces.py | 1 + 6 files changed, 264 insertions(+), 9 deletions(-) create mode 100644 src/coulobre/hosting/templates/hosting/user_delete.html diff --git a/src/coulobre/hosting/account_administration.py b/src/coulobre/hosting/account_administration.py index de47d5e..1ad5036 100644 --- a/src/coulobre/hosting/account_administration.py +++ b/src/coulobre/hosting/account_administration.py @@ -1,6 +1,6 @@ from django import forms from django.contrib import messages -from django.contrib.admin.models import ADDITION, LogEntry +from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.mixins import ( @@ -10,9 +10,12 @@ from django.contrib.auth.mixins import ( 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.db.models.deletion import ProtectedError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect from django.urls import reverse_lazy from django.utils.decorators import method_decorator +from django.utils.functional import cached_property from django.views.decorators.debug import sensitive_post_parameters from django.views.generic import FormView, ListView @@ -341,17 +344,127 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView): [profile.pk for profile in profiles if profile], operator=self.request.user, ) + actor = self.request.user context["login_rows"] = [ - (login, measurements.get(profile.pk) if profile else None) + ( + login, + measurements.get(profile.pk) if profile else None, + deletable_profile(actor, login) is not None, + ) for login, profile in zip(context["logins"], profiles, strict=True) ] - actor = self.request.user context["may_manage_invitations"] = actor.has_perm( "hosting.change_customer" ) or actor.has_perm("hosting.change_reseller") + context["has_user_actions"] = context["may_manage_invitations"] or any( + row[2] for row in context["login_rows"] + ) return context +def deletable_profile(actor, login): + if login.pk == actor.pk or login.is_staff or login.is_superuser: + return None + manager = getattr(login, "hosting_reseller", None) + if manager is not None: + if actor.has_perms( + ("hosting.view_reseller", "hosting.delete_reseller") + ): + return manager + return None + if actor.has_perm("hosting.delete_customer"): + return getattr(login, "hosting_customer", None) + return None + + +def deletion_blocker(profile): + if profile.hostingaccount_set.exists(): + return ( + "This user still has hosting accounts. Reassign or retire those " + "accounts before deleting the login." + ) + if isinstance(profile, Reseller) and profile.managed_customers.exists(): + return ( + "This manager still has assigned customers. Reassign those " + "customers before deleting the login." + ) + return "" + + +class UserDeletionForm(forms.Form): + username = forms.CharField(label="Username", max_length=150) + + +class UserDeleteView(OperatorOnlyMixin, PermissionRequiredMixin, FormView): + permission_required = "hosting.view_customer" + template_name = "hosting/user_delete.html" + form_class = UserDeletionForm + success_url = reverse_lazy("panel:all_users") + + @cached_property + def login(self): + return get_object_or_404( + get_user_model().objects.select_related( + "hosting_customer", "hosting_reseller" + ), + pk=self.kwargs["pk"], + ) + + @cached_property + def profile(self): + profile = deletable_profile(self.request.user, self.login) + if profile is None: + raise Http404 + return profile + + def get_context_data(self, **kwargs): + return super().get_context_data( + login=self.login, blocker=deletion_blocker(self.profile), **kwargs + ) + + def form_valid(self, form): + actor = self.request.user + try: + with transaction.atomic(): + profiles = type(self.profile).objects.filter( + pk=self.profile.pk + ) + locked = ( + lock_resellers(profiles) + if isinstance(self.profile, Reseller) + else profiles.select_for_update() + ) + profile = get_object_or_404(locked, user_id=self.login.pk) + login = get_object_or_404( + get_user_model().objects.select_for_update(), + pk=self.login.pk, + is_staff=False, + is_superuser=False, + ) + if login.get_username() != form.cleaned_data["username"]: + form.add_error( + "username", "Enter the username shown above." + ) + return self.form_invalid(form) + if blocker := deletion_blocker(profile): + raise ValidationError(blocker) + LogEntry.objects.log_actions( + actor.pk, [login], DELETION, "Deleted panel login." + ) + profile.delete() + login.delete() + except ValidationError as error: + form.add_error(None, error) + except ProtectedError: + form.add_error(None, "The login still has linked records.") + else: + messages.success(self.request, "The user was deleted.") + return super().form_valid(form) + return self.render_to_response( + self.get_context_data(form=form), status=409 + ) + + class OperatorAuthorization(UserPassesTestMixin): def test_func(self): user = self.request.user diff --git a/src/coulobre/hosting/templates/hosting/all_users.html b/src/coulobre/hosting/templates/hosting/all_users.html index d2e5885..d5b6a12 100644 --- a/src/coulobre/hosting/templates/hosting/all_users.html +++ b/src/coulobre/hosting/templates/hosting/all_users.html @@ -20,9 +20,9 @@
- {% if may_manage_invitations %}{% endif %} + {% if has_user_actions %}{% endif %} - {% for login, usage in login_rows %} + {% for login, usage, may_delete in login_rows %} @@ -30,8 +30,9 @@ {% include "hosting/account_metrics_cells.html" %} - {% if may_manage_invitations %} + {% if has_user_actions %} {% endif %} - {% empty %}{% endfor %} + {% empty %}{% endfor %}
UserWorkspaceManagerHosting accountsDiskMonthly trafficDomainsDatabasesMailboxesAddedActions
UserWorkspaceManagerHosting accountsDiskMonthly trafficDomainsDatabasesMailboxesAddedActions
{{ login.get_username }} {% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}{{ login.account_count }}{{ login.date_joined|date:"j M Y" }} +
{% if not login.is_staff and not login.is_superuser %} {% if login.hosting_reseller and perms.hosting.change_reseller %} Contact and invitation @@ -39,10 +40,14 @@ Contact and invitation {% endif %} {% endif %} + {% if may_delete %} + Delete user + {% endif %} +
No logins found.
No logins found.
diff --git a/src/coulobre/hosting/templates/hosting/user_delete.html b/src/coulobre/hosting/templates/hosting/user_delete.html new file mode 100644 index 0000000..4625be3 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/user_delete.html @@ -0,0 +1,24 @@ +{% extends "hosting/workspace_page.html" %} +{% block title %}Delete user · Coulobre Panel{% endblock %} +{% block page_title %}Delete user{% endblock %} +{% block page_context %} + ← All users +{% endblock %} +{% block page_content %} +
+

{{ login.get_username }}

+ {% if blocker %} +

{{ blocker }}

+ {% else %} +

Deleting this user permanently removes their panel login, sign-in methods, and invitation. Type the username above to confirm.

+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+ {% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py index 4f7e496..d6de8ec 100644 --- a/src/coulobre/hosting/test_workspaces.py +++ b/src/coulobre/hosting/test_workspaces.py @@ -1,8 +1,9 @@ from unittest.mock import patch +from django.contrib.admin.models import DELETION, LogEntry from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission -from django.test import TestCase, override_settings +from django.test import Client, TestCase, override_settings from django.urls import reverse from django.utils import timezone from django_otp.plugins.otp_totp.models import TOTPDevice @@ -11,12 +12,119 @@ from .models import ( Customer, HostingAccount, HostingPlan, + PanelInvitation, Reseller, WebsiteScheduledJob, WebsiteUsage, ) +class UserDeletionTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.customer = Customer.objects.create(user=users.create_user("user")) + cls.manager = Reseller.objects.create( + user=users.create_user("manager") + ) + + def setUp(self): + self.client.force_login(self.operator) + self.index = reverse("panel:all_users") + self.delete = reverse( + "panel:user_delete", args=[self.customer.user_id] + ) + + def test_confirmation_deletes_only_the_login_and_audits_the_deletion(self): + invite = PanelInvitation.objects.create(user=self.customer.user) + other = HostingAccount.objects.create( + name="Unrelated", primary_domain="unrelated.example" + ) + self.assertContains(self.client.get(self.index), self.delete) + self.assertContains(self.client.get(self.delete), "Type the username") + response = self.client.post(self.delete, {"username": "wrong"}) + self.assertContains(response, "Enter the username shown above.") + self.assertTrue(Customer.objects.filter(pk=self.customer.pk).exists()) + self.assertFalse(LogEntry.objects.exists()) + + self.assertRedirects( + self.client.post(self.delete, {"username": "user"}), self.index + ) + self.assertFalse(Customer.objects.filter(pk=self.customer.pk).exists()) + self.assertFalse( + get_user_model().objects.filter(pk=self.customer.user_id).exists() + ) + self.assertFalse(PanelInvitation.objects.filter(pk=invite.pk).exists()) + self.assertTrue(HostingAccount.objects.filter(pk=other.pk).exists()) + event = LogEntry.objects.get(action_flag=DELETION) + self.assertEqual(event.user, self.operator) + self.assertEqual(event.object_repr, "user") + self.assertEqual(self.client.get(self.delete).status_code, 404) + + def test_attached_hosting_added_after_preview_blocks_deletion(self): + self.assertContains(self.client.get(self.delete), "Type the username") + account = HostingAccount.objects.create( + name="Owned", + primary_domain="owned.example", + customer=self.customer, + ) + response = self.client.post(self.delete, {"username": "user"}) + self.assertContains( + response, "still has hosting accounts", status_code=409 + ) + account.refresh_from_db() + self.assertEqual(account.customer_id, self.customer.pk) + self.assertFalse(LogEntry.objects.exists()) + + def test_manager_cannot_be_deleted_until_its_customers_are_reassigned( + self, + ): + self.customer.reseller = self.manager + self.customer.save(update_fields=["reseller"]) + url = reverse("panel:user_delete", args=[self.manager.user_id]) + self.assertContains(self.client.get(self.index), url) + self.assertContains( + self.client.post(url, {"username": "manager"}), + "still has assigned customers", + status_code=409, + ) + self.customer.refresh_from_db() + self.assertEqual(self.customer.reseller, self.manager) + self.customer.reseller = None + self.customer.save(update_fields=["reseller"]) + self.assertRedirects( + self.client.post(url, {"username": "manager"}), self.index + ) + self.assertFalse(Reseller.objects.filter(pk=self.manager.pk).exists()) + + def test_permission_and_csrf_checks_apply_to_direct_submissions(self): + operator_url = reverse("panel:user_delete", args=[self.operator.pk]) + self.assertNotContains(self.client.get(self.index), operator_url) + self.assertEqual( + self.client.post( + operator_url, {"username": "operator"} + ).status_code, + 404, + ) + browser = Client(enforce_csrf_checks=True) + browser.force_login(self.operator) + self.assertEqual( + browser.post(self.delete, {"username": "user"}).status_code, 403 + ) + viewer = get_user_model().objects.create_user("viewer", is_staff=True) + viewer.user_permissions.add( + Permission.objects.get(codename="view_customer") + ) + self.client.force_login(viewer) + self.assertNotContains(self.client.get(self.index), self.delete) + self.assertEqual( + self.client.post(self.delete, {"username": "user"}).status_code, + 404, + ) + self.assertTrue(Customer.objects.filter(pk=self.customer.pk).exists()) + + class WorkspaceTests(TestCase): def test_operator_creates_and_links_the_first_hosting_account(self): users = get_user_model().objects diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 7888989..f421c2a 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -8,6 +8,7 @@ from .account_administration import ( ManagerPackagesView, MoveHostingView, OperatorCreateView, + UserDeleteView, ) from .account_security import ( AccountSecurityView, @@ -242,6 +243,9 @@ urlpatterns = [ ), path("system//", system_workspace, name="system_workspace"), path("users/", AllUsersView.as_view(), name="all_users"), + path( + "users//delete/", UserDeleteView.as_view(), name="user_delete" + ), path( "users/new/", CustomerOnboardingView.as_view(), diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 1ae7ce9..e68f871 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -67,6 +67,7 @@ CUSTOMER_NAV_ROUTES = { } WORKSPACE_PARENT_ROUTES = { + "user_delete": ("all_users", ()), "remote_deploy": ("connected_nodes", ()), "dns_topology": ("dns_defaults", ()), "operator_settings": ("operator_settings", ("general",)), -- 2.43.0 From aebe978780ce7c900d34bb8b681d9b66e0b7500b Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 24 Nov 2026 14:52:11 +0100 Subject: [PATCH 2/2] Link unconfigured features to setup instructions --- src/coulobre/hosting/installation_features.py | 37 +++++++++++++++++++ src/coulobre/hosting/installation_views.py | 10 ++++- .../hosting/feature_configuration.html | 18 +++++++++ .../templates/hosting/feature_setup.html | 7 ++++ .../templates/hosting/installation.html | 8 +++- .../hosting/test_feature_configuration.py | 21 +++++++++++ 6 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 src/coulobre/hosting/templates/hosting/feature_setup.html diff --git a/src/coulobre/hosting/installation_features.py b/src/coulobre/hosting/installation_features.py index bf499a8..77de4a8 100644 --- a/src/coulobre/hosting/installation_features.py +++ b/src/coulobre/hosting/installation_features.py @@ -10,15 +10,26 @@ from coulobre.linked_updates import UNIT_DIR from .dns_defaults import zone_defaults from .models import PanelFeaturePolicy +DEPLOYMENT_GUIDE = ( + "https://code.hosting.hippogrief.nl/hippogrief/coulobre/" + "src/branch/main/docs/deployment.md" +) + @dataclass(frozen=True) class Feature: setting: str label: str prerequisite: str + setup_anchor: str + setup_instruction: str socket: str = "" role: str = "" + @property + def setup_url(self): + return f"{DEPLOYMENT_GUIDE}#{self.setup_anchor}" + @property def configured(self): if self.setting == "DEFAULT_DNS_ZONES": @@ -68,30 +79,40 @@ FEATURES = ( "LOCAL_WEB_ACTIVATION", "Website provisioning", "Apache and PHP provisioning", + "activate-local-websites-from-the-panel", + "Install and enable the local web provisioning worker.", "coulobre-web-apply", ), Feature( "LOCAL_WEB_HTTPS", "Managed website certificates", "Website certificate provisioning", + "request-https-from-the-panel", + "Configure Certbot and install the website certificate worker.", "coulobre-https-apply", ), Feature( "WEB_FILE_MANAGER", "Website file manager", "Website file service", + "enable-the-website-file-manager", + "Install the website file service and enable it for the panel.", "coulobre-website-files", ), Feature( "WEBSITE_JOBS", "Website scheduled tasks", "Website task service", + "enable-scheduled-website-jobs", + "Install the task worker and allow tasks in the hosting package.", "coulobre-website-jobs", ), Feature( "LOCAL_DNS_PUBLISHING", "DNS publishing", "Local BIND9 or a linked DNS receiver", + "publish-local-dns-zones-from-the-panel", + "Configure local BIND9 or connect a Coulobre DNS receiver.", "coulobre-dns-apply", "dns", ), @@ -99,11 +120,15 @@ FEATURES = ( "DEFAULT_DNS_ZONES", "Default managed DNS zones for new accounts", "DNS publishing, nameservers and hosting IP addresses", + "set-defaults-for-new-hosting-accounts", + "Enable DNS publishing and set nameservers and hosting IPs.", ), Feature( "LOCAL_MAILBOX_PROVISIONING", "Mailbox provisioning", "Local mail services or a linked mail receiver", + "provision-local-mailboxes-from-the-panel", + "Set up local mail services or connect a Coulobre mail receiver.", "coulobre-mail-apply", "mail", ), @@ -111,35 +136,47 @@ FEATURES = ( "MANAGE_MAIL_DNS", "Managed mail DNS records", "Mail exchanger and sending IP addresses", + "check-and-provision-mail-dns", + "Set the mail exchanger and public sending IPs, then enable mail DNS.", ), Feature( "LOCAL_DATABASE_PROVISIONING", "Database provisioning", "MariaDB provisioning", + "provision-local-databases-from-the-panel", + "Install the MariaDB provisioning worker and enable it for the panel.", "coulobre-database-apply", ), Feature( "LOCAL_ACCOUNT_BACKUPS", "Local account backups", "Local backup service", + "start-local-account-backups-from-the-panel", + "Install the account backup worker and enable it for the panel.", "coulobre-account-backup", ), Feature( "OFFSITE_BACKUP_DESTINATIONS", "Off-site backup destinations", "A configured destination and the transfer service", + "copy-scheduled-account-backups-off-site", + "Set up local backups, a restic destination and the transfer worker.", "coulobre-account-offsite", ), Feature( "PHPMYADMIN_URL", "phpMyAdmin sign-in", "phpMyAdmin bridge and MariaDB credential service", + "open-phpmyadmin-from-the-panel", + "Enable database credential access and set up the HTTPS bridge.", "coulobre-service-credentials", ), Feature( "ROUNDCUBE_URL", "Roundcube sign-in", "Roundcube bridge and mailbox credential service", + "open-a-mailbox-in-roundcube", + "Enable mailbox credential access and set up the HTTPS bridge.", ), ) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 43a2fd5..66bbe7b 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -84,12 +84,18 @@ class FeatureConfigurationForm(forms.Form): def __init__(self, *args, policy, section=None, **kwargs): super().__init__(*args, **kwargs) self.initial["revision"] = policy.saved.revision - self.configured_features = [ + features = [ feature for feature in FEATURES if (section is None or feature.setting in section) - and feature.configured ] + self.configured_features = [] + self.features_requiring_setup = [] + for feature in features: + if feature.configured: + self.configured_features.append(feature) + else: + self.features_requiring_setup.append(feature) for feature in self.configured_features: self.fields[feature.setting] = forms.BooleanField( required=False, diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html index 258ef47..5b8c0a0 100644 --- a/src/coulobre/hosting/templates/hosting/feature_configuration.html +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -42,5 +42,23 @@ + {% if form.features_requiring_setup %} +
+

Requires setup

+
+ + + + {% for feature in form.features_requiring_setup %} + + + + + {% endfor %} + +
FeatureSetup
{{ feature.label }}{% include "hosting/feature_setup.html" with show_dns_link=True %}
+
+
+ {% endif %} {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/feature_setup.html b/src/coulobre/hosting/templates/hosting/feature_setup.html new file mode 100644 index 0000000..c3e9343 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/feature_setup.html @@ -0,0 +1,7 @@ +

{{ feature.setup_instruction }}

+
+ Setup guide + {% if show_dns_link and feature.setting == 'DEFAULT_DNS_ZONES' %} + Configure DNS defaults + {% endif %} +
diff --git a/src/coulobre/hosting/templates/hosting/installation.html b/src/coulobre/hosting/templates/hosting/installation.html index 9877008..793c7c7 100644 --- a/src/coulobre/hosting/templates/hosting/installation.html +++ b/src/coulobre/hosting/templates/hosting/installation.html @@ -42,7 +42,13 @@ {% endif %} - {{ feature.prerequisite }} + + {% if configured and feature.socket_ready %} + {{ feature.prerequisite }} + {% else %} + {% include "hosting/feature_setup.html" %} + {% endif %} + {% endfor %} diff --git a/src/coulobre/hosting/test_feature_configuration.py b/src/coulobre/hosting/test_feature_configuration.py index b4da145..a9f9910 100644 --- a/src/coulobre/hosting/test_feature_configuration.py +++ b/src/coulobre/hosting/test_feature_configuration.py @@ -5,6 +5,7 @@ from django.test import TestCase, override_settings from django.urls import reverse from django_otp.plugins.otp_totp.models import TOTPDevice +from .installation_features import FEATURES from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy @@ -28,6 +29,26 @@ class FeatureConfigurationTests(TestCase): def save(self, **data): return self.client.post(reverse("panel:feature_configuration"), data) + @override_settings(LOCAL_WEB_HTTPS=False) + def test_setup_guides_are_visible_where_unconfigured_features_appear(self): + self.sign_in() + certificates = next( + feature + for feature in FEATURES + if feature.setting == "LOCAL_WEB_HTTPS" + ) + for route, args in ( + ("installation", ()), + ("feature_configuration", ()), + ("operator_settings", ("security",)), + ): + with self.subTest(route=route): + page = self.client.get(reverse(f"panel:{route}", args=args)) + self.assertContains(page, "Requires setup") + self.assertContains(page, certificates.setup_instruction) + self.assertContains(page, f'href="{certificates.setup_url}"') + self.assertNotContains(page, 'name="LOCAL_WEB_HTTPS"') + def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible( self, ): -- 2.43.0