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
+
+{% 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 %}
+
+ {% endif %}
{% endif %}
{% endif %}
- {% if not account_backup_pending %}
+ {% if can_request_account_backup and not account_backup_pending %}