From 930b692328c2863c79f18b8bfcaee7540cb4d7d9 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 23:05:37 +0100 Subject: [PATCH 1/2] Allow scoped and audited writes during customer support --- src/coulobre/hosting/admin.py | 41 +++++++ src/coulobre/hosting/impersonation.py | 112 ++++++++++++++++-- .../migrations/0041_audited_support_writes.py | 84 +++++++++++++ src/coulobre/hosting/models.py | 28 +++++ src/coulobre/hosting/sftp.py | 47 +++++--- .../hosting/templates/hosting/base.html | 6 +- .../hosting/customer_action_fields.html | 5 + .../templates/hosting/customer_list.html | 6 + .../templates/hosting/database_form.html | 4 +- .../templates/hosting/mailbox_form.html | 4 +- .../hosting/templates/hosting/sftp_keys.html | 4 +- src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 94 ++++++++++----- 13 files changed, 378 insertions(+), 62 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0041_audited_support_writes.py create mode 100644 src/coulobre/hosting/templates/hosting/customer_action_fields.html diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 6ecb636..7f1725d 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -5,6 +5,7 @@ from django.utils.timezone import now from .models import ( Customer, CustomerImpersonation, + CustomerImpersonationAction, HostingAccount, HostingPlan, Reseller, @@ -98,6 +99,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin): list_display = ( "operator_username", "customer_username", + "write_enabled", "started_at", "expires_at", "ended_at", @@ -107,6 +109,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin): fields = ( "operator_username", "customer_username", + "write_enabled", "started_at", "expires_at", "ended_at", @@ -132,6 +135,44 @@ class CustomerImpersonationAdmin(admin.ModelAdmin): return False +@admin.register(CustomerImpersonationAction) +class CustomerImpersonationActionAdmin(admin.ModelAdmin): + list_display = ( + "requested_at", + "operator_username", + "customer_username", + "hosting_account_id", + "operation", + "resource", + ) + list_select_related = ("session",) + list_filter = ("operation",) + search_fields = ( + "session__operator_username", + "session__customer_username", + "resource", + ) + fields = list_display + ("session", "details") + readonly_fields = fields + + @admin.display(description="Administrator") + def operator_username(self, obj): + return obj.session.operator_username + + @admin.display(description="Customer") + def customer_username(self, obj): + return obj.session.customer_username + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False + + def has_delete_permission(self, request, obj=None): + return False + + @admin.register(ServiceCredentialAccess) class ServiceCredentialAccessAdmin(admin.ModelAdmin): list_display = ( diff --git a/src/coulobre/hosting/impersonation.py b/src/coulobre/hosting/impersonation.py index 9c03b4b..43be719 100644 --- a/src/coulobre/hosting/impersonation.py +++ b/src/coulobre/hosting/impersonation.py @@ -1,5 +1,9 @@ +from contextlib import contextmanager from datetime import timedelta +from django.core.exceptions import PermissionDenied +from django.db import connection, transaction +from django.db.models import F from django.middleware.csrf import rotate_token from django.shortcuts import render from django.utils import timezone @@ -7,6 +11,7 @@ from django.utils.cache import add_never_cache_headers from .access import is_tenant from .models import CustomerImpersonation +from .sftp import MANAGE_SFTP_KEYS SESSION_KEY = "customer_impersonation" SESSION_DURATION = timedelta(minutes=30) @@ -14,16 +19,27 @@ IMPERSONATE_CUSTOMER = ( "hosting.view_customer", "hosting.impersonate_customer", ) +WRITE_AS_CUSTOMER = "hosting.write_as_customer" +CUSTOMER_WRITE_PERMISSIONS = { + "panel:database_create": ( + "hosting.view_hostingaccount", + "hosting.view_hostingdatabase", + "hosting.add_hostingdatabase", + ), + "panel:mailbox_create": ( + "hosting.view_hostingaccount", + "hosting.view_hostingmailbox", + "hosting.add_hostingmailbox", + ), + "panel:sftp_keys": MANAGE_SFTP_KEYS, +} PREVIEW_VIEWS = frozenset( { "panel:accounts", "panel:account", - "panel:database_create", - "panel:mailbox_create", "panel:mail_dns_check", - "panel:sftp_keys", } -) +) | frozenset(CUSTOMER_WRITE_PERMISSIONS) EndReason = CustomerImpersonation.EndReason @@ -37,13 +53,78 @@ def can_impersonate_customer(user): ) -def start_impersonation(request, customer): +def can_start_writable_support(user): + return can_impersonate_customer(user) and user.has_perm(WRITE_AS_CUSTOMER) + + +def can_edit_customer_resource(request): + session = getattr(request, "impersonation", None) + if session is None: + return True + permissions = CUSTOMER_WRITE_PERMISSIONS.get( + request.resolver_match.view_name + ) + return ( + session.write_enabled + and permissions is not None + and request.support_operator.has_perms(permissions) + ) + + +def lock_session(sessions): + if connection.vendor == "sqlite": + # Take the write lock before reading the session on SQLite. + sessions.update(write_enabled=F("write_enabled")) + return sessions.select_for_update().first() + + +@contextmanager +def support_write_session(request): + session = getattr(request, "impersonation", None) + submitted_session = request.POST.get("support_session") + if session is None: + if submitted_session is not None: + raise PermissionDenied + yield None + return + + if str(session.pk) != submitted_session or not can_edit_customer_resource( + request + ): + raise PermissionDenied + with transaction.atomic(): + sessions = CustomerImpersonation.objects.filter( + pk=session.pk, + operator_id=request.support_operator.pk, + customer_id=session.customer_id, + ended_at__isnull=True, + write_enabled=True, + ) + current = lock_session(sessions) + permissions = CUSTOMER_WRITE_PERMISSIONS[ + request.resolver_match.view_name + ] + if ( + current is None + or current.expires_at <= timezone.now() + or current.customer is None + or current.customer.user_id != request.user.pk + or not current.customer.may_be_impersonated + or not can_start_writable_support(current.operator) + or not current.operator.has_perms(permissions) + ): + raise PermissionDenied + yield current + + +def start_impersonation(request, customer, *, write_enabled=False): now = timezone.now() session = CustomerImpersonation.objects.create( operator=request.user, customer=customer, operator_username=request.user.get_username(), customer_username=customer.user.get_username(), + write_enabled=write_enabled, started_at=now, expires_at=now + SESSION_DURATION, ) @@ -53,12 +134,16 @@ def start_impersonation(request, customer): def end_impersonation(request, session, reason): if session is not None: - CustomerImpersonation.objects.filter( - pk=session.pk, ended_at__isnull=True - ).update( - ended_at=min(timezone.now(), session.expires_at), - end_reason=reason, - ) + with transaction.atomic(): + sessions = CustomerImpersonation.objects.filter( + pk=session.pk, ended_at__isnull=True + ) + current = lock_session(sessions) + if current is not None: + sessions.update( + ended_at=min(timezone.now(), current.expires_at), + end_reason=reason, + ) request.session.pop(SESSION_KEY, None) rotate_token(request) @@ -98,6 +183,8 @@ class CustomerImpersonationMiddleware: reason = EndReason.EXPIRED elif ( not can_impersonate_customer(request.user) + or session.write_enabled + and not request.user.has_perm(WRITE_AS_CUSTOMER) or session.customer is None or not session.customer.may_be_impersonated ): @@ -116,6 +203,7 @@ class CustomerImpersonationMiddleware: ) request.impersonation = session + request.support_operator = request.user if view_name == "panel:impersonation_stop": return None @@ -126,6 +214,8 @@ class CustomerImpersonationMiddleware: request.auser = preview_user if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS: return None + if request.method == "POST" and can_edit_customer_resource(request): + return None return render( request, "hosting/customer_preview_restricted.html", status=403 ) diff --git a/src/coulobre/hosting/migrations/0041_audited_support_writes.py b/src/coulobre/hosting/migrations/0041_audited_support_writes.py new file mode 100644 index 0000000..7cd5521 --- /dev/null +++ b/src/coulobre/hosting/migrations/0041_audited_support_writes.py @@ -0,0 +1,84 @@ +# Generated by Django 5.2.19 on 2026-11-21 22:01 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0040_remote_mail_archives"), + ] + + operations = [ + migrations.AlterModelOptions( + name="customerimpersonation", + options={ + "default_permissions": ("view",), + "ordering": ("-started_at", "-pk"), + "permissions": ( + ( + "impersonate_customer", + "Can view the panel as a customer", + ), + ( + "write_as_customer", + "Can start a support session with write access", + ), + ), + "verbose_name": "customer impersonation session", + }, + ), + migrations.AddField( + model_name="customerimpersonation", + name="write_enabled", + field=models.BooleanField(default=False), + ), + migrations.CreateModel( + name="CustomerImpersonationAction", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("hosting_account_id", models.PositiveBigIntegerField()), + ( + "operation", + models.CharField( + choices=[ + ("database", "Requested database"), + ("mailbox", "Requested mailbox"), + ("add_keys", "Queued SSH key upload"), + ("remove_key", "Queued SSH key removal"), + ("revoke_sftp", "Queued SFTP revocation"), + ], + max_length=16, + ), + ), + ("resource", models.CharField(max_length=254)), + ("details", models.JSONField(default=dict)), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ( + "session", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="actions", + to="hosting.customerimpersonation", + ), + ), + ], + options={ + "verbose_name": "customer impersonation action", + "ordering": ("-requested_at", "-pk"), + "default_permissions": ("view",), + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 6d98a63..6c79210 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -137,6 +137,7 @@ class CustomerImpersonation(models.Model): ) operator_username = models.CharField(max_length=150) customer_username = models.CharField(max_length=150) + write_enabled = models.BooleanField(default=False) started_at = models.DateTimeField(default=timezone.now) expires_at = models.DateTimeField() ended_at = models.DateTimeField(null=True, blank=True) @@ -150,12 +151,39 @@ class CustomerImpersonation(models.Model): verbose_name = "customer impersonation session" permissions = ( ("impersonate_customer", "Can view the panel as a customer"), + ( + "write_as_customer", + "Can start a support session with write access", + ), ) def __str__(self): return f"{self.operator_username} viewing as {self.customer_username}" +class CustomerImpersonationAction(models.Model): + class Operation(models.TextChoices): + DATABASE = "database", "Requested database" + MAILBOX = "mailbox", "Requested mailbox" + ADD_KEYS = "add_keys", "Queued SSH key upload" + REMOVE_KEY = "remove_key", "Queued SSH key removal" + REVOKE_SFTP = "revoke_sftp", "Queued SFTP revocation" + + session = models.ForeignKey( + CustomerImpersonation, on_delete=models.PROTECT, related_name="actions" + ) + hosting_account_id = models.PositiveBigIntegerField() + operation = models.CharField(max_length=16, choices=Operation.choices) + resource = models.CharField(max_length=254) + details = models.JSONField(default=dict) + requested_at = models.DateTimeField(default=timezone.now) + + class Meta: + ordering = ("-requested_at", "-pk") + default_permissions = ("view",) + verbose_name = "customer impersonation action" + + class ServiceCredentialAccess(models.Model): class Kind(models.TextChoices): DATABASE = "database", "MariaDB database" diff --git a/src/coulobre/hosting/sftp.py b/src/coulobre/hosting/sftp.py index 50e56ec..ddf676b 100644 --- a/src/coulobre/hosting/sftp.py +++ b/src/coulobre/hosting/sftp.py @@ -1,3 +1,5 @@ +from dataclasses import dataclass + from django import forms from django.core.exceptions import ValidationError from django.db import transaction @@ -12,13 +14,19 @@ from .access import customer_for_user, is_tenant from .models import SiteSFTP from .resource_requests import lock_hosting_account, require_open_account +MANAGE_SFTP_KEYS = ("hosting.view_hostingaccount", "hosting.change_sitesftp") + + +@dataclass(frozen=True) +class SFTPKeyChange: + domain: str + added: list[str] + removed: list[str] + def can_manage_sftp(user): return customer_for_user(user) is not None or ( - not is_tenant(user) - and user.has_perms( - ("hosting.view_hostingaccount", "hosting.change_sitesftp") - ) + not is_tenant(user) and user.has_perms(MANAGE_SFTP_KEYS) ) @@ -54,21 +62,28 @@ def queue_sftp_keys( } if request is None: SiteSFTP.objects.create(account=account, **updates) - return - same_keys = ( - request.domain == updates["domain"] - and request.public_keys == keys - and request.requested_customer_id == customer_id - ) - if request.finished_at is None: - if not same_keys: - raise ValidationError( - "Wait for the current SFTP key request to finish." - ) - elif not same_keys or request.problem: + else: + same_keys = ( + request.domain == updates["domain"] + and request.public_keys == keys + and request.requested_customer_id == customer_id + ) + if request.finished_at is None: + if not same_keys: + raise ValidationError( + "Wait for the current SFTP key request to finish." + ) + return + if same_keys and not request.problem: + return SiteSFTP.objects.requeue( SiteSFTP.objects.filter(pk=request.pk), **updates ) + before = {public_key_fingerprint(key) for key in previous.splitlines()} + after = {public_key_fingerprint(key) for key in keys.splitlines()} + return SFTPKeyChange( + updates["domain"], sorted(after - before), sorted(before - after) + ) def change_key_list(previous, operation, public_keys, fingerprint): diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index e030a8d..1cad2be 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -68,7 +68,11 @@
Viewing as {{ request.impersonation.customer }} -

