Allow audited customer support writes #80

Merged
parkel merged 2 commits from feature/audited-support-writes into main 2026-11-21 23:11:12 +01:00
16 changed files with 772 additions and 64 deletions

No files matched your search

+3 -2
View File
@@ -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. and resellers. The project is in early development.
The web panel gives operators a workspace to manage hosting accounts, request The web panel gives operators a workspace to manage hosting accounts, request
Apache configuration previews, and follow their progress. Administrators with Apache configuration previews, and follow their progress. Administrators
permission can view the panel as a customer in a read-only support session. 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 [Local development](docs/development.md) to run it.
See [Single-server deployment](docs/deployment.md) to install it with Apache, See [Single-server deployment](docs/deployment.md) to install it with Apache,
MariaDB, and RabbitMQ. MariaDB, and RabbitMQ.
+19
View File
@@ -119,6 +119,25 @@ sessions**. In `/admin/`, users with **Can view customer impersonation
session** can review the administrator, customer, timestamps, and outcome session** can review the administrator, customer, timestamps, and outcome
for each session. The audit records are read-only in Django admin. 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 ## Request a MariaDB database
Open a hosting account and select **Request database**. Choose a short suffix Open a hosting account and select **Request database**. Choose a short suffix
+41
View File
@@ -5,6 +5,7 @@ from django.utils.timezone import now
from .models import ( from .models import (
Customer, Customer,
CustomerImpersonation, CustomerImpersonation,
CustomerImpersonationAction,
HostingAccount, HostingAccount,
HostingPlan, HostingPlan,
Reseller, Reseller,
@@ -98,6 +99,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
list_display = ( list_display = (
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
@@ -107,6 +109,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
fields = ( fields = (
"operator_username", "operator_username",
"customer_username", "customer_username",
"write_enabled",
"started_at", "started_at",
"expires_at", "expires_at",
"ended_at", "ended_at",
@@ -132,6 +135,44 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
return False 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) @admin.register(ServiceCredentialAccess)
class ServiceCredentialAccessAdmin(admin.ModelAdmin): class ServiceCredentialAccessAdmin(admin.ModelAdmin):
list_display = ( list_display = (
+101 -11
View File
@@ -1,5 +1,9 @@
from contextlib import contextmanager
from datetime import timedelta 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.middleware.csrf import rotate_token
from django.shortcuts import render from django.shortcuts import render
from django.utils import timezone from django.utils import timezone
@@ -7,6 +11,7 @@ from django.utils.cache import add_never_cache_headers
from .access import is_tenant from .access import is_tenant
from .models import CustomerImpersonation from .models import CustomerImpersonation
from .sftp import MANAGE_SFTP_KEYS
SESSION_KEY = "customer_impersonation" SESSION_KEY = "customer_impersonation"
SESSION_DURATION = timedelta(minutes=30) SESSION_DURATION = timedelta(minutes=30)
@@ -14,16 +19,27 @@ IMPERSONATE_CUSTOMER = (
"hosting.view_customer", "hosting.view_customer",
"hosting.impersonate_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( PREVIEW_VIEWS = frozenset(
{ {
"panel:accounts", "panel:accounts",
"panel:account", "panel:account",
"panel:database_create",
"panel:mailbox_create",
"panel:mail_dns_check", "panel:mail_dns_check",
"panel:sftp_keys",
} }
) ) | frozenset(CUSTOMER_WRITE_PERMISSIONS)
EndReason = CustomerImpersonation.EndReason 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() now = timezone.now()
session = CustomerImpersonation.objects.create( session = CustomerImpersonation.objects.create(
operator=request.user, operator=request.user,
customer=customer, customer=customer,
operator_username=request.user.get_username(), operator_username=request.user.get_username(),
customer_username=customer.user.get_username(), customer_username=customer.user.get_username(),
write_enabled=write_enabled,
started_at=now, started_at=now,
expires_at=now + SESSION_DURATION, expires_at=now + SESSION_DURATION,
) )
@@ -53,12 +134,16 @@ def start_impersonation(request, customer):
def end_impersonation(request, session, reason): def end_impersonation(request, session, reason):
if session is not None: if session is not None:
CustomerImpersonation.objects.filter( with transaction.atomic():
pk=session.pk, ended_at__isnull=True sessions = CustomerImpersonation.objects.filter(
).update( pk=session.pk, ended_at__isnull=True
ended_at=min(timezone.now(), session.expires_at), )
end_reason=reason, 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) request.session.pop(SESSION_KEY, None)
rotate_token(request) rotate_token(request)
@@ -98,6 +183,8 @@ class CustomerImpersonationMiddleware:
reason = EndReason.EXPIRED reason = EndReason.EXPIRED
elif ( elif (
not can_impersonate_customer(request.user) 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 session.customer is None
or not session.customer.may_be_impersonated or not session.customer.may_be_impersonated
): ):
@@ -116,6 +203,7 @@ class CustomerImpersonationMiddleware:
) )
request.impersonation = session request.impersonation = session
request.support_operator = request.user
if view_name == "panel:impersonation_stop": if view_name == "panel:impersonation_stop":
return None return None
@@ -126,6 +214,8 @@ class CustomerImpersonationMiddleware:
request.auser = preview_user request.auser = preview_user
if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS: if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS:
return None return None
if request.method == "POST" and can_edit_customer_resource(request):
return None
return render( return render(
request, "hosting/customer_preview_restricted.html", status=403 request, "hosting/customer_preview_restricted.html", status=403
) )
@@ -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",),
},
),
]
+28
View File
@@ -137,6 +137,7 @@ class CustomerImpersonation(models.Model):
) )
operator_username = models.CharField(max_length=150) operator_username = models.CharField(max_length=150)
customer_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) started_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField() expires_at = models.DateTimeField()
ended_at = models.DateTimeField(null=True, blank=True) ended_at = models.DateTimeField(null=True, blank=True)
@@ -150,12 +151,39 @@ class CustomerImpersonation(models.Model):
verbose_name = "customer impersonation session" verbose_name = "customer impersonation session"
permissions = ( permissions = (
("impersonate_customer", "Can view the panel as a customer"), ("impersonate_customer", "Can view the panel as a customer"),
(
"write_as_customer",
"Can start a support session with write access",
),
) )
def __str__(self): def __str__(self):
return f"{self.operator_username} viewing as {self.customer_username}" 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 ServiceCredentialAccess(models.Model):
class Kind(models.TextChoices): class Kind(models.TextChoices):
DATABASE = "database", "MariaDB database" DATABASE = "database", "MariaDB database"
+31 -16
View File
@@ -1,3 +1,5 @@
from dataclasses import dataclass
from django import forms from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
@@ -12,13 +14,19 @@ from .access import customer_for_user, is_tenant
from .models import SiteSFTP from .models import SiteSFTP
from .resource_requests import lock_hosting_account, require_open_account 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): def can_manage_sftp(user):
return customer_for_user(user) is not None or ( return customer_for_user(user) is not None or (
not is_tenant(user) not is_tenant(user) and user.has_perms(MANAGE_SFTP_KEYS)
and user.has_perms(
("hosting.view_hostingaccount", "hosting.change_sitesftp")
)
) )
@@ -54,21 +62,28 @@ def queue_sftp_keys(
} }
if request is None: if request is None:
SiteSFTP.objects.create(account=account, **updates) SiteSFTP.objects.create(account=account, **updates)
return else:
same_keys = ( same_keys = (
request.domain == updates["domain"] request.domain == updates["domain"]
and request.public_keys == keys and request.public_keys == keys
and request.requested_customer_id == customer_id and request.requested_customer_id == customer_id
) )
if request.finished_at is None: if request.finished_at is None:
if not same_keys: if not same_keys:
raise ValidationError( raise ValidationError(
"Wait for the current SFTP key request to finish." "Wait for the current SFTP key request to finish."
) )
elif not same_keys or request.problem: return
if same_keys and not request.problem:
return
SiteSFTP.objects.requeue( SiteSFTP.objects.requeue(
SiteSFTP.objects.filter(pk=request.pk), **updates 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): def change_key_list(previous, operation, public_keys, fingerprint):
@@ -68,7 +68,11 @@
<section class="notice customer-preview" aria-label="Customer view"> <section class="notice customer-preview" aria-label="Customer view">
<div> <div>
<strong>Viewing as {{ request.impersonation.customer }}</strong> <strong>Viewing as {{ request.impersonation.customer }}</strong>
<p>Read-only support session</p> {% if request.impersonation.write_enabled %}
<p>Support session with write access · {{ request.impersonation.operator_username }}</p>
{% else %}
<p>Read-only support session</p>
{% endif %}
</div> </div>
<form method="post" action="{% url 'panel:impersonation_stop' %}"> <form method="post" action="{% url 'panel:impersonation_stop' %}">
{% csrf_token %} {% csrf_token %}
@@ -0,0 +1,5 @@
{% load l10n %}
{% csrf_token %}
{% if request.impersonation.write_enabled %}
<input type="hidden" name="support_session" value="{{ request.impersonation.pk|unlocalize }}">
{% endif %}
@@ -50,6 +50,12 @@
{% csrf_token %} {% csrf_token %}
<button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button> <button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button>
</form> </form>
{% if can_start_support %}
<form method="post" action="{% url 'panel:impersonation_write_start' customer.pk %}">
{% csrf_token %}
<button class="button secondary" type="submit" aria-label="Start support with write access for {{ customer }}">Support with write access</button>
</form>
{% endif %}
{% endif %} {% endif %}
</div> </div>
</td> </td>
@@ -5,10 +5,10 @@
<header class="page-heading"><h1>Request MariaDB database</h1></header> <header class="page-heading"><h1>Request MariaDB database</h1></header>
<section class="surface editor-surface"> <section class="surface editor-surface">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
{% if not request.impersonation %} {% if can_request_resource %}
<button class="button primary" type="submit">Request database</button> <button class="button primary" type="submit">Request database</button>
{% endif %} {% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
@@ -10,10 +10,10 @@
</header> </header>
<section class="surface editor-surface"> <section class="surface editor-surface">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
{% if not request.impersonation %} {% if can_request_resource %}
<button class="button primary" type="submit">Request mailbox</button> <button class="button primary" type="submit">Request mailbox</button>
{% endif %} {% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
@@ -62,7 +62,7 @@
{% if can_edit_keys %} {% if can_edit_keys %}
<td> <td>
<form method="post"> <form method="post">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
<input type="hidden" name="fingerprint" value="{{ fingerprint }}"> <input type="hidden" name="fingerprint" value="{{ fingerprint }}">
<button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button> <button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button>
</form> </form>
@@ -78,7 +78,7 @@
{% if can_edit_keys or can_revoke_keys %} {% if can_edit_keys or can_revoke_keys %}
<section class="surface editor-surface" aria-label="SSH key management"> <section class="surface editor-surface" aria-label="SSH key management">
<form class="editor" method="post" enctype="multipart/form-data"> <form class="editor" method="post" enctype="multipart/form-data">
{% csrf_token %} {% include "hosting/customer_action_fields.html" %}
{% if can_edit_keys %} {% if can_edit_keys %}
{{ form.public_keys.as_field_group }} {{ form.public_keys.as_field_group }}
{% endif %} {% endif %}
+372
View File
@@ -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)
+5
View File
@@ -156,6 +156,11 @@ urlpatterns = [
views.CustomerImpersonationStart.as_view(), views.CustomerImpersonationStart.as_view(),
name="impersonation_start", name="impersonation_start",
), ),
path(
"customers/<int:pk>/support/",
views.CustomerImpersonationStart.as_view(write_enabled=True),
name="impersonation_write_start",
),
path( path(
"customer-view/end/", "customer-view/end/",
views.CustomerImpersonationStop.as_view(), views.CustomerImpersonationStop.as_view(),
+66 -28
View File
@@ -68,16 +68,21 @@ from .backup_retention import change_backup_retention, protect_backup
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .dns_publication import queue_dns_publication from .dns_publication import queue_dns_publication
from .impersonation import ( from .impersonation import (
CUSTOMER_WRITE_PERMISSIONS,
EndReason, EndReason,
can_edit_customer_resource,
can_impersonate_customer, can_impersonate_customer,
can_start_writable_support,
end_impersonation, end_impersonation,
start_impersonation, start_impersonation,
support_write_session,
) )
from .models import ( from .models import (
AccountBackupJob, AccountBackupJob,
AccountBackupSchedule, AccountBackupSchedule,
ComponentRestoreJob, ComponentRestoreJob,
Customer, Customer,
CustomerImpersonationAction,
HostingAccount, HostingAccount,
HostingDatabase, HostingDatabase,
HostingDnsZone, HostingDnsZone,
@@ -1209,7 +1214,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
status = getattr(self.account, "sftp", None) 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 idle = status is None or status.finished_at is not None
keys = () if status is None else status.public_keys.splitlines() keys = () if status is None else status.public_keys.splitlines()
return super().get_context_data( return super().get_context_data(
@@ -1231,14 +1236,32 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
def form_valid(self, form): def form_valid(self, form):
customer = customer_for_user(self.request.user) customer = customer_for_user(self.request.user)
operation = form.cleaned_data["operation"]
try: try:
queue_sftp_keys( with support_write_session(self.request) as session:
self.account.pk, change = queue_sftp_keys(
form.cleaned_data["operation"], self.account.pk,
public_keys=form.cleaned_data["public_keys"], operation,
fingerprint=form.cleaned_data["fingerprint"], public_keys=form.cleaned_data["public_keys"],
customer_id=customer.pk if customer is not None else None, 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: except HostingAccount.DoesNotExist as error:
raise Http404 from error raise Http404 from error
except ValidationError as error: except ValidationError as error:
@@ -1269,6 +1292,7 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
return super().get_context_data( return super().get_context_data(
search=self.search, search=self.search,
can_impersonate=can_impersonate_customer(self.request.user), can_impersonate=can_impersonate_customer(self.request.user),
can_start_support=can_start_writable_support(self.request.user),
**kwargs, **kwargs,
) )
@@ -1322,7 +1346,11 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
class CustomerImpersonationStart(PermissionRequiredMixin, View): class CustomerImpersonationStart(PermissionRequiredMixin, View):
write_enabled = False
def has_permission(self): def has_permission(self):
if self.write_enabled:
return can_start_writable_support(self.request.user)
return can_impersonate_customer(self.request.user) return can_impersonate_customer(self.request.user)
def post(self, request, pk): def post(self, request, pk):
@@ -1330,7 +1358,9 @@ class CustomerImpersonationStart(PermissionRequiredMixin, View):
customer = get_object_or_404(customers, pk=pk) customer = get_object_or_404(customers, pk=pk)
if not customer.may_be_impersonated: if not customer.may_be_impersonated:
raise Http404 raise Http404
start_impersonation(request, customer) start_impersonation(
request, customer, write_enabled=self.write_enabled
)
return redirect("panel:accounts") return redirect("panel:accounts")
@@ -1372,6 +1402,8 @@ def provisioning_conflict(error):
class ResourceRequestCreate(PermissionRequiredMixin, CreateView): class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
audit_operation = None
@cached_property @cached_property
def customer(self): def customer(self):
return customer_for_user(self.request.user) 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"]) return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs): 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): def get_form(self, form_class=None):
form = super().get_form(form_class) 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(): for field in form.fields.values():
field.disabled = True field.disabled = True
return form return form
def form_valid(self, form): def form_valid(self, form):
try: try:
self.object = self.create_request( with support_write_session(self.request) as session:
self.account.pk, self.object = self.create_request(
**form.cleaned_data, self.account.pk,
customer_id=self.customer.pk **form.cleaned_data,
if self.customer is not None customer_id=self.customer.pk
else None, 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: except HostingAccount.DoesNotExist as error:
raise Http404 from error raise Http404 from error
except ValidationError as error: except ValidationError as error:
@@ -1420,11 +1464,8 @@ class DatabaseCreate(ResourceRequestCreate):
model = HostingDatabase model = HostingDatabase
fields = ("suffix",) fields = ("suffix",)
template_name = "hosting/database_form.html" template_name = "hosting/database_form.html"
permission_required = ( permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:database_create"]
VIEW_ACCOUNTS, audit_operation = CustomerImpersonationAction.Operation.DATABASE
VIEW_DATABASES,
"hosting.add_hostingdatabase",
)
create_request = staticmethod(create_database_request) create_request = staticmethod(create_database_request)
@@ -1642,11 +1683,8 @@ class MailboxCreate(ResourceRequestCreate):
model = HostingMailbox model = HostingMailbox
fields = ("local_part",) fields = ("local_part",)
template_name = "hosting/mailbox_form.html" template_name = "hosting/mailbox_form.html"
permission_required = ( permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:mailbox_create"]
VIEW_ACCOUNTS, audit_operation = CustomerImpersonationAction.Operation.MAILBOX
VIEW_MAILBOXES,
"hosting.add_hostingmailbox",
)
create_request = staticmethod(create_mailbox_request) create_request = staticmethod(create_mailbox_request)
def get_form(self, form_class=None): def get_form(self, form_class=None):