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):