Read-only support session

+ {% if request.impersonation.write_enabled %} +

Support session with write access ยท {{ request.impersonation.operator_username }}

+ {% else %} +

Read-only support session

+ {% endif %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/customer_action_fields.html b/src/coulobre/hosting/templates/hosting/customer_action_fields.html new file mode 100644 index 0000000..c800cd4 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/customer_action_fields.html @@ -0,0 +1,5 @@ +{% load l10n %} +{% csrf_token %} +{% if request.impersonation.write_enabled %} + +{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html index f02b8ca..1e67d59 100644 --- a/src/coulobre/hosting/templates/hosting/customer_list.html +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -50,6 +50,12 @@ {% csrf_token %}
+ {% if can_start_support %} +
+ {% csrf_token %} + +
+ {% endif %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/database_form.html b/src/coulobre/hosting/templates/hosting/database_form.html index 754419c..79a5bdb 100644 --- a/src/coulobre/hosting/templates/hosting/database_form.html +++ b/src/coulobre/hosting/templates/hosting/database_form.html @@ -5,10 +5,10 @@

Request MariaDB database

- {% csrf_token %} + {% include "hosting/customer_action_fields.html" %} {{ form.as_div }}
- {% if not request.impersonation %} + {% if can_request_resource %} {% endif %} Cancel diff --git a/src/coulobre/hosting/templates/hosting/mailbox_form.html b/src/coulobre/hosting/templates/hosting/mailbox_form.html index 9f01cf8..e6bd161 100644 --- a/src/coulobre/hosting/templates/hosting/mailbox_form.html +++ b/src/coulobre/hosting/templates/hosting/mailbox_form.html @@ -10,10 +10,10 @@
- {% csrf_token %} + {% include "hosting/customer_action_fields.html" %} {{ form.as_div }}
- {% if not request.impersonation %} + {% if can_request_resource %} {% endif %} Cancel diff --git a/src/coulobre/hosting/templates/hosting/sftp_keys.html b/src/coulobre/hosting/templates/hosting/sftp_keys.html index d5c9620..bd0cdd4 100644 --- a/src/coulobre/hosting/templates/hosting/sftp_keys.html +++ b/src/coulobre/hosting/templates/hosting/sftp_keys.html @@ -62,7 +62,7 @@ {% if can_edit_keys %} - {% csrf_token %} + {% include "hosting/customer_action_fields.html" %} @@ -78,7 +78,7 @@ {% if can_edit_keys or can_revoke_keys %}
- {% csrf_token %} + {% include "hosting/customer_action_fields.html" %} {% if can_edit_keys %} {{ form.public_keys.as_field_group }} {% endif %} diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 9577432..480728a 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -156,6 +156,11 @@ urlpatterns = [ views.CustomerImpersonationStart.as_view(), name="impersonation_start", ), + path( + "customers//support/", + views.CustomerImpersonationStart.as_view(write_enabled=True), + name="impersonation_write_start", + ), path( "customer-view/end/", views.CustomerImpersonationStop.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index a6303ef..f80356f 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -68,16 +68,21 @@ from .backup_retention import change_backup_retention, protect_backup from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_publication import queue_dns_publication from .impersonation import ( + CUSTOMER_WRITE_PERMISSIONS, EndReason, + can_edit_customer_resource, can_impersonate_customer, + can_start_writable_support, end_impersonation, start_impersonation, + support_write_session, ) from .models import ( AccountBackupJob, AccountBackupSchedule, ComponentRestoreJob, Customer, + CustomerImpersonationAction, HostingAccount, HostingDatabase, HostingDnsZone, @@ -1209,7 +1214,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): def get_context_data(self, **kwargs): status = getattr(self.account, "sftp", None) - editable = getattr(self.request, "impersonation", None) is None + editable = can_edit_customer_resource(self.request) idle = status is None or status.finished_at is not None keys = () if status is None else status.public_keys.splitlines() return super().get_context_data( @@ -1231,14 +1236,32 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): def form_valid(self, form): customer = customer_for_user(self.request.user) + operation = form.cleaned_data["operation"] try: - queue_sftp_keys( - self.account.pk, - form.cleaned_data["operation"], - public_keys=form.cleaned_data["public_keys"], - fingerprint=form.cleaned_data["fingerprint"], - customer_id=customer.pk if customer is not None else None, - ) + with support_write_session(self.request) as session: + change = queue_sftp_keys( + self.account.pk, + operation, + public_keys=form.cleaned_data["public_keys"], + fingerprint=form.cleaned_data["fingerprint"], + customer_id=customer.pk if customer is not None else None, + ) + if session is not None and change is not None: + operations = CustomerImpersonationAction.Operation + CustomerImpersonationAction.objects.create( + session=session, + hosting_account_id=self.account.pk, + operation={ + "add": operations.ADD_KEYS, + "remove": operations.REMOVE_KEY, + "revoke": operations.REVOKE_SFTP, + }[operation], + resource=change.domain, + details={ + "added": change.added, + "removed": change.removed, + }, + ) except HostingAccount.DoesNotExist as error: raise Http404 from error except ValidationError as error: @@ -1269,6 +1292,7 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): return super().get_context_data( search=self.search, can_impersonate=can_impersonate_customer(self.request.user), + can_start_support=can_start_writable_support(self.request.user), **kwargs, ) @@ -1322,7 +1346,11 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View): class CustomerImpersonationStart(PermissionRequiredMixin, View): + write_enabled = False + def has_permission(self): + if self.write_enabled: + return can_start_writable_support(self.request.user) return can_impersonate_customer(self.request.user) def post(self, request, pk): @@ -1330,7 +1358,9 @@ class CustomerImpersonationStart(PermissionRequiredMixin, View): customer = get_object_or_404(customers, pk=pk) if not customer.may_be_impersonated: raise Http404 - start_impersonation(request, customer) + start_impersonation( + request, customer, write_enabled=self.write_enabled + ) return redirect("panel:accounts") @@ -1372,6 +1402,8 @@ def provisioning_conflict(error): class ResourceRequestCreate(PermissionRequiredMixin, CreateView): + audit_operation = None + @cached_property def customer(self): return customer_for_user(self.request.user) @@ -1390,24 +1422,36 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): - return super().get_context_data(account=self.account, **kwargs) + return super().get_context_data( + account=self.account, + can_request_resource=can_edit_customer_resource(self.request), + **kwargs, + ) def get_form(self, form_class=None): form = super().get_form(form_class) - if getattr(self.request, "impersonation", None) is not None: + if not can_edit_customer_resource(self.request): for field in form.fields.values(): field.disabled = True return form def form_valid(self, form): try: - self.object = self.create_request( - self.account.pk, - **form.cleaned_data, - customer_id=self.customer.pk - if self.customer is not None - else None, - ) + with support_write_session(self.request) as session: + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk + if self.customer is not None + else None, + ) + if session is not None: + CustomerImpersonationAction.objects.create( + session=session, + hosting_account_id=self.account.pk, + operation=self.audit_operation, + resource=str(self.object), + ) except HostingAccount.DoesNotExist as error: raise Http404 from error except ValidationError as error: @@ -1420,11 +1464,8 @@ class DatabaseCreate(ResourceRequestCreate): model = HostingDatabase fields = ("suffix",) template_name = "hosting/database_form.html" - permission_required = ( - VIEW_ACCOUNTS, - VIEW_DATABASES, - "hosting.add_hostingdatabase", - ) + permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:database_create"] + audit_operation = CustomerImpersonationAction.Operation.DATABASE create_request = staticmethod(create_database_request) @@ -1642,11 +1683,8 @@ class MailboxCreate(ResourceRequestCreate): model = HostingMailbox fields = ("local_part",) template_name = "hosting/mailbox_form.html" - permission_required = ( - VIEW_ACCOUNTS, - VIEW_MAILBOXES, - "hosting.add_hostingmailbox", - ) + permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:mailbox_create"] + audit_operation = CustomerImpersonationAction.Operation.MAILBOX create_request = staticmethod(create_mailbox_request) def get_form(self, form_class=None): From 3b4157f514561cd0ad1105340874c442af562740 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 23:05:37 +0100 Subject: [PATCH 2/2] Document and verify writable customer support sessions --- README.md | 5 +- docs/development.md | 19 + src/coulobre/hosting/test_support_writes.py | 372 ++++++++++++++++++++ 3 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 src/coulobre/hosting/test_support_writes.py diff --git a/README.md b/README.md index 9258a98..b8a0198 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ Coulobre Panel is an open-source web hosting control panel for hosting providers and resellers. The project is in early development. The web panel gives operators a workspace to manage hosting accounts, request -Apache configuration previews, and follow their progress. Administrators with -permission can view the panel as a customer in a read-only support session. +Apache configuration previews, and follow their progress. Administrators +with the appropriate permissions can view the panel as a customer or +perform audited support actions on their behalf. See [Local development](docs/development.md) to run it. See [Single-server deployment](docs/deployment.md) to install it with Apache, MariaDB, and RabbitMQ. diff --git a/docs/development.md b/docs/development.md index c5c9df9..c25f727 100644 --- a/docs/development.md +++ b/docs/development.md @@ -119,6 +119,25 @@ sessions**. In `/admin/`, users with **Can view customer impersonation session** can review the administrator, customer, timestamps, and outcome for each session. The audit records are read-only in Django admin. +### Make changes during a support session + +Grant **Can start a support session with write access** in addition to the +two customer view permissions. Select **Support with write access** next +to the customer. The banner identifies the active customer, administrator, +and mode. + +In a writable session, the administrator can request a database or mailbox +and manage SSH keys on the customer's hosting accounts. Each action also +requires the administrator's normal permission for that operation. The +customer's account scope and plan limits apply. Forms belong to the active +support session. Reopen the form after changing sessions or modes. + +Grant **Can view customer impersonation action** to review these changes in +`/admin/`. Each entry records the session, administrator, customer, account +ID, operation, resource, and time. SSH key changes record fingerprints of +the keys added or removed. Queued changes still report their execution +status in the hosting account. + ## Request a MariaDB database Open a hosting account and select **Request database**. Choose a short suffix diff --git a/src/coulobre/hosting/test_support_writes.py b/src/coulobre/hosting/test_support_writes.py new file mode 100644 index 0000000..5339f82 --- /dev/null +++ b/src/coulobre/hosting/test_support_writes.py @@ -0,0 +1,372 @@ +from unittest.mock import patch + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.core.files.uploadedfile import SimpleUploadedFile +from django.db import IntegrityError +from django.test import Client, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.sftp_keys import public_key_fingerprint + +from .impersonation import SESSION_KEY +from .models import ( + Customer, + CustomerImpersonation, + CustomerImpersonationAction, + HostingAccount, + HostingDatabase, + HostingMailbox, + HostingPlan, + Reseller, + SiteSFTP, + WebActivation, + WebProvisioningPlan, +) +from .test_sftp_keys import public_key +from .views import DatabaseCreate + +Operation = CustomerImpersonationAction.Operation + + +class SupportWriteTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.admin = users.create_superuser("operator") + cls.staff = users.create_user("support", is_staff=True) + cls.customer = Customer.objects.create(user=users.create_user("alice")) + cls.account = HostingAccount.objects.create( + name="Alice site", + primary_domain="alice.example", + customer=cls.customer, + hosting_plan=HostingPlan.objects.create( + name="Small", database_limit=1, mailbox_limit=1 + ), + ) + cls.other = HostingAccount.objects.create( + name="Other site", + primary_domain="other.example", + customer=Customer.objects.create(user=users.create_user("other")), + ) + + def setUp(self): + self.client.force_login(self.admin) + self.start_url = reverse( + "panel:impersonation_write_start", args=[self.customer.pk] + ) + self.stop_url = reverse("panel:impersonation_stop") + self.database_url = reverse( + "panel:database_create", args=[self.account.pk] + ) + self.mailbox_url = reverse( + "panel:mailbox_create", args=[self.account.pk] + ) + + def grant(self, *codenames): + self.staff.user_permissions.add( + *Permission.objects.filter( + content_type__app_label="hosting", codename__in=codenames + ) + ) + + def start(self): + self.assertRedirects( + self.client.post(self.start_url), reverse("panel:accounts") + ) + session = CustomerImpersonation.objects.get( + pk=self.client.session[SESSION_KEY] + ) + self.assertTrue(session.write_enabled) + return session + + def test_write_mode_requires_a_separate_permission_and_staff(self): + self.grant("view_customer", "impersonate_customer") + self.client.force_login(self.staff) + url = reverse("panel:customers") + self.assertNotContains( + self.client.get(url), "Support with write access" + ) + self.assertEqual(self.client.post(self.start_url).status_code, 403) + self.grant("write_as_customer") + self.assertContains(self.client.get(url), "Support with write access") + Reseller.objects.create(user=self.staff) + self.assertEqual(self.client.post(self.start_url).status_code, 403) + self.assertFalse(CustomerImpersonation.objects.exists()) + + def test_explicit_session_records_database_and_mailbox_requests(self): + session = self.start() + page = self.client.get(self.database_url) + self.assertContains(page, "Support session with write access") + self.assertContains( + page, f'name="support_session" value="{session.pk}"' + ) + self.assertFalse(page.context["form"].fields["suffix"].disabled) + for url, data in ( + (self.database_url, {"suffix": "blog"}), + (self.mailbox_url, {"local_part": "help"}), + ): + self.assertRedirects( + self.client.post(url, data | {"support_session": session.pk}), + self.account.get_absolute_url(), + ) + actions = CustomerImpersonationAction.objects.filter( + session=session, hosting_account_id=self.account.pk + ) + self.assertEqual( + dict(actions.values_list("operation", "resource")), + { + Operation.DATABASE: HostingDatabase.objects.get().spec.name, + Operation.MAILBOX: "help@alice.example", + }, + ) + self.assertEqual(session.operator_username, "operator") + self.assertEqual(session.customer_username, "alice") + response = self.client.post( + self.database_url, + {"suffix": "extra", "support_session": session.pk}, + ) + self.assertContains(response, "reached its database limit") + self.assertEqual(actions.count(), 2) + + def test_limits_writes_to_the_customer_and_existing_operator_permissions( + self, + ): + self.grant( + "view_customer", + "impersonate_customer", + "write_as_customer", + "view_hostingaccount", + "view_hostingdatabase", + "add_hostingdatabase", + ) + self.client.force_login(self.staff) + session = self.start() + data = {"suffix": "blog", "support_session": session.pk} + self.assertEqual( + self.client.post( + reverse("panel:database_create", args=[self.other.pk]), data + ).status_code, + 404, + ) + self.assertTrue( + self.client.get(self.mailbox_url) + .context["form"] + .fields["local_part"] + .disabled + ) + self.assertEqual( + self.client.post( + self.mailbox_url, + {"local_part": "help", "support_session": session.pk}, + ).status_code, + 403, + ) + self.assertRedirects( + self.client.post(self.database_url, data), + self.account.get_absolute_url(), + ) + self.assertEqual(CustomerImpersonationAction.objects.count(), 1) + + def test_credentials_and_administration_stay_restricted(self): + session = self.start() + self.client.post( + self.database_url, + {"suffix": "blog", "support_session": session.pk}, + ) + database = HostingDatabase.objects.get() + for route, args in ( + ("panel:database_credential_rotation", [database.pk]), + ("panel:account_backup_create", [self.account.pk]), + ("admin:index", []), + ): + with self.subTest(route=route): + self.assertEqual( + self.client.post( + reverse(route, args=args), + {"support_session": session.pk}, + ).status_code, + 403, + ) + self.assertEqual(CustomerImpersonationAction.objects.count(), 1) + + def test_uses_csrf_and_rejects_forms_from_another_mode(self): + self.client = Client(enforce_csrf_checks=True) + self.client.force_login(self.admin) + self.client.get(reverse("panel:customers")) + key = settings.CSRF_COOKIE_NAME + self.assertEqual(self.client.post(self.start_url).status_code, 403) + self.assertEqual( + self.client.post( + self.start_url, + {}, + HTTP_X_CSRFTOKEN=self.client.cookies[key].value, + ).status_code, + 302, + ) + marker = self.client.session[SESSION_KEY] + data = {"suffix": "blog", "support_session": marker} + self.assertEqual( + self.client.post(self.database_url, data).status_code, 403 + ) + csrf = self.client.cookies[key].value + self.assertEqual( + self.client.post( + self.database_url, {"suffix": "blog"}, HTTP_X_CSRFTOKEN=csrf + ).status_code, + 403, + ) + self.assertEqual( + self.client.post( + self.stop_url, {}, HTTP_X_CSRFTOKEN=csrf + ).status_code, + 302, + ) + self.assertEqual( + self.client.post( + self.database_url, + data, + HTTP_X_CSRFTOKEN=self.client.cookies[key].value, + ).status_code, + 403, + ) + self.assertFalse(HostingDatabase.objects.exists()) + + def test_rechecks_session_at_write_boundary_and_rolls_back_on_audit_error( + self, + ): + session = self.start() + data = {"suffix": "blog", "support_session": session.pk} + with ( + patch.object( + CustomerImpersonationAction.objects, + "create", + side_effect=IntegrityError, + ), + self.assertRaises(IntegrityError), + ): + self.client.post(self.database_url, data) + self.assertFalse(HostingDatabase.objects.exists()) + + get_form = DatabaseCreate.get_form + + def end_before_write(view, *args, **kwargs): + form = get_form(view, *args, **kwargs) + CustomerImpersonation.objects.filter(pk=session.pk).update( + ended_at=timezone.now(), + end_reason=CustomerImpersonation.EndReason.STOPPED, + ) + return form + + with patch.object(DatabaseCreate, "get_form", end_before_write): + self.assertEqual( + self.client.post(self.database_url, data).status_code, 403 + ) + self.assertFalse(HostingDatabase.objects.exists()) + self.assertFalse(CustomerImpersonationAction.objects.exists()) + + def test_revoking_write_permission_ends_the_active_session(self): + self.grant( + "view_customer", "impersonate_customer", "write_as_customer" + ) + self.client.force_login(self.staff) + session = self.start() + self.staff.user_permissions.remove( + Permission.objects.get(codename="write_as_customer") + ) + self.assertContains( + self.client.post( + self.mailbox_url, + {"local_part": "help", "support_session": session.pk}, + ), + "Customer view ended", + status_code=409, + ) + session.refresh_from_db() + self.assertEqual(session.end_reason, session.EndReason.ACCESS_REVOKED) + self.assertFalse(HostingMailbox.objects.exists()) + + def test_action_audit_is_read_only_and_requires_view_permission(self): + session = self.start() + self.client.post( + self.database_url, + {"suffix": "blog", "support_session": session.pk}, + ) + event = session.actions.get() + self.client.force_login(self.staff) + audit = reverse("admin:hosting_customerimpersonationaction_changelist") + self.assertEqual(self.client.get(audit).status_code, 403) + self.grant("view_customerimpersonationaction") + response = self.client.get(audit) + for label in ( + "operator", + "alice", + "Requested database", + event.resource, + ): + self.assertContains(response, label) + detail = reverse( + "admin:hosting_customerimpersonationaction_change", args=[event.pk] + ) + self.assertNotContains(self.client.get(detail), 'name="_save"') + self.assertEqual( + self.client.post(detail, {"resource": "changed"}).status_code, 403 + ) + + @override_settings(LOCAL_WEB_SFTP=True) + def test_audits_queued_key_changes_by_fingerprint(self): + plan = WebProvisioningPlan.for_account(self.account) + plan.save() + WebActivation.objects.create(plan=plan, finished_at=timezone.now()) + session = self.start() + url = reverse("panel:sftp_keys", args=[self.account.pk]) + self.assertContains(self.client.get(url), "Upload SSH keys") + key = public_key() + for operation, data, expected in ( + ( + "add", + {"public_keys": SimpleUploadedFile("site.pub", key.encode())}, + Operation.ADD_KEYS, + ), + ( + "remove", + {"fingerprint": public_key_fingerprint(key)}, + Operation.REMOVE_KEY, + ), + ): + self.assertRedirects( + self.client.post( + url, + data + | {"operation": operation, "support_session": session.pk}, + ), + url, + ) + change = session.actions.latest("pk") + field = "added" if operation == "add" else "removed" + self.assertEqual(change.operation, expected) + self.assertEqual( + change.details[field], [public_key_fingerprint(key)] + ) + self.assertNotIn(key, str(change.details)) + SiteSFTP.objects.filter(account=self.account).update( + finished_at=timezone.now() + ) + self.assertEqual( + SiteSFTP.objects.get().requested_customer_id, self.customer.pk + ) + self.assertEqual(session.actions.count(), 2) + self.assertRedirects( + self.client.post( + url, + { + "operation": "remove", + "fingerprint": public_key_fingerprint(key), + "support_session": session.pk, + }, + ), + url, + ) + self.assertEqual(session.actions.count(), 2)