Add read-only customer impersonation for administrators #18

Merged
parkel merged 2 commits from feature/customer-impersonation into main 2026-11-21 02:26:00 +01:00
17 changed files with 794 additions and 18 deletions

No files matched your search

+2 -3
View File
@@ -4,7 +4,8 @@ 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. Apache configuration previews, and follow their progress. Administrators with
permission can view the panel as a customer in a read-only support session.
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.
@@ -13,8 +14,6 @@ MariaDB, and RabbitMQ.
- Self-hosted installation on a single Ubuntu server, with Debian support planned. - Self-hosted installation on a single Ubuntu server, with Debian support planned.
- Hosting plans and self-service access for administrators, resellers, and customers. - Hosting plans and self-service access for administrators, resellers, and customers.
- Customer impersonation for administrator support, with a dedicated permission,
a visible session indicator, and an audit trail.
- Domains, TLS certificates, SFTP, and databases using Apache, PHP-FPM, and MariaDB. - Domains, TLS certificates, SFTP, and databases using Apache, PHP-FPM, and MariaDB.
- Mail and DNS on the hosting server or on separate servers. - Mail and DNS on the hosting server or on separate servers.
- Account backups, restore, and migration from DirectAdmin. - Account backups, restore, and migration from DirectAdmin.
+20
View File
@@ -79,6 +79,26 @@ and select a customer on hosting accounts they can create or edit. **Can add
customer** enables customer creation. **Can change customer** enables customer** enables customer creation. **Can change customer** enables
sign-in suspension and restoration. sign-in suspension and restoration.
## View the panel as a customer
In **Customers**, select **View as customer** next to an active customer.
The panel shows the customer's assigned hosting accounts and resource pages.
Request forms are visible with their inputs disabled. The banner identifies
the customer and offers **End customer view**. Ending the view returns you
to your administrator account. Signing out ends the view and signs you out
of the panel.
A support session lasts up to 30 minutes and applies to the current browser
session. The panel checks that both users remain eligible on each request.
For example, suspending the customer or removing the administrator's
permission ends the view on the next request.
A staff user needs both **Can view customer** and **Can view the panel as a
customer**. The second permission is listed under **Customer impersonation
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.
## 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
@@ -1,8 +1,10 @@
from django.contrib import admin from django.contrib import admin
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.timezone import now
from .models import ( from .models import (
Customer, Customer,
CustomerImpersonation,
HostingAccount, HostingAccount,
HostingPlan, HostingPlan,
Reseller, Reseller,
@@ -75,6 +77,45 @@ class CustomerAdmin(admin.ModelAdmin):
search_fields = ("user__username",) search_fields = ("user__username",)
@admin.register(CustomerImpersonation)
class CustomerImpersonationAdmin(admin.ModelAdmin):
list_display = (
"operator_username",
"customer_username",
"started_at",
"expires_at",
"ended_at",
"outcome",
)
search_fields = ("operator_username", "customer_username")
fields = (
"operator_username",
"customer_username",
"started_at",
"expires_at",
"ended_at",
"outcome",
)
readonly_fields = fields
@admin.display(description="Outcome")
def outcome(self, obj):
if obj.ended_at is not None:
return obj.get_end_reason_display()
if obj.expires_at <= now():
return CustomerImpersonation.EndReason.EXPIRED.label
return "Open"
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(WebProvisioningPlan) @admin.register(WebProvisioningPlan)
class WebProvisioningPlanAdmin(admin.ModelAdmin): class WebProvisioningPlanAdmin(admin.ModelAdmin):
list_display = ( list_display = (
+129
View File
@@ -0,0 +1,129 @@
from datetime import timedelta
from django.middleware.csrf import rotate_token
from django.shortcuts import render
from django.utils import timezone
from django.utils.cache import add_never_cache_headers
from .access import is_tenant
from .models import CustomerImpersonation
SESSION_KEY = "customer_impersonation"
SESSION_DURATION = timedelta(minutes=30)
IMPERSONATE_CUSTOMER = (
"hosting.view_customer",
"hosting.impersonate_customer",
)
PREVIEW_VIEWS = frozenset(
{
"panel:accounts",
"panel:account",
"panel:database_create",
"panel:mailbox_create",
}
)
EndReason = CustomerImpersonation.EndReason
def can_impersonate_customer(user):
return (
user.is_authenticated
and user.is_active
and user.is_staff
and not is_tenant(user)
and user.has_perms(IMPERSONATE_CUSTOMER)
)
def start_impersonation(request, customer):
now = timezone.now()
session = CustomerImpersonation.objects.create(
operator=request.user,
customer=customer,
operator_username=request.user.get_username(),
customer_username=customer.user.get_username(),
started_at=now,
expires_at=now + SESSION_DURATION,
)
request.session[SESSION_KEY] = session.pk
rotate_token(request)
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,
)
request.session.pop(SESSION_KEY, None)
rotate_token(request)
class CustomerImpersonationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
had_preview = SESSION_KEY in request.session
response = self.get_response(request)
if had_preview or SESSION_KEY in request.session:
add_never_cache_headers(response)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
session_id = request.session.get(SESSION_KEY)
if session_id is None:
return None
view_name = request.resolver_match.view_name
signing_out = view_name == "panel:logout" and request.method == "POST"
session = (
CustomerImpersonation.objects.select_related(
"customer__user__hosting_reseller"
)
.filter(
pk=session_id,
operator_id=request.user.pk,
ended_at__isnull=True,
)
.first()
)
if session is None:
reason = EndReason.ACCESS_REVOKED
elif session.expires_at <= timezone.now():
reason = EndReason.EXPIRED
elif (
not can_impersonate_customer(request.user)
or session.customer is None
or not session.customer.may_be_impersonated
):
reason = EndReason.ACCESS_REVOKED
else:
reason = None
if signing_out:
end_impersonation(request, session, reason or EndReason.SIGNED_OUT)
return None
if reason is not None:
end_impersonation(request, session, reason)
# Block stale requests before restoring operator access.
return render(
request, "hosting/customer_preview_restricted.html", status=409
)
request.impersonation = session
if view_name == "panel:impersonation_stop":
return None
async def preview_user():
return session.customer.user
request.user = session.customer.user
request.auser = preview_user
if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS:
return None
return render(
request, "hosting/customer_preview_restricted.html", status=403
)
@@ -0,0 +1,80 @@
# Generated by Django 5.2.19 on 2026-11-21 01:18
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0016_mailbox_provisioning"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="CustomerImpersonation",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("operator_username", models.CharField(max_length=150)),
("customer_username", models.CharField(max_length=150)),
(
"started_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("expires_at", models.DateTimeField()),
("ended_at", models.DateTimeField(blank=True, null=True)),
(
"end_reason",
models.CharField(
blank=True,
choices=[
("stopped", "Ended by administrator"),
("signed_out", "Signed out"),
("expired", "Expired"),
("access_revoked", "Access revoked"),
],
max_length=16,
),
),
(
"customer",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="+",
to="hosting.customer",
),
),
(
"operator",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"verbose_name": "customer impersonation session",
"ordering": ("-started_at", "-pk"),
"permissions": (
(
"impersonate_customer",
"Can view the panel as a customer",
),
),
"default_permissions": ("view",),
},
),
]
+50
View File
@@ -56,6 +56,56 @@ class Customer(models.Model):
def __str__(self): def __str__(self):
return self.user.get_username() return self.user.get_username()
@property
def may_be_impersonated(self):
user = self.user
return (
user.is_active
and not user.is_staff
and not user.is_superuser
and not hasattr(user, "hosting_reseller")
)
class CustomerImpersonation(models.Model):
class EndReason(models.TextChoices):
STOPPED = "stopped", "Ended by administrator"
SIGNED_OUT = "signed_out", "Signed out"
EXPIRED = "expired", "Expired"
ACCESS_REVOKED = "access_revoked", "Access revoked"
operator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
related_name="+",
)
customer = models.ForeignKey(
Customer,
on_delete=models.SET_NULL,
null=True,
related_name="+",
)
operator_username = models.CharField(max_length=150)
customer_username = models.CharField(max_length=150)
started_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField()
ended_at = models.DateTimeField(null=True, blank=True)
end_reason = models.CharField(
max_length=16, choices=EndReason.choices, blank=True
)
class Meta:
ordering = ("-started_at", "-pk")
default_permissions = ("view",)
verbose_name = "customer impersonation session"
permissions = (
("impersonate_customer", "Can view the panel as a customer"),
)
def __str__(self):
return f"{self.operator_username} viewing as {self.customer_username}"
class HostingPlan(models.Model): class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True) name = models.CharField(max_length=120, unique=True)
@@ -450,6 +450,25 @@ dd {
background: #e7eee5; background: #e7eee5;
} }
.customer-preview, .table-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
}
.customer-preview {
justify-content: space-between;
border-color: var(--focus);
background: #f5ead6;
color: #6b431b;
overflow-wrap: anywhere;
}
.customer-preview p {
margin: 0.2rem 0 0;
}
.status { .status {
display: inline-block; display: inline-block;
padding: 0.18rem 0.55rem; padding: 0.18rem 0.55rem;
@@ -52,6 +52,18 @@
</div> </div>
</aside> </aside>
<main class="main" id="main-content"> <main class="main" id="main-content">
{% if request.impersonation %}
<section class="notice customer-preview" aria-label="Customer view">
<div>
<strong>Viewing as {{ request.impersonation.customer }}</strong>
<p>Read-only support session</p>
</div>
<form method="post" action="{% url 'panel:impersonation_stop' %}">
{% csrf_token %}
<button class="button secondary" type="submit">End customer view</button>
</form>
</section>
{% endif %}
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
</div> </div>
@@ -21,7 +21,7 @@
<tr> <tr>
<th scope="col">Username</th> <th scope="col">Username</th>
<th scope="col">Sign-in status</th> <th scope="col">Sign-in status</th>
{% if perms.hosting.change_customer %}<th scope="col">Actions</th>{% endif %} {% if perms.hosting.change_customer or can_impersonate %}<th scope="col">Actions</th>{% endif %}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -32,18 +32,26 @@
{% if customer.user.is_active %}<span class="status active">Active</span> {% if customer.user.is_active %}<span class="status active">Active</span>
{% else %}<span class="status suspended">Suspended</span>{% endif %} {% else %}<span class="status suspended">Suspended</span>{% endif %}
</td> </td>
{% if perms.hosting.change_customer %} {% if perms.hosting.change_customer or can_impersonate %}
<td> <td>
{% if not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} <div class="table-actions">
<form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}"> {% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
{% csrf_token %} <form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}">
{% if customer.user.is_active %} {% csrf_token %}
<button class="button secondary" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button> {% if customer.user.is_active %}
{% else %} <button class="button secondary" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button>
<button class="button secondary" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button> {% else %}
{% endif %} <button class="button secondary" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button>
</form> {% endif %}
{% endif %} </form>
{% endif %}
{% if can_impersonate and customer.may_be_impersonated %}
<form method="post" action="{% url 'panel:impersonation_start' customer.pk %}">
{% csrf_token %}
<button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button>
</form>
{% endif %}
</div>
</td> </td>
{% endif %} {% endif %}
</tr> </tr>
@@ -0,0 +1,20 @@
{% extends "hosting/base.html" %}
{% block title %}Customer view · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<div>
{% if request.impersonation %}
<h1>Unavailable in customer view</h1>
<p class="heading-meta">End the customer view to use your administrator account.</p>
{% else %}
<h1>Customer view ended</h1>
<p class="heading-meta">The session expired or access changed.</p>
{% endif %}
</div>
</header>
{% if not request.impersonation and perms.hosting.view_customer %}
<a class="button secondary" href="{% url 'panel:customers' %}">Back to customers</a>
{% else %}
<a class="button secondary" href="{% url 'panel:accounts' %}">Back to hosting accounts</a>
{% endif %}
{% endblock %}
@@ -8,7 +8,9 @@
{% csrf_token %} {% csrf_token %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
<button class="button primary" type="submit">Request database</button> {% if not request.impersonation %}
<button class="button primary" type="submit">Request database</button>
{% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
</div> </div>
</form> </form>
@@ -13,7 +13,9 @@
{% csrf_token %} {% csrf_token %}
{{ form.as_div }} {{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
<button class="button primary" type="submit">Request mailbox</button> {% if not request.impersonation %}
<button class="button primary" type="submit">Request mailbox</button>
{% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a> <a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
</div> </div>
</form> </form>
+270
View File
@@ -0,0 +1,270 @@
from datetime import timedelta
from django.conf import settings
from django.contrib.auth import SESSION_KEY as AUTH_SESSION_KEY
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import Client, TestCase
from django.urls import reverse
from django.utils import timezone
from .impersonation import SESSION_DURATION, SESSION_KEY
from .models import (
Customer,
CustomerImpersonation,
HostingAccount,
HostingDatabase,
HostingMailbox,
Reseller,
)
class CustomerImpersonationTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.support = users.create_user("support", is_staff=True)
cls.alice = users.create_user("alice")
cls.customer = Customer.objects.create(user=cls.alice)
cls.account = HostingAccount.objects.create(
name="Alice website",
primary_domain="alice.example",
customer=cls.customer,
)
cls.other_account = HostingAccount.objects.create(
name="Operator website", primary_domain="operator.example"
)
def setUp(self):
self.client.force_login(self.operator)
self.accounts = reverse("panel:accounts")
self.customers = reverse("panel:customers")
self.start_url = reverse(
"panel:impersonation_start", args=[self.customer.pk]
)
self.stop_url = reverse("panel:impersonation_stop")
def grant_support_permissions(self, user, *codenames):
user.user_permissions.add(
*Permission.objects.filter(
content_type__app_label="hosting", codename__in=codenames
)
)
def start_preview(self):
response = self.client.post(self.start_url)
self.assertRedirects(
response, self.accounts, fetch_redirect_response=False
)
self.assertIn("no-store", response.headers["Cache-Control"])
return CustomerImpersonation.objects.get(
pk=self.client.session[SESSION_KEY]
)
def test_reads_only_customer_accounts_and_keeps_operator_login(self):
preview = self.start_preview()
self.assertEqual(preview.operator, self.operator)
self.assertEqual(preview.customer, self.customer)
self.assertEqual(preview.operator_username, "operator")
self.assertEqual(preview.customer_username, "alice")
self.assertEqual(
preview.expires_at - preview.started_at, SESSION_DURATION
)
self.assertEqual(
self.client.session[AUTH_SESSION_KEY], str(self.operator.pk)
)
response = self.client.get(self.accounts)
self.assertContains(response, "Viewing as alice")
self.assertContains(response, "Read-only support session")
self.assertContains(response, self.account.name)
self.assertNotContains(response, self.other_account.name)
self.assertNotContains(response, "Add hosting account")
self.assertIn("no-store", response.headers["Cache-Control"])
self.assertEqual(response.wsgi_request.user, self.alice)
self.assertEqual(
self.client.get(self.other_account.get_absolute_url()).status_code,
404,
)
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"Request mailbox",
)
another_browser = Client()
another_browser.force_login(self.operator)
self.assertContains(
another_browser.get(self.accounts), self.other_account.name
)
def test_disables_resource_forms_and_rejects_writes(self):
self.start_preview()
for route, field in (
("panel:database_create", "suffix"),
("panel:mailbox_create", "local_part"),
):
with self.subTest(route=route):
url = reverse(route, args=[self.account.pk])
response = self.client.get(url)
self.assertTrue(
response.context["form"].fields[field].disabled
)
self.assertNotContains(response, 'class="button primary"')
self.assertContains(
self.client.post(url, {field: "support"}),
"Unavailable in customer view",
status_code=403,
)
self.assertFalse(HostingDatabase.objects.exists())
self.assertFalse(HostingMailbox.objects.exists())
for url in (reverse("admin:index"), self.customers, self.start_url):
with self.subTest(url=url):
method = "post" if url == self.start_url else "get"
self.assertContains(
getattr(self.client, method)(url),
"End customer view",
status_code=403,
)
self.assertEqual(CustomerImpersonation.objects.count(), 1)
def test_requires_staff_and_the_dedicated_permission(self):
self.grant_support_permissions(self.support, "view_customer")
self.client.force_login(self.support)
self.assertNotContains(
self.client.get(self.customers), "View as customer"
)
self.assertEqual(self.client.post(self.start_url).status_code, 403)
self.grant_support_permissions(self.support, "impersonate_customer")
self.assertContains(
self.client.get(self.customers), "View as customer alice"
)
self.start_preview()
self.assertRedirects(self.client.post(self.stop_url), self.customers)
Reseller.objects.create(user=self.support)
self.assertEqual(self.client.post(self.start_url).status_code, 403)
users = get_user_model().objects
users.filter(pk=self.support.pk).update(is_staff=False)
Reseller.objects.filter(user=self.support).delete()
self.assertEqual(self.client.post(self.start_url).status_code, 403)
def test_rejects_suspended_and_privileged_targets(self):
for flags in (
{"is_active": False},
{"is_staff": True},
{"is_superuser": True},
):
with self.subTest(flags=flags):
user = get_user_model().objects.create_user(
next(iter(flags)), **flags
)
customer = Customer.objects.create(user=user)
url = reverse("panel:impersonation_start", args=[customer.pk])
self.assertEqual(self.client.post(url).status_code, 404)
Reseller.objects.create(user=self.alice)
self.assertEqual(self.client.post(self.start_url).status_code, 404)
self.assertFalse(CustomerImpersonation.objects.exists())
def test_start_and_stop_require_post_with_csrf(self):
self.client = Client(enforce_csrf_checks=True)
self.client.force_login(self.operator)
self.client.get(self.customers)
csrf = settings.CSRF_COOKIE_NAME
token = self.client.cookies[csrf].value
self.assertEqual(self.client.get(self.start_url).status_code, 405)
self.assertEqual(self.client.post(self.start_url).status_code, 403)
self.assertEqual(
self.client.post(
self.start_url, HTTP_X_CSRFTOKEN=token
).status_code,
302,
)
preview_token = self.client.cookies[csrf].value
self.assertNotEqual(preview_token, token)
self.assertEqual(self.client.get(self.stop_url).status_code, 405)
self.assertEqual(self.client.post(self.stop_url).status_code, 403)
self.assertEqual(
self.client.post(
self.stop_url, HTTP_X_CSRFTOKEN=preview_token
).status_code,
302,
)
self.assertNotEqual(self.client.cookies[csrf].value, preview_token)
self.assertNotIn(SESSION_KEY, self.client.session)
self.assertContains(
self.client.get(self.accounts), self.other_account.name
)
expired = CustomerImpersonation.objects.get()
self.assertEqual(expired.end_reason, expired.EndReason.STOPPED)
self.assertIsNotNone(expired.ended_at)
def test_signing_out_closes_audit_and_operator_session(self):
preview = self.start_preview()
self.client.post(reverse("panel:logout"))
preview.refresh_from_db()
self.assertEqual(preview.end_reason, preview.EndReason.SIGNED_OUT)
self.assertNotIn(AUTH_SESSION_KEY, self.client.session)
self.assertNotIn(SESSION_KEY, self.client.session)
def test_expired_preview_does_not_execute_stale_operator_action(self):
preview = self.start_preview()
cutoff = timezone.now() - timedelta(seconds=1)
CustomerImpersonation.objects.filter(pk=preview.pk).update(
expires_at=cutoff
)
response = self.client.post(
reverse("panel:customer_access", args=[self.customer.pk]),
{"access": "suspend"},
)
self.assertContains(response, "Customer view ended", status_code=409)
self.alice.refresh_from_db()
self.assertTrue(self.alice.is_active)
preview.refresh_from_db()
self.assertEqual(preview.end_reason, preview.EndReason.EXPIRED)
self.assertEqual(preview.ended_at, cutoff)
self.assertNotIn(SESSION_KEY, self.client.session)
def test_suspending_customer_ends_preview_on_next_request(self):
preview = self.start_preview()
get_user_model().objects.filter(pk=self.alice.pk).update(
is_active=False
)
response = self.client.get(self.accounts)
self.assertContains(response, "Customer view ended", status_code=409)
self.assertNotContains(response, self.account.name, status_code=409)
preview.refresh_from_db()
self.assertEqual(preview.end_reason, preview.EndReason.ACCESS_REVOKED)
def test_revoking_operator_permission_ends_preview_on_next_request(self):
self.grant_support_permissions(
self.support, "view_customer", "impersonate_customer"
)
self.client.force_login(self.support)
preview = self.start_preview()
self.support.user_permissions.clear()
response = self.client.get(self.accounts)
self.assertContains(response, "Customer view ended", status_code=409)
preview.refresh_from_db()
self.assertEqual(preview.end_reason, preview.EndReason.ACCESS_REVOKED)
def test_session_marker_cannot_be_used_by_another_operator(self):
preview = self.start_preview()
other = Client()
other.force_login(self.support)
session = other.session
session[SESSION_KEY] = preview.pk
session.save()
self.assertEqual(other.get(self.accounts).status_code, 409)
self.assertNotIn(SESSION_KEY, other.session)
preview.refresh_from_db()
self.assertIsNone(preview.ended_at)
@@ -0,0 +1,74 @@
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .models import Customer, CustomerImpersonation
class CustomerImpersonationAuditTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.customer = Customer.objects.create(user=users.create_user("alice"))
cutoff = timezone.now() - timedelta(minutes=1)
cls.entry = CustomerImpersonation.objects.create(
operator=cls.operator,
customer=cls.customer,
operator_username="operator",
customer_username="alice",
started_at=cutoff - timedelta(minutes=30),
expires_at=cutoff,
)
def test_audit_list_requires_the_separate_view_permission(self):
auditor = get_user_model().objects.create_user(
"auditor", is_staff=True
)
auditor.user_permissions.add(
Permission.objects.get(
content_type__app_label="hosting",
codename="impersonate_customer",
)
)
self.client.force_login(auditor)
audit_url = reverse("admin:hosting_customerimpersonation_changelist")
self.assertEqual(self.client.get(audit_url).status_code, 403)
auditor.user_permissions.add(
Permission.objects.get(
content_type__app_label="hosting",
codename="view_customerimpersonation",
)
)
response = self.client.get(audit_url)
self.assertContains(response, "alice")
self.assertContains(response, "Expired")
def test_audit_retains_usernames_and_disallows_manual_edits(self):
self.customer.delete()
self.client.force_login(self.operator)
url = reverse(
"admin:hosting_customerimpersonation_change",
args=[self.entry.pk],
)
response = self.client.get(url)
self.assertContains(response, "alice")
self.assertNotContains(response, 'name="_save"')
self.assertEqual(self.client.post(url).status_code, 403)
for view, args in (
("admin:hosting_customerimpersonation_add", ()),
("admin:hosting_customerimpersonation_delete", (self.entry.pk,)),
):
with self.subTest(view=view):
self.assertEqual(
self.client.post(reverse(view, args=args)).status_code,
403,
)
self.entry.refresh_from_db()
self.assertIsNone(self.entry.customer)
self.assertEqual(self.entry.customer_username, "alice")
+10
View File
@@ -36,6 +36,16 @@ urlpatterns = [
views.CustomerAccess.as_view(), views.CustomerAccess.as_view(),
name="customer_access", name="customer_access",
), ),
path(
"customers/<int:pk>/view-as/",
views.CustomerImpersonationStart.as_view(),
name="impersonation_start",
),
path(
"customer-view/end/",
views.CustomerImpersonationStop.as_view(),
name="impersonation_stop",
),
path( path(
"accounts/<int:pk>/databases/new/", "accounts/<int:pk>/databases/new/",
views.DatabaseCreate.as_view(), views.DatabaseCreate.as_view(),
+40 -1
View File
@@ -38,6 +38,12 @@ from .access import (
) )
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 (
EndReason,
can_impersonate_customer,
end_impersonation,
start_impersonation,
)
from .models import ( from .models import (
Customer, Customer,
DatabaseProvisioning, DatabaseProvisioning,
@@ -273,7 +279,11 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
return queryset return queryset
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
return super().get_context_data(search=self.search, **kwargs) return super().get_context_data(
search=self.search,
can_impersonate=can_impersonate_customer(self.request.user),
**kwargs,
)
@method_decorator( @method_decorator(
@@ -324,6 +334,28 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect(reverse("panel:customers", query=request.GET)) return redirect(reverse("panel:customers", query=request.GET))
class CustomerImpersonationStart(PermissionRequiredMixin, View):
def has_permission(self):
return can_impersonate_customer(self.request.user)
def post(self, request, pk):
customers = Customer.objects.select_related("user__hosting_reseller")
customer = get_object_or_404(customers, pk=pk)
if not customer.may_be_impersonated:
raise Http404
start_impersonation(request, customer)
return redirect("panel:accounts")
class CustomerImpersonationStop(View):
def post(self, request):
session = getattr(request, "impersonation", None)
if session is not None:
end_impersonation(request, session, EndReason.STOPPED)
return redirect("panel:customers")
return redirect("panel:accounts")
class ResourceRequestCreate(PermissionRequiredMixin, CreateView): class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
@cached_property @cached_property
def customer(self): def customer(self):
@@ -345,6 +377,13 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
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, **kwargs)
def get_form(self, form_class=None):
form = super().get_form(form_class)
if getattr(self.request, "impersonation", None) is not None:
for field in form.fields.values():
field.disabled = True
return form
def form_valid(self, form): def form_valid(self, form):
try: try:
self.object = self.create_request( self.object = self.create_request(
+1
View File
@@ -43,6 +43,7 @@ MIDDLEWARE = [
"django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware", "django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware",
"coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
] ]
ROOT_URLCONF = "coulobre.urls" ROOT_URLCONF = "coulobre.urls"