From 1933827a1cbe3c12ba80c2d43cbf669b4638ff85 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 20:28:22 +0100 Subject: [PATCH 1/3] Switch panel roles with server-enforced account scope --- src/coulobre/hosting/access.py | 15 ++ .../0058_scope_service_signon_grants.py | 22 ++ src/coulobre/hosting/models.py | 1 + src/coulobre/hosting/panel_roles.py | 209 ++++++++++++++++++ src/coulobre/hosting/phpmyadmin.py | 21 +- src/coulobre/hosting/reseller_onboarding.py | 7 +- src/coulobre/hosting/roundcube.py | 16 +- src/coulobre/hosting/signon.py | 14 ++ src/coulobre/hosting/static/hosting/panel.css | 16 ++ .../templates/hosting/assign_panel_role.html | 15 ++ .../hosting/templates/hosting/base.html | 12 + .../templates/hosting/customer_list.html | 7 +- .../templates/hosting/reseller_list.html | 3 + src/coulobre/hosting/test_panel_roles.py | 146 ++++++++++++ src/coulobre/hosting/urls.py | 7 + src/coulobre/settings.py | 1 + 16 files changed, 497 insertions(+), 15 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0058_scope_service_signon_grants.py create mode 100644 src/coulobre/hosting/panel_roles.py create mode 100644 src/coulobre/hosting/templates/hosting/assign_panel_role.html create mode 100644 src/coulobre/hosting/test_panel_roles.py diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 9359e05..14515f2 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -1,3 +1,12 @@ +from enum import StrEnum + + +class PanelRole(StrEnum): + ADMIN = "administrator" + MANAGER = "manager" + CUSTOMER = "customer" + + NAVIGATION_SECTIONS = { "accounts": "accounts", "retired-accounts": "accounts", @@ -14,12 +23,18 @@ NAVIGATION_SECTIONS = { def customer_for_user(user): + role = getattr(user, "panel_role", None) + if role is not None and role != PanelRole.CUSTOMER: + return None if not user.is_authenticated or user.is_superuser: return None return getattr(user, "hosting_customer", None) def reseller_for_user(user): + role = getattr(user, "panel_role", None) + if role is not None and role != PanelRole.MANAGER: + return None if ( not user.is_authenticated or user.is_superuser diff --git a/src/coulobre/hosting/migrations/0058_scope_service_signon_grants.py b/src/coulobre/hosting/migrations/0058_scope_service_signon_grants.py new file mode 100644 index 0000000..c577c66 --- /dev/null +++ b/src/coulobre/hosting/migrations/0058_scope_service_signon_grants.py @@ -0,0 +1,22 @@ +# Generated by Django 5.2.19 on 2026-11-23 19:26 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0057_panel_account_security"), + ] + + operations = [ + migrations.AddField( + model_name="phpmyadmingrant", + name="actor_scope", + field=models.JSONField(blank=True, default=list), + ), + migrations.AddField( + model_name="roundcubegrant", + name="actor_scope", + field=models.JSONField(blank=True, default=list), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 749b761..e7ac10f 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -582,6 +582,7 @@ class ServiceSignOnGrant(models.Model): actor = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) + actor_scope = models.JSONField(default=list, blank=True) expires_at = models.DateTimeField(db_index=True) redeemed_at = models.DateTimeField(null=True, blank=True) diff --git a/src/coulobre/hosting/panel_roles.py b/src/coulobre/hosting/panel_roles.py new file mode 100644 index 0000000..aa811cc --- /dev/null +++ b/src/coulobre/hosting/panel_roles.py @@ -0,0 +1,209 @@ +from copy import copy + +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, logout +from django.contrib.auth.middleware import get_user +from django.contrib.auth.mixins import UserPassesTestMixin +from django.core.exceptions import PermissionDenied +from django.db import transaction +from django.middleware.csrf import rotate_token +from django.shortcuts import redirect +from django.utils.cache import add_never_cache_headers +from django.utils.decorators import method_decorator +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 PanelRole +from .models import Customer, Reseller, ResellerProfile + +SESSION_ROLE = "coulobre_panel_role" +ROLE_LABELS = { + PanelRole.ADMIN: "Server administrator", + PanelRole.CUSTOMER: "Customer", + PanelRole.MANAGER: "Customer manager", +} + + +def assigned_roles(user): + if not user.is_authenticated or not user.is_active: + return {} + roles = {} + if user.is_superuser or ( + user.is_staff and user.has_perm("hosting.view_hostingaccount") + ): + roles[PanelRole.ADMIN] = user.pk + customer = getattr(user, "hosting_customer", None) + if customer is not None: + roles[PanelRole.CUSTOMER] = customer.pk + manager = getattr(user, "hosting_reseller", None) + if manager is not None: + roles[PanelRole.MANAGER] = manager.pk + return roles + + +def deny_permission(*args, **kwargs): + return False + + +def no_permissions(*args, **kwargs): + return set() + + +async def deny_async_permission(*args, **kwargs): + return False + + +async def no_async_permissions(*args, **kwargs): + return set() + + +def scoped_user(user, role): + actor = copy(user) + actor.panel_role = role + if role != PanelRole.ADMIN: + actor.is_staff = actor.is_superuser = False + actor.has_perm = actor.has_perms = actor.has_module_perms = ( + deny_permission + ) + actor.get_all_permissions = actor.get_user_permissions = ( + actor.get_group_permissions + ) = no_permissions + actor.ahas_perm = actor.ahas_perms = actor.ahas_module_perms = ( + deny_async_permission + ) + actor.aget_all_permissions = actor.aget_user_permissions = ( + actor.aget_group_permissions + ) = no_async_permissions + return actor + + +class PanelRoleMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + if getattr(request, "active_panel_role", None): + add_never_cache_headers(response) + return response + + def process_view(self, request, view_func, view_args, view_kwargs): + if not request.user.is_authenticated: + return None + user = get_user(request) + roles = assigned_roles(user) + selection = request.session.get(SESSION_ROLE) + if selection is None: + if len(roles) < 2: + return None + role, assignment = next(iter(roles.items())) + request.session[SESSION_ROLE] = [role, assignment] + else: + role, assignment = selection + if roles.get(role) != assignment: + logout(request) + messages.warning( + request, "Your panel roles changed. Sign in again." + ) + return redirect("panel:login") + + request.active_panel_role = role + request.panel_role_options = [ + (option, ROLE_LABELS[option]) for option in roles + ] + request.user = scoped_user(user, role) + + async def role_user(): + return request.user + + request.auser = role_user + return None + + +@require_POST +def switch_panel_role(request): + if not request.user.is_authenticated or getattr( + request, "impersonation", None + ): + raise PermissionDenied + user = get_user(request) + roles = assigned_roles(user) + role = request.POST.get("role") + if role not in roles or len(roles) < 2: + raise PermissionDenied + if role == PanelRole.ADMIN and not request.user.is_verified(): + raise PermissionDenied + if role != request.active_panel_role: + request.session.cycle_key() + request.session[SESSION_ROLE] = [role, roles[role]] + rotate_token(request) + return redirect("panel:accounts") + + +ROLE_MODELS = {PanelRole.CUSTOMER: Customer, PanelRole.MANAGER: Reseller} + + +class AssignPanelRoleForm(forms.Form): + username = forms.CharField(max_length=150, label="Existing username") + role = forms.ChoiceField( + choices=[(role, ROLE_LABELS[role]) for role in ROLE_MODELS], + label="Role to assign", + ) + + +@method_decorator(never_cache, name="dispatch") +class AssignPanelRoleView(UserPassesTestMixin, FormView): + form_class = AssignPanelRoleForm + template_name = "hosting/assign_panel_role.html" + + def test_func(self): + return ( + self.request.user.is_superuser and self.request.user.is_verified() + ) + + def get_initial(self): + role = self.request.GET.get("role") + return {"role": role} if role in ROLE_MODELS else {} + + @transaction.atomic + def form_valid(self, form): + user = ( + get_user_model() + .objects.select_for_update() + .filter(username=form.cleaned_data["username"], is_active=True) + .first() + ) + if user is None: + form.add_error("username", "Choose an active panel login.") + return self.form_invalid(form) + role = form.cleaned_data["role"] + assignment, created = ROLE_MODELS[role].objects.get_or_create( + user=user + ) + if not created: + form.add_error("role", "This login already has that role.") + return self.form_invalid(form) + if role == PanelRole.MANAGER: + profile = ResellerProfile.objects.filter(default_slot=1).first() + if profile is not None: + assignment.account_limit = profile.account_limit + assignment.manage_resources = profile.manage_resources + assignment.save( + update_fields=["account_limit", "manage_resources"] + ) + assignment.hosting_plans.set(profile.hosting_plans.all()) + LogEntry.objects.log_actions( + self.request.user.pk, + [assignment], + ADDITION, + "Assigned panel role.", + ) + messages.success( + self.request, f"Assigned {ROLE_LABELS[role]} to {user}." + ) + if role == PanelRole.MANAGER: + return redirect(assignment) + return redirect("panel:customers") diff --git a/src/coulobre/hosting/phpmyadmin.py b/src/coulobre/hosting/phpmyadmin.py index ea5c766..9d7e356 100644 --- a/src/coulobre/hosting/phpmyadmin.py +++ b/src/coulobre/hosting/phpmyadmin.py @@ -1,4 +1,5 @@ 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.views.decorators.cache import never_cache @@ -19,7 +20,12 @@ from .service_credentials import ( enabled_credential_access, fetch_service_credentials, ) -from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant +from .signon import ( + bridge_ticket, + consume_signon_grant, + issue_signon_grant, + signon_actor, +) def phpmyadmin_available(request): @@ -79,9 +85,10 @@ def redeem_phpmyadmin(request): raise Http404 token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY) grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account") - if grant is None or not actor_has_database_access( - grant.actor, grant.database - ): + if grant is None: + raise Http404 + actor = signon_actor(grant, grant.actor) + if actor is None or not actor_has_database_access(actor, grant.database): raise Http404 database = grant.database @@ -107,10 +114,14 @@ def redeem_phpmyadmin(request): .filter(pk=database.pk) .first() ) + actor = signon_actor( + grant, get_user_model().objects.filter(pk=grant.actor_id).first() + ) if ( current is None + or actor is None or current.spec != database.spec - or not actor_has_database_access(grant.actor, current) + or not actor_has_database_access(actor, current) ): audit.outcome = CredentialOutcome.UNAVAILABLE audit.save(update_fields=["outcome"]) diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py index 909e95a..a5d8551 100644 --- a/src/coulobre/hosting/reseller_onboarding.py +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -1,7 +1,6 @@ from django.core.exceptions import PermissionDenied, ValidationError from django.db import transaction -from .access import reseller_for_user from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent from .reseller_accounts import lock_resellers, record_event from .resource_requests import lock_hosting_account, require_open_account @@ -24,11 +23,7 @@ def lock_reseller_account(access, account_id, *, resources=False): reseller = lock_resellers( Reseller.objects.filter(pk=access.pk, user_id=access.user_id) ).first() - if ( - reseller is None - or not reseller.user.is_active - or reseller_for_user(reseller.user) is None - ): + if reseller is None or not reseller.user.is_active: raise PermissionDenied if resources and not reseller.manage_resources: raise PermissionDenied diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py index 8c3ce1d..cbc5a61 100644 --- a/src/coulobre/hosting/roundcube.py +++ b/src/coulobre/hosting/roundcube.py @@ -20,7 +20,12 @@ from .service_credentials import ( enabled_credential_access, fetch_service_credentials, ) -from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant +from .signon import ( + bridge_ticket, + consume_signon_grant, + issue_signon_grant, + signon_actor, +) def roundcube_available(request): @@ -105,7 +110,10 @@ def redeem_roundcube(request): "mailbox__mail_domain__account", "mailbox__provisioning", ) - if grant is None or not actor_can_open_webmail(grant.actor, grant.mailbox): + if grant is None: + raise Http404 + actor = signon_actor(grant, grant.actor) + if actor is None or not actor_can_open_webmail(actor, grant.mailbox): raise Http404 mailbox = grant.mailbox spec = mailbox.spec @@ -136,7 +144,9 @@ def redeem_roundcube(request): .filter(pk=mailbox.pk) .first() ) - actor = get_user_model().objects.filter(pk=grant.actor_id).first() + actor = signon_actor( + grant, get_user_model().objects.filter(pk=grant.actor_id).first() + ) if ( current is None or actor is None diff --git a/src/coulobre/hosting/signon.py b/src/coulobre/hosting/signon.py index af7a0ef..e395411 100644 --- a/src/coulobre/hosting/signon.py +++ b/src/coulobre/hosting/signon.py @@ -9,6 +9,8 @@ from django.http import Http404 from django.utils import timezone from django.views.decorators.debug import sensitive_variables +from .panel_roles import assigned_roles, scoped_user + GRANT_LIFETIME = timedelta(seconds=45) TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}") @@ -18,15 +20,27 @@ def issue_signon_grant(model, actor, **selection): now = timezone.now() model.objects.filter(expires_at__lte=now).delete() token = secrets.token_urlsafe(32) + role = getattr(actor, "panel_role", None) + scope = [role, assigned_roles(actor).get(role)] if role else [] model.objects.create( token_digest=token_digest(token), actor=actor, + actor_scope=scope, expires_at=now + GRANT_LIFETIME, **selection, ) return token +def signon_actor(grant, actor): + if actor is None or not grant.actor_scope: + return actor + role, assignment = grant.actor_scope + if assignment is None or assigned_roles(actor).get(role) != assignment: + return None + return scoped_user(actor, role) + + @sensitive_variables() def token_digest(token): return hashlib.sha256(token.encode("ascii")).hexdigest() diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index fc48ad4..f62287a 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -331,6 +331,22 @@ button, input, select, textarea { text-underline-offset: 0.2em; } +.panel-role-switch { + display: grid; + gap: 0.3rem; + margin: 0.6rem 0; + font-size: 0.82rem; +} + +.panel-role-switch select { + width: 100%; + background: var(--sidebar-active); + color: var(--sidebar-text); + border: 1px solid var(--sidebar-control-line); + border-radius: 0.35rem; + padding: 0.35rem; +} + .sidebar-account button { padding: 0; border: 0; diff --git a/src/coulobre/hosting/templates/hosting/assign_panel_role.html b/src/coulobre/hosting/templates/hosting/assign_panel_role.html new file mode 100644 index 0000000..6a9c84a --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/assign_panel_role.html @@ -0,0 +1,15 @@ +{% extends "hosting/base.html" %} +{% block title %}Assign panel role · Coulobre Panel{% endblock %} +{% block content %} +

Assign a role to an existing login

+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index efc886d..c17a9e7 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -90,6 +90,18 @@ {{ request.user.get_username }} {% else %} {{ request.user.get_username }} + {% if request.panel_role_options|length > 1 %} +
+ {% csrf_token %} + + + +
+ {% endif %} {% endif %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html index 57b4015..8dd8469 100644 --- a/src/coulobre/hosting/templates/hosting/customer_list.html +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -7,7 +7,12 @@

Manage the logins people use to access their assigned hosting.

{% if is_operator and perms.hosting.add_customer %} - Add customer login +
+ {% if request.user.is_superuser and request.user.is_verified %} + Assign to existing login + {% endif %} + Add customer login +
{% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/reseller_list.html b/src/coulobre/hosting/templates/hosting/reseller_list.html index 75d9e26..7f8b29e 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_list.html +++ b/src/coulobre/hosting/templates/hosting/reseller_list.html @@ -8,6 +8,9 @@ Profiles {% endif %} {% if perms.hosting.add_reseller %} + {% if request.user.is_superuser and request.user.is_verified %} + Assign to existing login + {% endif %} Add customer manager {% endif %} diff --git a/src/coulobre/hosting/test_panel_roles.py b/src/coulobre/hosting/test_panel_roles.py new file mode 100644 index 0000000..279136c --- /dev/null +++ b/src/coulobre/hosting/test_panel_roles.py @@ -0,0 +1,146 @@ +from django.contrib.auth import get_user_model +from django.test import Client, TestCase +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .access import PanelRole, customer_for_user +from .models import ( + Customer, + HostingAccount, + HostingDatabase, + PhpMyAdminGrant, + Reseller, +) +from .panel_roles import scoped_user +from .signon import consume_signon_grant, issue_signon_grant, signon_actor + + +class PanelRoleTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.admin = users.create_superuser("operator") + cls.device = TOTPDevice.objects.create(user=cls.admin, name="Panel") + cls.customer = Customer.objects.create(user=cls.admin) + cls.manager = Reseller.objects.create(user=cls.admin) + cls.private_site = HostingAccount.objects.create( + name="Personal", + primary_domain="mine.example", + customer=cls.customer, + ) + cls.managed_site = HostingAccount.objects.create( + name="Managed", + primary_domain="managed.example", + reseller=cls.manager, + ) + cls.other_site = HostingAccount.objects.create( + name="Other", primary_domain="other.example" + ) + + def sign_in(self, *, verified=True): + self.client.force_login(self.admin) + if verified: + session = self.client.session + session["otp_device_id"] = self.device.persistent_id + session.save() + + def switch(self, role): + return self.client.post( + reverse("panel:switch_panel_role"), {"role": role} + ) + + def test_switch_enforces_assigned_scope_on_lists_and_direct_urls(self): + self.sign_in() + home = reverse("panel:accounts") + response = self.client.get(home) + self.assertContains(response, "Server administrator") + self.assertContains(response, "other.example") + self.assertRedirects(self.switch("manager"), home) + response = self.client.get(home) + self.assertContains(response, "managed.example") + self.assertNotContains(response, "mine.example") + self.assertNotContains(response, "other.example") + self.assertEqual( + self.client.get(reverse("panel:updates")).status_code, 403 + ) + self.assertEqual( + self.client.get(self.private_site.get_absolute_url()).status_code, + 404, + ) + self.assertRedirects(self.switch("customer"), home) + response = self.client.get(home) + self.assertContains(response, "mine.example") + self.assertNotContains(response, "managed.example") + self.assertEqual( + self.client.get(self.managed_site.get_absolute_url()).status_code, + 404, + ) + self.assertEqual( + self.client.post( + reverse("panel:account_edit", args=[self.other_site.pk]), {} + ).status_code, + 403, + ) + self.assertRedirects(self.switch("administrator"), home) + self.assertContains(self.client.get(home), "other.example") + self.admin.refresh_from_db() + self.assertTrue(self.admin.is_superuser) + + def test_admin_cannot_be_restored_without_verified_second_factor(self): + self.sign_in(verified=False) + self.assertEqual(self.switch("customer").status_code, 302) + self.assertEqual(self.switch("administrator").status_code, 403) + self.assertEqual(self.switch("forged-role").status_code, 403) + + def test_removed_assignment_signs_out_before_processing_request(self): + self.sign_in() + self.assertEqual(self.switch("manager").status_code, 302) + self.managed_site.delete() + self.manager.delete() + response = self.client.get(reverse("panel:updates")) + self.assertRedirects(response, reverse("panel:login")) + self.assertNotIn("_auth_user_id", self.client.session) + + def test_assignment_requires_verified_superuser(self): + user = get_user_model().objects.create_user("another") + url = reverse("panel:assign_panel_role") + self.sign_in(verified=False) + self.assertEqual( + self.client.post( + url, {"username": user.username, "role": "customer"} + ).status_code, + 403, + ) + self.sign_in() + self.assertRedirects( + self.client.post( + url, {"username": user.username, "role": "customer"} + ), + reverse("panel:customers"), + ) + self.assertTrue(Customer.objects.filter(user=user).exists()) + + def test_role_switch_requires_csrf(self): + client = Client(enforce_csrf_checks=True) + client.force_login(self.admin) + response = client.post( + reverse("panel:switch_panel_role"), {"role": "manager"} + ) + self.assertEqual(response.status_code, 403) + + def test_signon_ticket_keeps_the_scope_under_which_it_was_issued(self): + database = HostingDatabase.objects.create( + account=self.private_site, suffix="test" + ) + actor = scoped_user(self.admin, PanelRole.CUSTOMER) + token = issue_signon_grant(PhpMyAdminGrant, actor, database=database) + grant = consume_signon_grant(PhpMyAdminGrant, token) + effective = signon_actor(grant, grant.actor) + self.assertFalse(effective.is_superuser) + self.assertEqual(customer_for_user(effective), self.customer) + self.private_site.customer = None + self.private_site.save(update_fields=["customer"]) + self.customer.delete() + self.assertIsNone( + signon_actor(grant, get_user_model().objects.get(pk=self.admin.pk)) + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index d042626..ede017a 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -27,6 +27,7 @@ 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 .panel_roles import AssignPanelRoleView, switch_panel_role from .password_reset import ( CustomerPasswordResetView, CustomerResetCompleteView, @@ -88,6 +89,12 @@ urlpatterns = [ "service-health/", ServiceHealthView.as_view(), name="service_health" ), path("about/", InstallationView.as_view(), name="installation"), + path("account/role/", switch_panel_role, name="switch_panel_role"), + path( + "logins/assign-role/", + AssignPanelRoleView.as_view(), + name="assign_panel_role", + ), path("sign-in/", PanelLoginView.as_view(), name="login"), path( "welcome///", diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 83a942a..bbdfe69 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -90,6 +90,7 @@ MIDDLEWARE = [ "coulobre.hosting.sign_in.PrivilegedFactorMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", + "coulobre.hosting.panel_roles.PanelRoleMiddleware", "coulobre.hosting.impersonation.CustomerImpersonationMiddleware", ] -- 2.43.0 From 2d2cd1837e6b08b80dfc83f948407988fe24cabc Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 20:36:59 +0100 Subject: [PATCH 2/3] Keep delegated staff and service tickets within assigned roles --- src/coulobre/hosting/panel_roles.py | 4 +--- src/coulobre/hosting/signon.py | 5 +++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/coulobre/hosting/panel_roles.py b/src/coulobre/hosting/panel_roles.py index aa811cc..04aaff8 100644 --- a/src/coulobre/hosting/panel_roles.py +++ b/src/coulobre/hosting/panel_roles.py @@ -31,9 +31,7 @@ def assigned_roles(user): if not user.is_authenticated or not user.is_active: return {} roles = {} - if user.is_superuser or ( - user.is_staff and user.has_perm("hosting.view_hostingaccount") - ): + if user.is_superuser: roles[PanelRole.ADMIN] = user.pk customer = getattr(user, "hosting_customer", None) if customer is not None: diff --git a/src/coulobre/hosting/signon.py b/src/coulobre/hosting/signon.py index e395411..27d473b 100644 --- a/src/coulobre/hosting/signon.py +++ b/src/coulobre/hosting/signon.py @@ -20,8 +20,9 @@ def issue_signon_grant(model, actor, **selection): now = timezone.now() model.objects.filter(expires_at__lte=now).delete() token = secrets.token_urlsafe(32) - role = getattr(actor, "panel_role", None) - scope = [role, assigned_roles(actor).get(role)] if role else [] + roles = assigned_roles(actor) + role = getattr(actor, "panel_role", None) or next(iter(roles), None) + scope = [role, roles.get(role)] if role else [] model.objects.create( token_digest=token_digest(token), actor=actor, -- 2.43.0 From 389bc075414cd44fd7ad7dc08e82db52d9159fdb Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Mon, 23 Nov 2026 20:36:59 +0100 Subject: [PATCH 3/3] Manage configured hosting capabilities from the panel --- docs/deployment.md | 33 +++ src/coulobre/hosting/account_backup_forms.py | 7 +- src/coulobre/hosting/account_setup.py | 5 +- .../hosting/independent_website_views.py | 8 +- src/coulobre/hosting/independent_websites.py | 3 +- src/coulobre/hosting/installation_features.py | 193 ++++++++++++++++++ src/coulobre/hosting/installation_views.py | 186 +++++++++++++---- src/coulobre/hosting/mail_dns_views.py | 8 +- src/coulobre/hosting/mail_queue_views.py | 4 +- .../migrations/0059_panel_feature_policy.py | 28 +++ src/coulobre/hosting/models.py | 5 + src/coulobre/hosting/phpmyadmin.py | 3 +- src/coulobre/hosting/roundcube.py | 3 +- .../templates/hosting/account_backups.html | 2 +- .../hosting/feature_configuration.html | 27 +++ .../templates/hosting/installation.html | 17 +- .../hosting/test_feature_configuration.py | 140 +++++++++++++ src/coulobre/hosting/test_service_health.py | 16 +- src/coulobre/hosting/urls.py | 7 +- src/coulobre/hosting/views.py | 184 +++++++++++------ src/coulobre/hosting/website_file_views.py | 6 +- src/coulobre/hosting/website_job_views.py | 6 +- src/coulobre/settings.py | 1 + 23 files changed, 751 insertions(+), 141 deletions(-) create mode 100644 src/coulobre/hosting/installation_features.py create mode 100644 src/coulobre/hosting/migrations/0059_panel_feature_policy.py create mode 100644 src/coulobre/hosting/templates/hosting/feature_configuration.html create mode 100644 src/coulobre/hosting/test_feature_configuration.py diff --git a/docs/deployment.md b/docs/deployment.md index 4488a8e..a5c7238 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -496,6 +496,20 @@ connected. Follow their logs with `journalctl`. 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 +to existing login** and enter the username. Customer roles use their own +assigned hosting accounts. Customer managers use their own hosting account +assignments and hosting plan policy. New manager assignments use the default +customer 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. +Returning to the administrator role requires a verified second factor. If the +active role assignment is revoked, the session asks the user to sign in again. + ## Select a panel theme The panel follows the browser's light or dark preference on the first visit. @@ -2657,6 +2671,25 @@ Keep the managed data directories on their service filesystems to allow an atomic move into the archive directory. Existing backup archives remain available to operators with backup access. +## Configure installed features in the panel + +Open **About Coulobre → Configure features** as a superuser with a verified +second factor. The page shows the installation prerequisites and distinguishes +local mail and DNS services from linked receivers. Use **Configure DNS +defaults** to edit the zone template for new hosting accounts. + +The switches control which installed capabilities the panel offers for new +actions. Existing managed sites, mailbox delivery, published DNS records, +schedules and queued provisioning continue running. Backup archives remain +accessible when new backup requests are paused. Pausing an application sign-in +also prevents redemption of pending tickets for that application. + +Configure service packages, linked receiver identities, bridge keys and +backup credentials on the host using their deployment procedures. Enabling +a paused feature checks its available service socket and, for linked mail or +DNS, the receiver's readiness and version. A failed prerequisite check leaves +the saved choices intact. Changes are recorded in the administrator audit log. + ## Monitor local and remote services The panel's **Service health** page shows the latest observation and timestamp diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index 5e8ad10..362a929 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -11,6 +11,7 @@ from coulobre.account_restore_request import ( ) from coulobre.database_node import DatabaseSpec +from .installation_features import panel_feature_allowed from .models import AccountBackupSchedule SCHEDULE_FIELDS = ( @@ -49,7 +50,11 @@ class AccountBackupScheduleForm(forms.Form): self.allow_mail = allow_mail if not allow_mail and not self.initial.get("include_mailboxes"): del self.fields["include_mailboxes"] - destinations = settings.OFFSITE_BACKUP_DESTINATIONS + destinations = ( + settings.OFFSITE_BACKUP_DESTINATIONS + if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS") + else {} + ) current = self.initial.get("offsite_destination") if destinations or current: choices = [("", "Local archive only"), *destinations.items()] diff --git a/src/coulobre/hosting/account_setup.py b/src/coulobre/hosting/account_setup.py index f53f143..a01f327 100644 --- a/src/coulobre/hosting/account_setup.py +++ b/src/coulobre/hosting/account_setup.py @@ -11,6 +11,7 @@ from coulobre.web_node import WebSite from .dns_defaults import zone_defaults from .dns_forms import normalize_record_rows from .dns_publication import queue_zone_snapshot +from .installation_features import panel_feature_allowed from .mail_dns_setup import mail_dns_proposal from .models import ( HostingDnsZone, @@ -70,8 +71,8 @@ def setup_new_account(account, options): ) if managed_dns: existing_managed_mail = ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and account.mail_domains.filter(domain=domain).exists() ) create_default_dns_zone( diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py index c77d68c..d5e68d6 100644 --- a/src/coulobre/hosting/independent_website_views.py +++ b/src/coulobre/hosting/independent_website_views.py @@ -1,5 +1,4 @@ from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.db import IntegrityError @@ -20,6 +19,7 @@ from .independent_websites import ( create_website, queue_website_operation, ) +from .installation_features import panel_feature_allowed from .models import HostingAccount, IndependentWebsite, WebsiteDomain @@ -79,7 +79,7 @@ class IndependentWebsiteEditor( template_name = "hosting/independent_website_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -130,7 +130,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor): operation = Operation(self.kwargs["operation"]) except ValueError: raise Http404 from None - if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS: + if operation == Operation.HTTPS and not panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ): raise Http404 return operation diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py index 094b798..90d4691 100644 --- a/src/coulobre/hosting/independent_websites.py +++ b/src/coulobre/hosting/independent_websites.py @@ -9,6 +9,7 @@ from coulobre.php_runtime import validate_php_version from coulobre.service_access import ServiceAccessRequest from .access import is_tenant, manages_account +from .installation_features import panel_feature_allowed from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob from .node_client import ( activate_local_site, @@ -54,7 +55,7 @@ def website_actions(website): if website.suspended: return (Operation.RESUME, Operation.RETIRE) actions = (Operation.PHP, Operation.SUSPEND) - if settings.LOCAL_WEB_HTTPS and not website.https_enabled: + if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled: actions += (Operation.HTTPS,) return actions diff --git a/src/coulobre/hosting/installation_features.py b/src/coulobre/hosting/installation_features.py new file mode 100644 index 0000000..bf499a8 --- /dev/null +++ b/src/coulobre/hosting/installation_features.py @@ -0,0 +1,193 @@ +from contextvars import ContextVar +from dataclasses import dataclass +from pathlib import Path + +from django.conf import settings +from django.utils.functional import cached_property + +from coulobre.linked_updates import UNIT_DIR + +from .dns_defaults import zone_defaults +from .models import PanelFeaturePolicy + + +@dataclass(frozen=True) +class Feature: + setting: str + label: str + prerequisite: str + socket: str = "" + role: str = "" + + @property + def configured(self): + if self.setting == "DEFAULT_DNS_ZONES": + defaults = zone_defaults() + return bool( + settings.LOCAL_DNS_PUBLISHING + and defaults.nameservers + and defaults.addresses + ) + if self.setting == "PHPMYADMIN_URL": + return bool( + settings.PHPMYADMIN_URL and settings.LOCAL_DATABASE_CREDENTIALS + ) + if self.setting == "ROUNDCUBE_URL": + return bool( + settings.ROUNDCUBE_URL + and ( + settings.LOCAL_MAILBOX_CREDENTIALS + or settings.REMOTE_MAILBOX_CREDENTIALS + ) + ) + return bool(getattr(settings, self.setting)) + + @property + def linked(self): + return ( + bool(self.role) + and ( + UNIT_DIR / f"coulobre-{self.role}-apply@.service.d/remote.conf" + ).is_file() + ) + + @property + def socket_ready(self): + if self.setting == "ROUNDCUBE_URL": + socket = ( + "coulobre-mail-credentials" + if settings.REMOTE_MAILBOX_CREDENTIALS + else "coulobre-service-credentials" + ) + return Path(f"/run/{socket}.sock").is_socket() + return not self.socket or Path(f"/run/{self.socket}.sock").is_socket() + + +FEATURES = ( + Feature( + "LOCAL_WEB_ACTIVATION", + "Website provisioning", + "Apache and PHP provisioning", + "coulobre-web-apply", + ), + Feature( + "LOCAL_WEB_HTTPS", + "Managed website certificates", + "Website certificate provisioning", + "coulobre-https-apply", + ), + Feature( + "WEB_FILE_MANAGER", + "Website file manager", + "Website file service", + "coulobre-website-files", + ), + Feature( + "WEBSITE_JOBS", + "Website scheduled tasks", + "Website task service", + "coulobre-website-jobs", + ), + Feature( + "LOCAL_DNS_PUBLISHING", + "DNS publishing", + "Local BIND9 or a linked DNS receiver", + "coulobre-dns-apply", + "dns", + ), + Feature( + "DEFAULT_DNS_ZONES", + "Default managed DNS zones for new accounts", + "DNS publishing, nameservers and hosting IP addresses", + ), + Feature( + "LOCAL_MAILBOX_PROVISIONING", + "Mailbox provisioning", + "Local mail services or a linked mail receiver", + "coulobre-mail-apply", + "mail", + ), + Feature( + "MANAGE_MAIL_DNS", + "Managed mail DNS records", + "Mail exchanger and sending IP addresses", + ), + Feature( + "LOCAL_DATABASE_PROVISIONING", + "Database provisioning", + "MariaDB provisioning", + "coulobre-database-apply", + ), + Feature( + "LOCAL_ACCOUNT_BACKUPS", + "Local account backups", + "Local backup service", + "coulobre-account-backup", + ), + Feature( + "OFFSITE_BACKUP_DESTINATIONS", + "Off-site backup destinations", + "A configured destination and the transfer service", + "coulobre-account-offsite", + ), + Feature( + "PHPMYADMIN_URL", + "phpMyAdmin sign-in", + "phpMyAdmin bridge and MariaDB credential service", + "coulobre-service-credentials", + ), + Feature( + "ROUNDCUBE_URL", + "Roundcube sign-in", + "Roundcube bridge and mailbox credential service", + ), +) + + +class FeaturePolicy: + @cached_property + def saved(self): + return ( + PanelFeaturePolicy.objects.filter(pk=1).first() + or PanelFeaturePolicy() + ) + + @cached_property + def disabled(self): + return frozenset(self.saved.disabled) + + +current_policy = ContextVar("current_feature_policy", default=None) + + +def panel_feature_allowed(setting): + if not getattr(settings, setting): + return False + return not panel_feature_paused(setting) + + +def panel_feature_paused(setting): + policy = current_policy.get() or FeaturePolicy() + return setting in policy.disabled + + +def default_dns_zones_allowed(defaults): + if not defaults.nameservers or not defaults.addresses: + return False + policy = current_policy.get() or FeaturePolicy() + return ( + panel_feature_allowed("LOCAL_DNS_PUBLISHING") + and "DEFAULT_DNS_ZONES" not in policy.disabled + ) + + +class FeaturePolicyMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + token = current_policy.set(FeaturePolicy()) + try: + return self.get_response(request) + finally: + current_policy.reset(token) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index 24544c1..9e73056 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -1,13 +1,23 @@ from importlib.metadata import PackageNotFoundError, version -from django.conf import settings -from django.contrib.auth.mixins import PermissionRequiredMixin +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.db import transaction +from django.db.models import F +from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache -from django.views.generic import TemplateView +from django.views.generic import FormView, TemplateView from .access import OperatorOnlyMixin -from .dns_defaults import zone_defaults +from .installation_features import FEATURES, FeaturePolicy +from .models import PanelFeaturePolicy +from .update_views import inspect_linked_nodes @method_decorator(never_cache, name="dispatch") @@ -22,41 +32,137 @@ class InstallationView( installed_version = version("coulobre-panel") except PackageNotFoundError: installed_version = "Unavailable" - - dns_defaults = zone_defaults() - features = ( - ("Local website provisioning", settings.LOCAL_WEB_ACTIVATION), - ("Managed website certificates", settings.LOCAL_WEB_HTTPS), - ("Website file manager", settings.WEB_FILE_MANAGER), - ("Website scheduled tasks", settings.WEBSITE_JOBS), - ("Local DNS publishing", settings.LOCAL_DNS_PUBLISHING), - ( - "Default managed DNS zones for new accounts", - settings.LOCAL_DNS_PUBLISHING - and dns_defaults.nameservers - and dns_defaults.addresses, - ), - ( - "Local mailbox provisioning", - settings.LOCAL_MAILBOX_PROVISIONING, - ), - ("Managed mail DNS records", settings.MANAGE_MAIL_DNS), - ( - "Local database provisioning", - settings.LOCAL_DATABASE_PROVISIONING, - ), - ("Local account backups", settings.LOCAL_ACCOUNT_BACKUPS), - ( - "Off-site backup destinations", - settings.OFFSITE_BACKUP_DESTINATIONS, - ), - ("phpMyAdmin sign-in", settings.PHPMYADMIN_URL), - ("Roundcube sign-in", settings.ROUNDCUBE_URL), - ) + policy = FeaturePolicy() + features = [] + for feature in FEATURES: + configured = feature.configured + enabled = ( + configured + and feature.setting not in policy.disabled + and ( + feature.setting != "DEFAULT_DNS_ZONES" + or "LOCAL_DNS_PUBLISHING" not in policy.disabled + ) + ) + features.append((feature, configured, enabled)) return super().get_context_data( - installed_version=installed_version, - features=[ - (name, bool(configured)) for name, configured in features - ], - **kwargs, + installed_version=installed_version, features=features, **kwargs + ) + + +class FeatureConfigurationForm(forms.Form): + revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput) + + def __init__(self, *args, policy, **kwargs): + super().__init__(*args, **kwargs) + self.initial["revision"] = policy.saved.revision + self.configured_features = [ + feature for feature in FEATURES if feature.configured + ] + for feature in self.configured_features: + self.fields[feature.setting] = forms.BooleanField( + required=False, + label=feature.label, + help_text=feature.prerequisite, + initial=feature.setting not in policy.disabled, + ) + + def changed_features(self): + return [ + feature + for feature in self.configured_features + if feature.setting in self.changed_data + ] + + +def check_features(form, changed): + new_enabled = [ + feature for feature in changed if form.cleaned_data[feature.setting] + ] + nodes = {} + if any(feature.linked for feature in new_enabled): + topology = inspect_linked_nodes() + nodes = {node["role"]: node for node in topology.get("nodes", [])} + for feature in new_enabled: + if not feature.socket_ready: + form.add_error( + feature.setting, + "Start the configured service before enabling this feature.", + ) + elif feature.linked: + report = nodes.get(feature.role, {}) + if report.get("state") != "configured" or report.get( + "release" + ) != version("coulobre-panel"): + form.add_error( + feature.setting, + "The linked receiver must be ready and on the same " + "release.", + ) + if ( + feature.setting == "DEFAULT_DNS_ZONES" + and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING") + ): + form.add_error(feature.setting, "Enable DNS publishing first.") + + +@method_decorator(never_cache, name="dispatch") +class FeatureConfigurationView(UserPassesTestMixin, FormView): + form_class = FeatureConfigurationForm + template_name = "hosting/feature_configuration.html" + success_url = reverse_lazy("panel:installation") + + def test_func(self): + return ( + self.request.user.is_superuser and self.request.user.is_verified() + ) + + def get_form_kwargs(self): + return {**super().get_form_kwargs(), "policy": FeaturePolicy()} + + def form_valid(self, form): + revision = form.cleaned_data["revision"] + policy = FeaturePolicy() + if revision != policy.saved.revision: + return self.stale_form(form) + changed = form.changed_features() + if not changed: + return super().form_valid(form) + check_features(form, changed) + if form.errors: + return self.form_invalid(form) + disabled = set(policy.disabled) + for feature in changed: + if form.cleaned_data[feature.setting]: + disabled.discard(feature.setting) + else: + disabled.add(feature.setting) + with transaction.atomic(): + saved, _ = PanelFeaturePolicy.objects.get_or_create(pk=1) + updated = PanelFeaturePolicy.objects.filter( + pk=1, revision=revision + ).update(disabled=sorted(disabled), revision=F("revision") + 1) + if not updated: + return self.stale_form(form) + LogEntry.objects.log_actions( + self.request.user.pk, + [saved], + CHANGE, + [ + { + "changed": { + "fields": [feature.label for feature in changed] + } + } + ], + ) + messages.success(self.request, "Feature configuration saved.") + return super().form_valid(form) + + def stale_form(self, form): + form.add_error( + None, "The configuration changed. Reopen this page and try again." + ) + return self.render_to_response( + self.get_context_data(form=form), status=409 ) diff --git a/src/coulobre/hosting/mail_dns_views.py b/src/coulobre/hosting/mail_dns_views.py index d9a715c..5cc74f9 100644 --- a/src/coulobre/hosting/mail_dns_views.py +++ b/src/coulobre/hosting/mail_dns_views.py @@ -22,6 +22,7 @@ from coulobre.mail_dns import ( ) from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant +from .installation_features import panel_feature_allowed from .mail_dns_setup import ( closest_zone, mail_dns_proposal, @@ -156,8 +157,8 @@ class MailDnsCheckView( report=report, mail_domain=self.object, can_refresh=( - settings.MANAGE_MAIL_DNS - and settings.LOCAL_MAILBOX_PROVISIONING + panel_feature_allowed("MANAGE_MAIL_DNS") + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") and not is_tenant(self.request.user) and self.request.user.has_perms(PROVISION_MAILBOX) and self.object.mailboxes.filter( @@ -261,7 +262,8 @@ class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View): def post(self, request, pk): if not ( - settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING + panel_feature_allowed("MANAGE_MAIL_DNS") + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") ): raise Http404 domain = get_object_or_404(HostingMailDomain, pk=pk) diff --git a/src/coulobre/hosting/mail_queue_views.py b/src/coulobre/hosting/mail_queue_views.py index 778d61b..c857c67 100644 --- a/src/coulobre/hosting/mail_queue_views.py +++ b/src/coulobre/hosting/mail_queue_views.py @@ -1,6 +1,5 @@ from datetime import timedelta -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.db import transaction from django.http import Http404 @@ -11,6 +10,7 @@ from django.views.decorators.cache import never_cache from django.views.generic import TemplateView from .access import OperatorOnlyMixin +from .installation_features import panel_feature_allowed from .models import HostingMailDomain from .tasks import refresh_mail_queue @@ -24,7 +24,7 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView): template_name = "hosting/mail_queue.html" def get_domain(self, *, locked=False): - if not settings.LOCAL_MAILBOX_PROVISIONING: + if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"): raise Http404 domains = HostingMailDomain.objects.filter( account__retired_at__isnull=True diff --git a/src/coulobre/hosting/migrations/0059_panel_feature_policy.py b/src/coulobre/hosting/migrations/0059_panel_feature_policy.py new file mode 100644 index 0000000..feec519 --- /dev/null +++ b/src/coulobre/hosting/migrations/0059_panel_feature_policy.py @@ -0,0 +1,28 @@ +# Generated by Django 5.2.19 on 2026-11-23 19:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0058_scope_service_signon_grants"), + ] + + operations = [ + migrations.CreateModel( + name="PanelFeaturePolicy", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("disabled", models.JSONField(blank=True, default=list)), + ("revision", models.PositiveBigIntegerField(default=0)), + ], + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index e7ac10f..a2c0fc9 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -608,6 +608,11 @@ class DirectAdminImport(models.Model): fingerprint = models.CharField(max_length=64, unique=True) +class PanelFeaturePolicy(models.Model): + disabled = models.JSONField(default=list, blank=True) + revision = models.PositiveBigIntegerField(default=0) + + class DnsZoneDefaults(models.Model): nameservers = models.JSONField(default=list, blank=True) addresses = models.JSONField(default=list, blank=True) diff --git a/src/coulobre/hosting/phpmyadmin.py b/src/coulobre/hosting/phpmyadmin.py index 9d7e356..5ce089c 100644 --- a/src/coulobre/hosting/phpmyadmin.py +++ b/src/coulobre/hosting/phpmyadmin.py @@ -12,6 +12,7 @@ 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 .service_credentials import ( CredentialKind, @@ -30,7 +31,7 @@ from .signon import ( def phpmyadmin_available(request): return bool( - settings.PHPMYADMIN_URL + panel_feature_allowed("PHPMYADMIN_URL") and settings.PHPMYADMIN_BRIDGE_KEY and enabled_credential_access(request, CredentialKind.DATABASE) ) diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py index cbc5a61..6006ec0 100644 --- a/src/coulobre/hosting/roundcube.py +++ b/src/coulobre/hosting/roundcube.py @@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST from .access import customer_for_user from .credential_views import MailboxCredentialView +from .installation_features import panel_feature_allowed from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess from .service_credentials import ( CredentialKind, @@ -30,7 +31,7 @@ from .signon import ( def roundcube_available(request): return bool( - settings.ROUNDCUBE_URL + panel_feature_allowed("ROUNDCUBE_URL") and settings.ROUNDCUBE_BRIDGE_KEY and enabled_credential_access(request, CredentialKind.MAILBOX) ) diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index 1ac1d91..ccbc916 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -16,7 +16,7 @@

{% endif %} - {% if not account_backup_pending %} + {% if can_request_account_backup and not account_backup_pending %} {% csrf_token %} {% if account_backup_allow_mail %} diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html new file mode 100644 index 0000000..429dc89 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -0,0 +1,27 @@ +{% extends "hosting/base.html" %} +{% block title %}Configure features · Coulobre Panel{% endblock %} +{% block content %} + ← About Coulobre +

Configure features

+
+

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

+ + {% csrf_token %} + {{ form.non_field_errors }} + {{ form.revision }} + {% for field in form.visible_fields %} +
+ + {{ field.errors }} +

{{ field.help_text }}

+
+ {% empty %} +

No installed features can be configured here yet.

+ {% endfor %} +
+ {% if form.visible_fields %}{% endif %} + Cancel +
+ +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/installation.html b/src/coulobre/hosting/templates/hosting/installation.html index 866dab3..af16dc4 100644 --- a/src/coulobre/hosting/templates/hosting/installation.html +++ b/src/coulobre/hosting/templates/hosting/installation.html @@ -4,6 +4,7 @@ {% block content %}

About Coulobre

+ {% for message in messages %}

{{ message }}

{% endfor %}

Installation

@@ -17,22 +18,28 @@

Feature configuration

See Service health for the latest local and remote checks.

+ {% if request.user.is_superuser and request.user.is_verified %} + Configure features + {% endif %}
- + - {% for name, enabled in features %} + {% for feature, configured, enabled in features %} - + + {% endfor %} diff --git a/src/coulobre/hosting/test_feature_configuration.py b/src/coulobre/hosting/test_feature_configuration.py new file mode 100644 index 0000000..b4da145 --- /dev/null +++ b/src/coulobre/hosting/test_feature_configuration.py @@ -0,0 +1,140 @@ +from unittest.mock import PropertyMock, patch + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy + + +@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DNS_PUBLISHING=True) +class FeatureConfigurationTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.device = TOTPDevice.objects.create(user=cls.operator, name="Panel") + cls.account = HostingAccount.objects.create( + name="Existing account", primary_domain="site.example" + ) + + def sign_in(self, *, verified=True): + self.client.force_login(self.operator) + if verified: + session = self.client.session + session["otp_device_id"] = self.device.persistent_id + session.save() + + def save(self, **data): + return self.client.post(reverse("panel:feature_configuration"), data) + + def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible( + self, + ): + self.sign_in() + result = self.save(revision=0, LOCAL_DNS_PUBLISHING="on") + self.assertRedirects(result, reverse("panel:installation")) + self.assertEqual( + PanelFeaturePolicy.objects.get().disabled, + ["LOCAL_ACCOUNT_BACKUPS"], + ) + self.assertEqual( + self.client.post( + reverse("panel:account_backup_create", args=[self.account.pk]) + ).status_code, + 404, + ) + self.assertFalse(AccountBackupJob.objects.exists()) + self.assertEqual( + self.client.get( + reverse( + "panel:account_backup_archives", args=[self.account.pk] + ) + ).status_code, + 200, + ) + + def test_failed_preflight_preserves_all_choices_and_revision(self): + self.sign_in() + policy = PanelFeaturePolicy.objects.create( + pk=1, disabled=["LOCAL_DNS_PUBLISHING"], revision=2 + ) + with patch( + "coulobre.hosting.installation_features.Feature.socket_ready", + new_callable=PropertyMock, + return_value=False, + ): + response = self.save(revision=2, LOCAL_DNS_PUBLISHING="on") + self.assertContains( + response, "Start the configured service before enabling" + ) + policy.refresh_from_db() + self.assertEqual(policy.disabled, ["LOCAL_DNS_PUBLISHING"]) + self.assertEqual(policy.revision, 2) + self.assertEqual(self.save(revision=1).status_code, 409) + + def test_linked_receiver_must_match_panel_release_before_enabling(self): + self.sign_in() + policy = PanelFeaturePolicy.objects.create( + pk=1, disabled=["LOCAL_DNS_PUBLISHING"] + ) + module = "coulobre.hosting.installation_features.Feature" + update = "coulobre.hosting.installation_views" + with ( + patch( + f"{module}.linked", + new_callable=PropertyMock, + return_value=True, + ), + patch( + f"{module}.socket_ready", + new_callable=PropertyMock, + return_value=True, + ), + patch(f"{update}.version", return_value="1.0.0"), + patch( + f"{update}.inspect_linked_nodes", + return_value={ + "nodes": [ + { + "role": "dns", + "release": "0.9.0", + "state": "configured", + } + ] + }, + ) as linked, + ): + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + ) + self.assertContains(response, "linked receiver must be ready") + linked.return_value["nodes"][0]["release"] = "1.0.0" + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + ) + self.assertRedirects(response, reverse("panel:installation")) + policy.refresh_from_db() + self.assertEqual(policy.disabled, []) + self.assertEqual(policy.revision, 1) + + @override_settings(LOCAL_WEB_HTTPS=False) + def test_requires_verified_admin_and_never_enables_unconfigured_service( + self, + ): + self.sign_in(verified=False) + response = self.save(revision=0) + self.assertEqual(response.status_code, 403) + self.sign_in() + response = self.save( + revision=0, + LOCAL_DNS_PUBLISHING="on", + LOCAL_ACCOUNT_BACKUPS="on", + LOCAL_WEB_HTTPS="on", + ) + self.assertRedirects(response, reverse("panel:installation")) + self.assertFalse(PanelFeaturePolicy.objects.exists()) diff --git a/src/coulobre/hosting/test_service_health.py b/src/coulobre/hosting/test_service_health.py index 4a6e300..d09117f 100644 --- a/src/coulobre/hosting/test_service_health.py +++ b/src/coulobre/hosting/test_service_health.py @@ -171,6 +171,7 @@ class ServiceHealthPanelTests(TestCase): HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",), ROUNDCUBE_URL="https://webmail.example.net", ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key", + LOCAL_MAILBOX_CREDENTIALS=True, ) def test_installation_reports_configuration_to_operators(self): url = reverse("panel:installation") @@ -190,7 +191,10 @@ class ServiceHealthPanelTests(TestCase): self.assertContains(response, "1.2.3") self.assertContains(response, "Apache License 2.0") self.assertContains(response, reverse("panel:service_health")) - features = dict(response.context["features"]) + features = { + feature.label: enabled + for feature, _, enabled in response.context["features"] + } self.assertTrue(features["Default managed DNS zones for new accounts"]) self.assertTrue(features["Roundcube sign-in"]) self.assertNotContains(response, "test-only-bridge-key") @@ -207,11 +211,11 @@ class ServiceHealthPanelTests(TestCase): ) self.client.force_login(self.admin) response = self.client.get(reverse("panel:installation")) - self.assertTrue( - dict(response.context["features"])[ - "Default managed DNS zones for new accounts" - ] - ) + features = { + feature.label: enabled + for feature, _, enabled in response.context["features"] + } + self.assertTrue(features["Default managed DNS zones for new accounts"]) self.assertContains(response, "Configure DNS defaults") def test_view_marks_missing_and_old_observations_distinctly(self): diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index ede017a..c151a2f 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -22,7 +22,7 @@ from .independent_website_views import ( IndependentWebsiteManifest, IndependentWebsiteOperation, ) -from .installation_views import InstallationView +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 @@ -89,6 +89,11 @@ urlpatterns = [ "service-health/", ServiceHealthView.as_view(), name="service_health" ), path("about/", InstallationView.as_view(), name="installation"), + path( + "about/features/", + FeatureConfigurationView.as_view(), + name="feature_configuration", + ), 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 6607f20..999f89c 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -93,6 +93,11 @@ from .independent_websites import ( website_actions, website_limit, ) +from .installation_features import ( + default_dns_zones_allowed, + panel_feature_allowed, + panel_feature_paused, +) from .invitations import InviteLoginForm, queue_invitation from .mail_policy_views import mail_policy_enabled from .models import ( @@ -249,7 +254,7 @@ def missing_account_setup(account, actor): defaults = zone_defaults() options = [] if ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and actor.has_perms(ACTIVATE_WEB) and not account.webprovisioningplan_set.filter( primary_domain=domain, activation__isnull=False @@ -257,16 +262,14 @@ def missing_account_setup(account, actor): ): options.append(("setup_website", "Set up the primary website")) if ( - settings.LOCAL_DNS_PUBLISHING - and defaults.nameservers - and defaults.addresses + default_dns_zones_allowed(defaults) and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) and not HostingDnsZone.objects.filter(domain=domain).exists() ): options.append(("setup_dns", "Publish a Coulobre DNS zone")) if ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and actor.has_perms(PROVISION_MAILBOX) and not account.mail_domains.filter(domain=domain).exists() ): @@ -313,7 +316,7 @@ class ExistingAccountSetup( and bool(form["setup_email"].value()) ) or ( - settings.MANAGE_MAIL_DNS + panel_feature_allowed("MANAGE_MAIL_DNS") and self.account.mail_domains.filter( domain=self.account.primary_domain ).exists() @@ -481,19 +484,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): actor = self.request.user reseller = reseller_for_user(actor) is not None defaults = zone_defaults() - web = settings.LOCAL_WEB_ACTIVATION and ( + web = panel_feature_allowed("LOCAL_WEB_ACTIVATION") and ( reseller or actor.has_perms(ACTIVATE_WEB) ) - dns = ( - settings.LOCAL_DNS_PUBLISHING - and defaults.nameservers - and defaults.addresses - and ( - reseller - or actor.has_perms( - (*PUBLISH_DNS, "hosting.add_hostingdnszone") - ) - ) + dns = default_dns_zones_allowed(defaults) and ( + reseller + or actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) ) choices = { "setup_website": (web, "Set up the primary website"), @@ -505,8 +501,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): "setup_www": (web or dns, "Include the www hostname"), "setup_wildcard": (dns, "Include a wildcard (*) DNS record"), "setup_email": ( - settings.LOCAL_MAILBOX_PROVISIONING - and settings.MANAGE_MAIL_DNS + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") + and panel_feature_allowed("MANAGE_MAIL_DNS") and (reseller or actor.has_perms(PROVISION_MAILBOX)), "Set up email DNS for this domain", ), @@ -620,7 +616,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["show_mail_queue"] = ( not tenant - and settings.LOCAL_MAILBOX_PROVISIONING + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") and user.has_perm("hosting.view_hostingmaildomain") ) manage_resources = reseller is not None and reseller.manage_resources @@ -645,10 +641,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["primary_file_access"] = manage_files and site_is_active( self.object ) + website_provisioning = panel_feature_allowed("LOCAL_WEB_ACTIVATION") if settings.LOCAL_WEB_ACTIVATION or manage_files: websites = list(account_websites(self.object)) can_manage = ( - settings.LOCAL_WEB_ACTIVATION + website_provisioning and not self.object.services_suspended and (tenant or user.has_perm(CHANGE_ACCOUNTS)) and getattr(self.request, "impersonation", None) is None @@ -687,7 +684,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ): context["website_storage"] = storage context["can_measure_site_storage"] = ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and not tenant and user.has_perms(MEASURE_SITE_STORAGE) ) @@ -698,7 +695,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): if quota is not None and quota.domain == self.object.primary_domain: context["website_limit"] = quota context["can_change_site_storage_limit"] = ( - settings.LOCAL_WEB_ACTIVATION + panel_feature_allowed("LOCAL_WEB_ACTIVATION") and not tenant and user.has_perms(CHANGE_SITE_STORAGE_LIMIT) ) @@ -721,7 +718,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["website_php_job"] = php_job context["can_change_php_settings"] = ( - not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS) + website_provisioning + and not tenant + and user.has_perms(CHANGE_SITE_PHP_SETTINGS) ) version_job = getattr(self.object, "php_version_job", None) if ( @@ -734,7 +733,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) context["website_php_version_job"] = version_job context["can_change_php_version"] = ( - can_change_php_version(self.request) + website_provisioning + and can_change_php_version(self.request) and not self.object.services_suspended and ( version_job is None @@ -746,13 +746,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): .select_related("reservation") .order_by("reservation__domain") ) - if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES): + if ( + website_provisioning + and not tenant + and user.has_perms(MANAGE_WEBSITE_ALIASES) + ): context["manage_website_aliases"] = True context["can_add_website_alias"] = site_active - context["can_enable_alias_https"] = ( - settings.LOCAL_WEB_HTTPS - and user.has_perms(ENABLE_WEB_HTTPS) - ) + context["can_enable_alias_https"] = panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ) and user.has_perms(ENABLE_WEB_HTTPS) context["export_backup_manifest"] = not tenant and user.has_perms( EXPORT_BACKUP_MANIFEST ) @@ -766,7 +769,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ): can_view_mailboxes = user.has_perm(VIEW_MAILBOXES) context["show_account_backups"] = True - context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) + context["can_request_account_backup"] = panel_feature_allowed( + "LOCAL_ACCOUNT_BACKUPS" + ) + context["can_retry_offsite"] = panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ) and user.has_perms(RETRY_OFFSITE_BACKUP) context["manage_backup_retention"] = ( settings.LOCAL_BACKUP_RETENTION and user.has_perms(MANAGE_BACKUP_RETENTION) @@ -799,9 +807,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): or can_view_mailboxes ): context["account_backup_schedule"] = schedule - context["edit_account_backup_schedule"] = user.has_perms( - MANAGE_BACKUP_SCHEDULE - ) + context["edit_account_backup_schedule"] = ( + schedule is not None + or context["can_request_account_backup"] + ) and user.has_perms(MANAGE_BACKUP_SCHEDULE) context["manage_sftp"] = ( settings.LOCAL_WEB_SFTP and can_manage_sftp(user) @@ -831,7 +840,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["automatic_database_provisioning"] = ( automatic_resource_provisioning( user, - settings.LOCAL_DATABASE_PROVISIONING, + panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"), PROVISION_DATABASE, ) ) @@ -840,8 +849,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): not tenant and user.has_perms(PROVISION_DATABASE) ): context["manage_database_provisioning"] = True - context["local_database_enabled"] = ( - settings.LOCAL_DATABASE_PROVISIONING + context["local_database_enabled"] = panel_feature_allowed( + "LOCAL_DATABASE_PROVISIONING" ) context["databases"] = databases if tenant or user.has_perm(VIEW_DNS_ZONES): @@ -851,15 +860,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): "publication__manifest" ) context["tenant_dns_editing"] = True - context["tenant_dns_publishing"] = ( - settings.LOCAL_DNS_PUBLISHING + context["tenant_dns_publishing"] = panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" ) if not tenant and user.has_perms(PUBLISH_DNS): zone_list = zone_list.select_related("publication").defer( "publication__manifest" ) context["manage_dns_publishing"] = True - context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING + context["local_dns_enabled"] = panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ) zones = list(zone_list) context["dns_zones"] = zones context["dns_zone_records"] = [ @@ -876,11 +887,15 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["has_primary_zone"] = primary_zone is not None if primary_zone is None: context["dns_readiness"] = "No managed zone" - if not tenant and settings.LOCAL_DNS_PUBLISHING: + if not tenant and panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ): try: draft = default_dns_zone( self.object, - managed_mail=settings.MANAGE_MAIL_DNS + managed_mail=panel_feature_allowed( + "MANAGE_MAIL_DNS" + ) and self.object.mail_domains.filter( domain=self.object.primary_domain ).exists(), @@ -904,7 +919,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["automatic_mailbox_provisioning"] = ( automatic_resource_provisioning( user, - settings.LOCAL_MAILBOX_PROVISIONING, + panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"), PROVISION_MAILBOX, ) ) @@ -929,8 +944,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): not tenant and user.has_perms(PROVISION_MAILBOX) ): context["manage_mailbox_provisioning"] = True - context["local_mailbox_enabled"] = ( - settings.LOCAL_MAILBOX_PROVISIONING + context["local_mailbox_enabled"] = panel_feature_allowed( + "LOCAL_MAILBOX_PROVISIONING" ) context["change_mailbox_quota"] = ( not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) @@ -1002,7 +1017,7 @@ class SiteStorageLimitEdit( template_name = "hosting/site_storage_limit_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1051,7 +1066,7 @@ class SitePhpSettingsEdit( template_name = "hosting/site_php_settings_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1098,7 +1113,7 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView): template_name = "hosting/site_php_version_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1160,7 +1175,7 @@ class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView): template_name = "hosting/website_alias_form.html" def dispatch(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 return super().dispatch(request, *args, **kwargs) @@ -1214,9 +1229,9 @@ class WebsiteAliasAction(WebsiteAliasEditor): ) def can_enable_https(self): - return settings.LOCAL_WEB_HTTPS and self.request.user.has_perms( - ENABLE_WEB_HTTPS - ) + return panel_feature_allowed( + "LOCAL_WEB_HTTPS" + ) and self.request.user.has_perms(ENABLE_WEB_HTTPS) def has_permission(self): if not super().has_permission(): @@ -1259,7 +1274,7 @@ class RequestSiteStorageMeasurement( permission_required = MEASURE_SITE_STORAGE def post(self, request, pk): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 try: queue_site_storage_measurement(pk) @@ -1305,7 +1320,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = MANAGE_ACCOUNT_BACKUPS def post(self, request, pk): - if not settings.LOCAL_ACCOUNT_BACKUPS: + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): raise Http404 include_mailboxes = request.POST.get("include_mail") == "1" if include_mailboxes: @@ -1354,7 +1369,9 @@ class AccountBackupArchiveList( def get_context_data(self, **kwargs): context = super().get_context_data(account=self.account, **kwargs) user = self.request.user - context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) + context["can_retry_offsite"] = panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ) and user.has_perms(RETRY_OFFSITE_BACKUP) context["manage_backup_retention"] = ( settings.LOCAL_BACKUP_RETENTION and user.has_perms(MANAGE_BACKUP_RETENTION) @@ -1378,7 +1395,9 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): permission_required = RETRY_OFFSITE_BACKUP def post(self, request, pk, backup_pk): - if not settings.LOCAL_ACCOUNT_BACKUPS: + if not settings.LOCAL_ACCOUNT_BACKUPS or not panel_feature_allowed( + "OFFSITE_BACKUP_DESTINATIONS" + ): raise Http404 account = get_object_or_404(HostingAccount, pk=pk) backup = get_object_or_404( @@ -1689,6 +1708,8 @@ class EditAccountBackupSchedule( def get_initial(self): schedule = getattr(self.account, "backup_schedule", None) if schedule is None: + if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"): + raise Http404 return { "enabled": True, "frequency": AccountBackupSchedule.Frequency.DAILY, @@ -1711,6 +1732,15 @@ class EditAccountBackupSchedule( return super().get_context_data(account=self.account, **kwargs) def form_valid(self, form): + if ( + form.cleaned_data["enabled"] + and not self.get_initial()["enabled"] + and not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS") + ): + form.add_error( + "enabled", "New backup requests are paused in the panel." + ) + return self.form_invalid(form) try: save_backup_schedule( self.account.pk, @@ -1977,7 +2007,7 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def auto_provision(self): return automatic_resource_provisioning( self.request.user, - getattr(settings, self.provisioning_setting), + panel_feature_allowed(self.provisioning_setting), self.provisioning_permissions, ) @@ -2070,7 +2100,7 @@ class ResourceProvisioningRequest(PermissionRequiredMixin, View): ) def post(self, request, pk): - if not getattr(settings, self.enabled_setting): + if not panel_feature_allowed(self.enabled_setting): raise Http404 queryset = self.queryset.all() if self.reseller is not None: @@ -2141,7 +2171,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): try: draft = default_dns_zone( self.account, - managed_mail=settings.MANAGE_MAIL_DNS + managed_mail=panel_feature_allowed("MANAGE_MAIL_DNS") and self.account.mail_domains.filter( domain=self.domain ).exists(), @@ -2157,9 +2187,9 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): @cached_property def publish_on_create(self): - return settings.LOCAL_DNS_PUBLISHING and self.request.user.has_perms( - PUBLISH_DNS - ) + return panel_feature_allowed( + "LOCAL_DNS_PUBLISHING" + ) and self.request.user.has_perms(PUBLISH_DNS) def get_context_data(self, **kwargs): return super().get_context_data( @@ -2167,6 +2197,13 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor): ) def form_valid(self, form): + if form.cleaned_data["manage_mail_dns"] and panel_feature_paused( + "MANAGE_MAIL_DNS" + ): + form.add_error( + "manage_mail_dns", "Managed mail DNS is paused in the panel." + ) + return self.form_invalid(form) try: with transaction.atomic(): account = lock_hosting_account( @@ -2272,6 +2309,15 @@ class DnsZoneEdit(DnsZoneEditor): def form_valid(self, form): values = form.cleaned_data + if ( + values["manage_mail_dns"] + and not self.zone.manage_mail_dns + and panel_feature_paused("MANAGE_MAIL_DNS") + ): + form.add_error( + "manage_mail_dns", "Managed mail DNS is paused in the panel." + ) + return self.form_invalid(form) serial = values["serial"] if all( getattr(self.zone, field) == value @@ -2344,7 +2390,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View): return super().has_permission() def post(self, request, pk): - if not settings.LOCAL_DNS_PUBLISHING: + if not panel_feature_allowed("LOCAL_DNS_PUBLISHING"): raise Http404 try: zone = queue_dns_publication( @@ -2569,10 +2615,12 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): return super().get_context_data( manage_activation=not is_tenant(user) and user.has_perms(ACTIVATE_WEB), - local_activation_enabled=settings.LOCAL_WEB_ACTIVATION, + local_activation_enabled=panel_feature_allowed( + "LOCAL_WEB_ACTIVATION" + ), manage_https=not is_tenant(user) and user.has_perms(ENABLE_WEB_HTTPS), - local_https_enabled=settings.LOCAL_WEB_HTTPS, + local_https_enabled=panel_feature_allowed("LOCAL_WEB_HTTPS"), **kwargs, ) @@ -2584,7 +2632,7 @@ class RequestWebActivation( permission_required = ACTIVATE_WEB def post(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_ACTIVATION: + if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"): raise Http404 plan = self.get_object() if not plan.can_export: @@ -2610,7 +2658,7 @@ class RequestWebHTTPS( permission_required = ENABLE_WEB_HTTPS def post(self, request, *args, **kwargs): - if not settings.LOCAL_WEB_HTTPS: + if not panel_feature_allowed("LOCAL_WEB_HTTPS"): raise Http404 plan = self.get_object() if not plan.can_enable_https: diff --git a/src/coulobre/hosting/website_file_views.py b/src/coulobre/hosting/website_file_views.py index 50da522..e65fc3a 100644 --- a/src/coulobre/hosting/website_file_views.py +++ b/src/coulobre/hosting/website_file_views.py @@ -1,7 +1,6 @@ from urllib.parse import urlencode from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.http import Http404, StreamingHttpResponse @@ -22,6 +21,7 @@ from coulobre.website_files import ( from .access import TenantScopeMixin, is_tenant from .independent_websites import active_websites +from .installation_features import panel_feature_allowed from .models import HostingAccount from .resource_requests import require_active_services from .sftp import site_is_active @@ -34,7 +34,7 @@ UNAVAILABLE = "The website files service is unavailable. Try again later." def can_manage_website_files(request): user = request.user return ( - settings.WEB_FILE_MANAGER + panel_feature_allowed("WEB_FILE_MANAGER") and getattr(request, "impersonation", None) is None and (is_tenant(user) or user.has_perms(MANAGE_FILES)) ) @@ -75,7 +75,7 @@ class WebsiteFilesView( permission_required = MANAGE_FILES def dispatch(self, request, *args, **kwargs): - if not settings.WEB_FILE_MANAGER: + if not panel_feature_allowed("WEB_FILE_MANAGER"): raise Http404 return super().dispatch(request, *args, **kwargs) diff --git a/src/coulobre/hosting/website_job_views.py b/src/coulobre/hosting/website_job_views.py index 1944d6b..66a8268 100644 --- a/src/coulobre/hosting/website_job_views.py +++ b/src/coulobre/hosting/website_job_views.py @@ -1,5 +1,4 @@ from django import forms -from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.exceptions import ValidationError from django.db import transaction @@ -18,6 +17,7 @@ from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command from .access import TenantScopeMixin, is_tenant from .independent_websites import check_actor +from .installation_features import panel_feature_allowed from .models import HostingAccount from .resource_requests import lock_hosting_account from .website_job_schedule import next_website_run @@ -33,7 +33,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs") def can_manage_website_jobs(request): user = request.user return ( - settings.WEBSITE_JOBS + panel_feature_allowed("WEBSITE_JOBS") and getattr(request, "impersonation", None) is None and (is_tenant(user) or user.has_perms(MANAGE_JOBS)) ) @@ -104,7 +104,7 @@ class WebsiteJobAccountView( permission_required = MANAGE_JOBS def dispatch(self, request, *args, **kwargs): - if not settings.WEBSITE_JOBS: + if not panel_feature_allowed("WEBSITE_JOBS"): raise Http404 return super().dispatch(request, *args, **kwargs) diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index bbdfe69..c38d540 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -91,6 +91,7 @@ MIDDLEWARE = [ "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "coulobre.hosting.panel_roles.PanelRoleMiddleware", + "coulobre.hosting.installation_features.FeaturePolicyMiddleware", "coulobre.hosting.impersonation.CustomerImpersonationMiddleware", ] -- 2.43.0
FeatureConfiguration
FeatureConfigurationPrerequisites
{{ name }}{{ feature.label }}
- {% if enabled %}Enabled{% else %}Disabled{% endif %} - {% if request.user.is_superuser and name == 'Default managed DNS zones for new accounts' %} + {% if enabled %}Enabled{% elif configured %}Paused in panel{% else %}Requires setup{% endif %} + {% if enabled and not feature.socket_ready %}Service socket unavailable{% endif %} + {% if configured and feature.role %}{% if feature.linked %}Linked receiver{% else %}Local{% endif %}{% endif %} + {% if request.user.is_superuser and feature.setting == 'DEFAULT_DNS_ZONES' %} Configure DNS defaults {% endif %}
{{ feature.prerequisite }}