Restore and extend operator customer impersonation #309

Merged
parkel merged 2 commits from fix/operator-impersonation into main 2026-12-04 15:20:47 +01:00
33 changed files with 551 additions and 88 deletions
Showing only changes of commit 9fb42d9625 - Show all commits

No files matched your search

+21 -1
View File
@@ -131,7 +131,27 @@ In `/admin/`, users with **Can view customer impersonation
session** can review the administrator, customer, timestamps, and outcome
for each session. The audit records are read-only in Django admin.
### Make changes during a support session
### Manage hosting on behalf of a customer
Grant **Can manage hosting as a customer** under **Customer impersonation
sessions**, in addition to the two customer view permissions. In the operator
workspace, open **Show All Users** and select **Manage as customer**. You can
use the customer's hosting tools for their assigned accounts, with the same
feature availability and package limits as the customer. This includes website
management, DNS, email, databases, SFTP, and backups where enabled.
The operator remains signed in. The support banner and **Leave impersonation**
stay available while managing hosting. Personal account settings, sign-in
credentials, MFA, existing service credential reveals, and SSO are not
delegated. Service password rotation, where enabled, requires the operator's
own password and the normal service credential permissions.
Managed hosting submissions are audited with the operator and customer
session, route, HTTP outcome, and numeric resource identifiers when available.
The audit does not include form values or credentials. A queued submission's
HTTP outcome is not its eventual execution result.
### Make limited changes during a support session
Grant **Can start a support session with write access** in addition to the
two customer view permissions. In the operator workspace, open the legacy
+2 -1
View File
@@ -104,7 +104,8 @@ heading, help, fields, and actions should share a left edge.
`<a href>` styled as a button. An action that submits the change uses a
native `<button type="submit">` in its existing POST form.
- Show only actions available in the active workspace. For example, give
operators a **Sign in as customer** row action and give managers direct
eligible operators **Sign in as customer** for a read-only preview and
**Manage as customer** for delegated hosting work. Give managers direct
actions for assigned hosting and invitations without impersonation.
- During impersonation, identify the customer and session mode in a
persistent banner. Replace the sidebar workspace switcher with **Leave
+6 -4
View File
@@ -58,13 +58,15 @@ def owns_customer_operations(user, account):
def panel_access(request):
from .impersonation import restricted_preview
customer = customer_for_user(request.user) is not None
reseller = not customer and reseller_for_user(request.user) is not None
from .mailbox_imports import PERMISSIONS as IMPORT_PERMISSIONS
from .mailbox_imports import available as mailbox_import_available
from .workspaces import (
CUSTOMER_ACCOUNT,
active_navigation,
customer_account_key,
groups_for,
workspace_accounts,
)
@@ -80,9 +82,9 @@ def panel_access(request):
),
"",
)
selected = request.session.get(CUSTOMER_ACCOUNT)
selected = request.session.get(customer_account_key(request))
available = []
if customer and not getattr(request, "impersonation", None):
if customer and not restricted_preview(request):
available = list(
workspace_accounts(request.user)
.only("id", "primary_domain")
@@ -102,7 +104,7 @@ def panel_access(request):
"workspace_selected": selected,
"mailbox_import_enabled": (
mailbox_import_available()
and not getattr(request, "impersonation", None)
and not restricted_preview(request)
and can_manage_hosting(request.user, IMPORT_PERMISSIONS)
),
}
@@ -25,7 +25,10 @@ from .access import OperatorOnlyMixin, reseller_for_user
from .account_metrics import customer_metrics
from .account_setup import setup_new_account
from .dns_defaults import zone_defaults
from .impersonation import can_impersonate_customer
from .impersonation import (
can_impersonate_customer,
can_start_managed_support,
)
from .installation_features import (
default_dns_zones_allowed,
panel_feature_allowed,
@@ -368,6 +371,7 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
)
actor = self.request.user
may_impersonate = can_impersonate_customer(actor)
context["may_manage_as_customer"] = can_start_managed_support(actor)
context["login_rows"] = [
(
login,
+2
View File
@@ -116,6 +116,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
"operator_username",
"customer_username",
"write_enabled",
"managed_enabled",
"started_at",
"expires_at",
"ended_at",
@@ -126,6 +127,7 @@ class CustomerImpersonationAdmin(admin.ModelAdmin):
"operator_username",
"customer_username",
"write_enabled",
"managed_enabled",
"started_at",
"expires_at",
"ended_at",
+11 -14
View File
@@ -31,7 +31,7 @@ from .service_credentials import (
CredentialMethod,
CredentialOutcome,
can_reveal_credentials,
can_rotate_credentials,
credential_actor,
enabled_credential_access,
enabled_rotation,
fetch_service_credentials,
@@ -39,6 +39,7 @@ from .service_credentials import (
reserve_rotation,
rotation_history,
rotation_ticket,
show_rotation_action,
verify_credential_access,
)
@@ -59,7 +60,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
def dispatch(self, request, *args, **kwargs):
if not self.access_enabled(request):
raise Http404
if getattr(request, "impersonation", None) is not None:
if not self.rotating and getattr(request, "impersonation", None):
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
@@ -75,10 +76,9 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
return response
def has_permission(self):
check = (
can_rotate_credentials if self.rotating else can_reveal_credentials
)
return check(self.request.user, self.kind)
if self.rotating:
return show_rotation_action(self.request, self.kind)
return can_reveal_credentials(self.request.user, self.kind)
def get_form_class(self):
if self.rotating:
@@ -98,7 +98,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
self.check_rotation_resource(self.resource, self.account)
form = self.get_form()
form.initial["ticket"] = rotation_ticket(
self.resource, self.account.pk, request.user.pk
self.resource, self.account.pk, credential_actor(request).pk
)
except ValidationError as error:
return self.rotation_problem(" ".join(error.messages), status=409)
@@ -128,11 +128,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
database=self.kind == CredentialKind.DATABASE,
**kwargs,
)
if (
not self.rotating
and enabled_rotation(self.request, self.kind)
and can_rotate_credentials(self.request.user, self.kind)
):
if not self.rotating and show_rotation_action(self.request, self.kind):
context["rotation_url"] = reverse(
f"panel:{self.kind}_credential_rotation",
args=[self.resource.pk],
@@ -149,6 +145,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
@sensitive_variables()
def form_valid(self, form):
actor = credential_actor(self.request)
rotation = None
if self.rotating:
try:
@@ -156,7 +153,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
form.cleaned_data["ticket"],
self.resource,
self.account.pk,
self.request.user,
actor,
)
except (BadSignature, ValueError):
return self.rotation_problem(
@@ -164,7 +161,7 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView):
status=409,
)
event = verify_credential_access(
self.request.user,
actor,
form.cleaned_data["password"],
kind=self.kind,
resource=str(self.resource),
+2 -1
View File
@@ -15,6 +15,7 @@ from django.views.decorators.http import (
from .access import customer_for_user
from .account_backups import queue_account_backup
from .credential_views import DatabaseCredentialView
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed
from .models import DatabaseLogin, HostingAccount, HostingDatabase
from .phpmyadmin import phpmyadmin_available
@@ -30,7 +31,7 @@ class AddDatabaseLoginForm(forms.Form):
def signed_in_customer(request):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
if customer is None or restricted_preview(request):
raise PermissionDenied
return customer
+3 -2
View File
@@ -16,6 +16,7 @@ from .account_setup import website_records
from .dns_defaults import zone_defaults
from .dns_forms import zone_record_rows
from .domain_policies import managed_mail_domains, policy_for
from .impersonation import restricted_preview
from .independent_websites import account_websites
from .installation_features import panel_feature_allowed
from .mailbox_imports import with_import_status
@@ -281,10 +282,10 @@ def domain_workspace(request, pk, page):
"customer_mailbox_quota": (
panel_feature_allowed(MAIL_PROVISIONING)
and customer_mailbox_quota_limit(account) is not None
and not getattr(request, "impersonation", None)
and not restricted_preview(request)
),
"roundcube_enabled": (
not getattr(request, "impersonation", None)
not restricted_preview(request)
and roundcube_available(request)
),
"mail_imap_host": settings.MAIL_IMAP_HOST,
+2 -1
View File
@@ -11,6 +11,7 @@ from coulobre.sftp_keys import normalize_public_keys
from coulobre.website_files import directory_parts
from .access import customer_for_user
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed
from .models import FolderSftpLogin, HostingAccount
from .resource_requests import (
@@ -94,7 +95,7 @@ def save_folder_login(account_id, customer_id, action, login, data):
@require_http_methods(("GET", "HEAD", "POST"))
def folder_sftp_users(request, pk):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
if customer is None or restricted_preview(request):
raise PermissionDenied
if not settings.LOCAL_WEB_SFTP:
raise Http404
+141 -18
View File
@@ -10,7 +10,8 @@ from django.utils import timezone
from django.utils.cache import add_never_cache_headers
from .access import PanelRole, is_tenant
from .models import CustomerImpersonation
from .models import CustomerImpersonation, CustomerImpersonationAction
from .panel_roles import scoped_user
from .sftp import MANAGE_SFTP_KEYS
SESSION_KEY = "customer_impersonation"
@@ -40,6 +41,66 @@ PREVIEW_VIEWS = frozenset(
"panel:mail_dns_check",
}
) | frozenset(CUSTOMER_WRITE_PERMISSIONS)
# Review customer hosting routes before adding them. Exclude account
# identity, credential reveals, SSO, and operator endpoints.
MANAGED_VIEWS = (
frozenset(
f"panel:{name}"
for name in [
"account_wordpress",
"customer_workspace",
"domain_workspace",
"system_workspace",
"website_usage",
"website_files",
"independent_website_files",
"website_jobs",
"website_job_create",
"website_job_edit",
"website_https",
"customer_certificates",
"site_php_settings",
"site_php_version",
"independent_php_settings",
"independent_website_create",
"independent_website_operation",
"website_alias_create",
"website_alias_action",
"customer_redirects",
"dns_zone_edit",
"dns_zone_publish",
"mail_dns_setup",
"mail_routing",
"mail_vacation",
"mail_spam",
"mail_delivery",
"mailbox_quota",
"mailbox_import",
"mailbox_removal",
"smtp_applications",
"mail_domain_alias",
"customer_databases",
"database_logins",
"database_export",
"folder_sftp_users",
"customer_backups",
"customer_restore",
"theme_stylesheet",
"user_stylesheet",
"mailbox_credential_rotation",
"database_credential_rotation",
]
)
| PREVIEW_VIEWS
)
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
def restricted_preview(request):
session = getattr(request, "impersonation", None)
return session is not None and not session.managed_enabled
EndReason = CustomerImpersonation.EndReason
@@ -58,9 +119,15 @@ def can_start_writable_support(user):
return can_impersonate_customer(user) and user.has_perm(WRITE_AS_CUSTOMER)
def can_start_managed_support(user):
return can_impersonate_customer(user) and user.has_perm(
"hosting.manage_as_customer"
)
def can_edit_customer_resource(request):
session = getattr(request, "impersonation", None)
if session is None:
if session is None or session.managed_enabled:
return True
permissions = CUSTOMER_WRITE_PERMISSIONS.get(
request.resolver_match.view_name
@@ -89,6 +156,10 @@ def support_write_session(request):
yield None
return
if session.managed_enabled:
yield None
return
if str(session.pk) != submitted_session or not can_edit_customer_resource(
request
):
@@ -118,7 +189,9 @@ def support_write_session(request):
yield current
def start_impersonation(request, customer, *, write_enabled=False):
def start_impersonation(
request, customer, *, write_enabled=False, managed_enabled=False
):
now = timezone.now()
session = CustomerImpersonation.objects.create(
operator=request.user,
@@ -126,6 +199,7 @@ def start_impersonation(request, customer, *, write_enabled=False):
operator_username=request.user.get_username(),
customer_username=customer.user.get_username(),
write_enabled=write_enabled,
managed_enabled=managed_enabled,
started_at=now,
expires_at=now + SESSION_DURATION,
)
@@ -146,6 +220,7 @@ def end_impersonation(request, session, reason):
end_reason=reason,
)
request.session.pop(SESSION_KEY, None)
request.session.pop("support_hosting_account", None)
rotate_token(request)
@@ -155,11 +230,43 @@ class CustomerImpersonationMiddleware:
def __call__(self, request):
had_preview = SESSION_KEY in request.session
response = self.get_response(request)
if had_preview and request.method not in SAFE_METHODS:
with transaction.atomic():
response = self.get_response(request)
if response.status_code == 500:
transaction.set_rollback(True)
elif session := getattr(
request, "managed_hosting_action", None
):
self.audit_hosting_action(request, session, response)
if response.status_code == 500 and (
session := getattr(request, "managed_hosting_action", None)
):
self.audit_hosting_action(request, session, response)
else:
response = self.get_response(request)
if had_preview or SESSION_KEY in request.session:
add_never_cache_headers(response)
return response
@staticmethod
def audit_hosting_action(request, session, response):
match = request.resolver_match
# Audit only the route and numeric IDs, never submitted values,
# query strings, filenames, or credentials.
identifiers = {
key: value
for key, value in match.kwargs.items()
if isinstance(value, int)
}
CustomerImpersonationAction.objects.create(
session=session,
hosting_account_id=identifiers.get("account_id"),
operation=CustomerImpersonationAction.Operation.HOSTING,
resource=match.url_name,
details={"ids": identifiers, "status": response.status_code},
)
def process_view(self, request, view_func, view_args, view_kwargs):
session_id = request.session.get(SESSION_KEY)
if session_id is None:
@@ -167,17 +274,21 @@ class CustomerImpersonationMiddleware:
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()
sessions = CustomerImpersonation.objects.select_related(
"customer__user__hosting_reseller"
).filter(
pk=session_id,
operator_id=request.user.pk,
ended_at__isnull=True,
)
mutating = request.method not in SAFE_METHODS
if mutating:
# Lock only the session row. The customer is nullable and is
# checked separately below.
locked = lock_session(sessions.select_related(None))
session = sessions.first() if locked is not None else None
else:
session = sessions.first()
if session is None:
reason = EndReason.ACCESS_REVOKED
elif session.expires_at <= timezone.now():
@@ -186,6 +297,8 @@ class CustomerImpersonationMiddleware:
not can_impersonate_customer(request.user)
or session.write_enabled
and not request.user.has_perm(WRITE_AS_CUSTOMER)
or session.managed_enabled
and not can_start_managed_support(request.user)
or session.customer is None
or not session.customer.may_be_impersonated
):
@@ -208,14 +321,24 @@ class CustomerImpersonationMiddleware:
if view_name == "panel:impersonation_stop":
return None
async def preview_user():
return session.customer.user
request.active_panel_role = PanelRole.CUSTOMER
request.user = scoped_user(session.customer.user, PanelRole.CUSTOMER)
async def preview_user():
return request.user
request.user = session.customer.user
request.auser = preview_user
if session.managed_enabled and view_name in MANAGED_VIEWS:
if mutating:
request.managed_hosting_action = session
return None
if request.method in ("GET", "HEAD") and view_name in PREVIEW_VIEWS:
return None
if request.method == "POST" and can_edit_customer_resource(request):
if (
not session.managed_enabled
and request.method == "POST"
and can_edit_customer_resource(request)
):
return None
return render(
request, "hosting/customer_preview_restricted.html", status=403
@@ -8,6 +8,7 @@ from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from .access import can_manage_hosting, customer_for_user
from .impersonation import restricted_preview
from .mail_domain_aliases import (
aliases_available,
queue_domain_alias,
@@ -24,7 +25,7 @@ PERMISSIONS = (
def may_manage_aliases(request):
return (
aliases_available()
and not getattr(request, "impersonation", None)
and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS)
)
+3 -2
View File
@@ -26,6 +26,7 @@ from .access import (
owns_customer_operations,
reseller_for_user,
)
from .impersonation import restricted_preview
from .mail_policies import (
mail_policy_available,
policy_account,
@@ -53,7 +54,7 @@ VIEW_PERMISSIONS = (
def mail_policy_enabled(request, kind):
return (
mail_policy_available(kind)
and getattr(request, "impersonation", None) is None
and not restricted_preview(request)
and can_manage_hosting(
request.user, (*VIEW_PERMISSIONS, POLICY_PERMISSIONS[kind])
)
@@ -210,7 +211,7 @@ class MailPolicyEditor(
def has_permission(self):
return (
reseller_for_user(self.request.user) is None
and getattr(self.request, "impersonation", None) is None
and not restricted_preview(self.request)
and super().has_permission()
)
+2 -1
View File
@@ -18,6 +18,7 @@ from coulobre.imap_import import MailboxImportError, source_hostname
from . import mailbox_import_preview as preview
from .access import can_manage_hosting, customer_for_user
from .impersonation import restricted_preview
from .mailbox_imports import PERMISSIONS, available, display_name, queue_import
from .models import HostingMailbox, MailboxImport
@@ -62,7 +63,7 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
def has_permission(self):
return (
available()
and not getattr(self.request, "impersonation", None)
and not restricted_preview(self.request)
and can_manage_hosting(self.request.user, PERMISSIONS)
)
+2 -1
View File
@@ -17,6 +17,7 @@ from coulobre.mail_policy import parse_mail_policy
from .access import can_manage_hosting, customer_for_user
from .domain_policies import require_managed
from .impersonation import restricted_preview
from .models import HostingAccount, HostingMailbox, MailboxRemoval
from .node_client import apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services
@@ -32,7 +33,7 @@ PERMISSIONS = ("hosting.view_hostingmailbox", "hosting.delete_hostingmailbox")
def can_remove_mailbox(request):
return (
settings.LOCAL_MAILBOX_PROVISIONING
and getattr(request, "impersonation", None) is None
and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS)
)
@@ -0,0 +1,56 @@
# Generated by Django 5.2.19 on 2026-12-04 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0098_mailbox_import_preview"),
]
operations = [
migrations.AlterModelOptions(
name="customerimpersonation",
options={
"default_permissions": ("view",),
"ordering": ("-started_at", "-pk"),
"permissions": (
("manage_as_customer", "Can manage hosting as a customer"),
(
"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="managed_enabled",
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name="customerimpersonationaction",
name="hosting_account_id",
field=models.PositiveBigIntegerField(null=True),
),
migrations.AlterField(
model_name="customerimpersonationaction",
name="operation",
field=models.CharField(
choices=[
("hosting", "Customer hosting action"),
("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,
),
),
]
+4 -1
View File
@@ -245,6 +245,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)
managed_enabled = models.BooleanField(default=False)
started_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField()
ended_at = models.DateTimeField(null=True, blank=True)
@@ -257,6 +258,7 @@ class CustomerImpersonation(models.Model):
default_permissions = ("view",)
verbose_name = "customer impersonation session"
permissions = (
("manage_as_customer", "Can manage hosting as a customer"),
("impersonate_customer", "Can view the panel as a customer"),
(
"write_as_customer",
@@ -270,6 +272,7 @@ class CustomerImpersonation(models.Model):
class CustomerImpersonationAction(models.Model):
class Operation(models.TextChoices):
HOSTING = "hosting", "Customer hosting action"
DATABASE = "database", "Requested database"
MAILBOX = "mailbox", "Requested mailbox"
ADD_KEYS = "add_keys", "Queued SSH key upload"
@@ -279,7 +282,7 @@ class CustomerImpersonationAction(models.Model):
session = models.ForeignKey(
CustomerImpersonation, on_delete=models.PROTECT, related_name="actions"
)
hosting_account_id = models.PositiveBigIntegerField()
hosting_account_id = models.PositiveBigIntegerField(null=True)
operation = models.CharField(max_length=16, choices=Operation.choices)
resource = models.CharField(max_length=254)
details = models.JSONField(default=dict)
+2 -1
View File
@@ -5,6 +5,7 @@ from django.db import transaction
from coulobre.php_runtime import available_php_versions
from .access import customer_for_user, is_tenant
from .impersonation import restricted_preview
from .models import SitePhpVersion, WebActivation
from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account, require_active_services
@@ -27,7 +28,7 @@ class SitePhpVersionForm(forms.Form):
def can_change_php_version(request):
user = request.user
return getattr(request, "impersonation", None) is None and (
return not restricted_preview(request) and (
customer_for_user(user) is not None
or (not is_tenant(user) and user.has_perms(CHANGE_PHP_VERSION))
)
+2 -1
View File
@@ -17,6 +17,7 @@ from coulobre.web_redirects import (
from .access import customer_for_user
from .certificate_views import account_certificate_sites
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias, WebsiteRedirectPolicy
from .resource_requests import lock_hosting_account, require_active_services
@@ -137,7 +138,7 @@ def request_redirect_change(
@require_http_methods(("GET", "HEAD", "POST"))
def customer_redirects(request, pk):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
if customer is None or restricted_preview(request):
raise PermissionDenied
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404
+13 -4
View File
@@ -121,11 +121,20 @@ def show_credential_action(request, kind):
)
def credential_actor(request):
return getattr(request, "support_operator", request.user)
def show_rotation_action(request, kind):
return (
getattr(request, "impersonation", None) is None
and enabled_rotation(request, kind)
and can_rotate_credentials(request.user, kind)
session = getattr(request, "impersonation", None)
if session is not None and not (
session.managed_enabled
and credential_actor(request).has_perms(CREDENTIAL_PERMISSIONS[kind])
and credential_actor(request).has_perm(ROTATION_PERMISSIONS[kind])
):
return False
return enabled_rotation(request, kind) and can_rotate_credentials(
request.user, kind
)
+2 -1
View File
@@ -20,6 +20,7 @@ from coulobre.smtp_application import SmtpApplicationRequest
from .access import can_manage_hosting, customer_for_user
from .domain_policies import require_managed
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed
from .mail_dns_setup import sync_mail_dns
from .models import HostingAccount, HostingMailDomain, SmtpApplication
@@ -41,7 +42,7 @@ def smtp_applications_available(request):
and settings.MAIL_SUBMISSION_HOST
and request.is_secure()
and not settings.DEBUG
and getattr(request, "impersonation", None) is None
and not restricted_preview(request)
and can_manage_hosting(request.user, PERMISSIONS)
)
@@ -168,6 +168,9 @@
{% if show_database_credentials %}
<a class="button secondary compact" href="{% url 'panel:database_credentials' database.pk %}" aria-label="Connection details for {{ database }}">Connection details</a>
{% endif %}
{% if show_database_rotation and database.provisioning.state == "configured" %}
<a class="button secondary compact" href="{% url 'panel:database_credential_rotation' database.pk %}" aria-label="Change password for {{ database }}">Change password</a>
{% endif %}
{% if show_phpmyadmin %}
<form method="post" action="{% url 'panel:phpmyadmin_launch' database.pk %}">
{% csrf_token %}
@@ -33,6 +33,12 @@
{% if has_user_actions %}
<td>
<div class="table-actions">
{% if may_impersonate and may_manage_as_customer %}
<form method="post" action="{% url 'panel:impersonation_managed_start' login.hosting_customer.pk %}">
{% csrf_token %}
<button class="button secondary compact" type="submit" aria-label="Manage hosting as {{ login.get_username }}">Manage as customer</button>
</form>
{% endif %}
{% if may_impersonate %}
<form method="post" action="{% url 'panel:impersonation_start' login.hosting_customer.pk %}">
{% csrf_token %}
@@ -83,7 +83,9 @@
{% if request.impersonation %}
<section class="notice customer-preview" aria-label="Customer view">
<strong>Viewing as {{ request.impersonation.customer }}</strong>
{% if request.impersonation.write_enabled %}
{% if request.impersonation.managed_enabled %}
<p>Managing customer hosting · {{ request.impersonation.operator_username }}</p>
{% elif request.impersonation.write_enabled %}
<p>Support session with write access · {{ request.impersonation.operator_username }}</p>
{% else %}
<p>Read-only support session</p>
@@ -3,7 +3,7 @@
{% block page_title %}SSL Certificates{% endblock %}
{% block page_metadata %}<p class="heading-meta">{{ account.primary_domain }}</p>{% endblock %}
{% block page_actions %}
{% if not request.impersonation %}<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">HTTPS by hostname</a>{% endif %}
{% if not request.impersonation or request.impersonation.managed_enabled %}<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">HTTPS by hostname</a>{% endif %}
{% endblock %}
{% block page_tabs %}
{% if sites %}
@@ -13,7 +13,7 @@
<a class="quiet-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
{% endblock %}
{% block page_content %}
{% if not request.impersonation %}
{% if not request.impersonation or request.impersonation.managed_enabled %}
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
+200 -2
View File
@@ -1,10 +1,11 @@
from datetime import timedelta
from unittest.mock import patch
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.test import Client, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
@@ -15,8 +16,12 @@ from .models import (
CustomerImpersonation,
HostingAccount,
HostingDatabase,
HostingDnsZone,
HostingMailbox,
HostingMailDomain,
MailboxProvisioning,
Reseller,
ServiceCredentialAccess,
)
@@ -67,6 +72,193 @@ class CustomerImpersonationTests(TestCase):
pk=self.client.session[SESSION_KEY]
)
def start_managed(self):
url = reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
)
response = self.client.post(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_managed_session_can_make_customer_changes_and_audits_them(self):
self.assertContains(
self.client.get(self.all_users), "Manage as customer"
)
support = self.start_managed()
self.assertTrue(support.managed_enabled)
page = self.client.get(self.accounts)
self.assertContains(page, "Managing customer hosting")
self.assertNotContains(page, "Add hosting account")
self.assertNotContains(page, self.other_account.name)
self.assertContains(page, "Leave impersonation")
url = reverse("panel:database_create", args=[self.account.pk])
other = reverse("panel:database_create", args=[self.other_account.pk])
self.assertNotEqual(
self.client.post(other, {"suffix": "denied"}).status_code, 302
)
form = self.client.get(url).context["form"]
self.assertFalse(form.fields["suffix"].disabled)
response = self.client.post(url, {"suffix": "application"})
self.assertEqual(response.status_code, 302)
self.assertTrue(
self.account.databases.filter(suffix="application").exists()
)
self.assertFalse(self.other_account.databases.exists())
action = support.actions.get(details__status=302)
self.assertEqual(action.resource, "database_create")
self.assertEqual(
action.details,
{
"ids": {"pk": self.account.pk},
"status": 302,
},
)
self.assertRedirects(self.client.post(self.stop_url), self.all_users)
self.assertEqual(
self.client.session[AUTH_SESSION_KEY], str(self.operator.pk)
)
def test_managed_dns_edit_respects_customer_delegation(self):
zone = HostingDnsZone.objects.create(
account=self.account,
domain=self.account.primary_domain,
nameservers=["ns.provider.example"],
responsible_name="hostmaster.alice.example",
)
self.start_managed()
show = reverse("panel:dns_zone_edit", args=[zone.pk])
self.assertEqual(self.client.get(show).status_code, 403)
zone.delegate_dns = True
zone.save(update_fields=["delegate_dns"])
self.assertEqual(self.client.get(show).status_code, 200)
self.assertRedirects(
self.client.post(
show,
{
"serial": zone.serial,
"nameservers": "ns.unapproved.example",
"addresses": "alice.example 192.0.2.1",
},
),
self.account.get_absolute_url(),
)
zone.refresh_from_db()
self.assertEqual(zone.nameservers, ["ns.provider.example"])
self.assertEqual(len(zone.addresses), 1)
def test_managed_session_denies_account_identity_and_operator_changes(
self,
):
self.start_managed()
for name, args in (
("panel:account_security", []),
("panel:account_password", []),
("panel:account_authenticator", []),
("panel:all_users", []),
("panel:account_edit", [self.account.pk]),
("panel:impersonation_start", [self.customer.pk]),
("panel:switch_panel_role", []),
):
with self.subTest(route=name):
url = reverse(name, args=args)
self.assertEqual(self.client.get(url).status_code, 403)
self.assertEqual(self.client.post(url).status_code, 403)
def test_managed_permission_is_separate_and_revocation_ends_session(self):
self.grant_support_permissions(
self.support,
"view_customer",
"impersonate_customer",
"write_as_customer",
)
self.client.force_login(self.support)
start = reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
)
self.assertNotContains(self.client.get(self.all_users), start)
self.assertEqual(self.client.post(start).status_code, 403)
self.grant_support_permissions(self.support, "manage_as_customer")
managed = self.start_managed()
self.support.user_permissions.remove(
Permission.objects.get(codename="manage_as_customer")
)
self.assertEqual(
self.client.post(
reverse("panel:database_create", args=[self.account.pk]),
{"suffix": "denied"},
).status_code,
409,
)
managed.refresh_from_db()
self.assertEqual(managed.end_reason, managed.EndReason.ACCESS_REVOKED)
self.assertFalse(self.account.databases.exists())
@override_settings(
LOCAL_MAILBOX_PROVISIONING=True,
MAILBOX_PASSWORD_CHANGES=True,
REMOTE_MAILBOX_CREDENTIALS=True,
REMOTE_MAILBOX_CREDENTIAL_ROTATION=True,
)
def test_managed_mailbox_rotation_requires_operator_password(self):
self.operator.set_password("operator-password")
self.operator.save(update_fields=["password"])
self.alice.set_password("customer-password")
self.alice.save(update_fields=["password"])
self.client.force_login(self.operator)
domain = HostingMailDomain.objects.create(
account=self.account, domain=self.account.primary_domain
)
mailbox = HostingMailbox.objects.create(
mail_domain=domain, local_part="support"
)
MailboxProvisioning.objects.create(
mailbox=mailbox, finished_at=timezone.now()
)
self.start_managed()
self.assertEqual(
self.client.get(
reverse("panel:mailbox_credentials", args=[mailbox.pk])
).status_code,
403,
)
url = reverse("panel:mailbox_credential_rotation", args=[mailbox.pk])
with patch(
"coulobre.hosting.service_credentials.apply_on_local_node",
side_effect=[
{"generation": None},
{
"user": str(mailbox),
"password": "new-mailbox-password",
},
],
) as node:
page = self.client.get(url, secure=True)
self.assertEqual(page.status_code, 200)
ticket = page.context["form"]["ticket"].value()
result = self.client.post(
url,
{"ticket": ticket, "password": "customer-password"},
secure=True,
)
self.assertContains(result, "Enter your current panel password.")
self.assertEqual(node.call_count, 1)
result = self.client.post(
url,
{"ticket": ticket, "password": "operator-password"},
secure=True,
)
self.assertContains(result, "new-mailbox-password")
self.assertIn("no-store", result.headers["Cache-Control"])
self.assertEqual(
ServiceCredentialAccess.objects.get(outcome="rotated").actor,
self.operator,
)
def test_operator_starts_from_all_users_and_leaves_in_sidebar(self):
response = self.client.get(self.all_users)
self.assertContains(response, f'action="{self.start_url}"', count=1)
@@ -128,7 +320,13 @@ class CustomerImpersonationTests(TestCase):
self.client.get(self.accounts, {"customer": self.customer.pk}),
self.account.name,
)
for route in (self.start_url, self.write_start_url):
for route in (
self.start_url,
self.write_start_url,
reverse(
"panel:impersonation_managed_start", args=[self.customer.pk]
),
):
self.assertEqual(self.client.post(route).status_code, 403)
def test_operator_cannot_impersonate_in_another_workspace(self):
+5
View File
@@ -685,6 +685,11 @@ urlpatterns = [
views.CustomerImpersonationStart.as_view(write_enabled=True),
name="impersonation_write_start",
),
path(
"customers/<int:pk>/manage-as/",
views.CustomerImpersonationStart.as_view(managed_enabled=True),
name="impersonation_managed_start",
),
path(
"customer-view/end/",
views.CustomerImpersonationStop.as_view(),
+25 -19
View File
@@ -89,8 +89,10 @@ from .impersonation import (
EndReason,
can_edit_customer_resource,
can_impersonate_customer,
can_start_managed_support,
can_start_writable_support,
end_impersonation,
restricted_preview,
start_impersonation,
support_write_session,
)
@@ -699,7 +701,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
)
context["manage_wordpress"] = wordpress_available() and (
getattr(self.request, "impersonation", None) is None
not restricted_preview(self.request)
and can_manage_wordpress(user, self.object)
)
context["manage_website_jobs"] = can_access_website_jobs(
@@ -715,7 +717,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
website_provisioning
and not self.object.services_suspended
and can_manage_hosting(user, (CHANGE_ACCOUNTS,))
and getattr(self.request, "impersonation", None) is None
and not restricted_preview(self.request)
)
context["independent_websites"] = [
(website, website_actions(website) if can_manage else ())
@@ -893,6 +895,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
"apache_config"
).order_by("-requested_at", "-pk")
context["apache_history"] = list(history[:10])
context["show_mailbox_rotation"] = show_rotation_action(
self.request, CredentialKind.MAILBOX
)
context["show_database_rotation"] = getattr(
self.request, "impersonation", None
) is not None and show_rotation_action(
self.request, CredentialKind.DATABASE
)
if getattr(self.request, "impersonation", None) is None:
context["show_database_credentials"] = show_credential_action(
self.request, CredentialKind.DATABASE
@@ -900,9 +910,6 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["show_mailbox_credentials"] = show_credential_action(
self.request, CredentialKind.MAILBOX
)
context["show_mailbox_rotation"] = show_rotation_action(
self.request, CredentialKind.MAILBOX
)
context["show_phpmyadmin"] = context[
"show_database_credentials"
] and phpmyadmin_available(self.request)
@@ -926,10 +933,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["databases"] = databases
if tenant or user.has_perm(VIEW_DNS_ZONES):
zone_list = self.object.dns_zones.all()
if (
customer
and getattr(self.request, "impersonation", None) is None
):
if customer and not restricted_preview(self.request):
zone_list = zone_list.select_related("publication").defer(
"publication__manifest"
)
@@ -1060,9 +1064,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["change_mailbox_quota"] = (
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
)
elif customer is not None and not getattr(
self.request, "impersonation", None
):
elif customer is not None and not restricted_preview(self.request):
context["customer_mailbox_quota"] = (
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and customer_mailbox_quota_limit(self.object) is not None
@@ -2096,8 +2098,11 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
class CustomerImpersonationStart(PermissionRequiredMixin, View):
write_enabled = False
managed_enabled = False
def has_permission(self):
if self.managed_enabled:
return can_start_managed_support(self.request.user)
if self.write_enabled:
return can_start_writable_support(self.request.user)
return can_impersonate_customer(self.request.user)
@@ -2108,7 +2113,10 @@ class CustomerImpersonationStart(PermissionRequiredMixin, View):
if not customer.may_be_impersonated:
raise Http404
start_impersonation(
request, customer, write_enabled=self.write_enabled
request,
customer,
write_enabled=self.write_enabled,
managed_enabled=self.managed_enabled,
)
return redirect("panel:accounts")
@@ -2438,7 +2446,7 @@ class DnsZoneEdit(DnsZoneEditor):
if reseller_for_user(self.request.user) is not None:
return False
if is_tenant(self.request.user):
return getattr(self.request, "impersonation", None) is None and (
return not restricted_preview(self.request) and (
self.zone.delegate_dns
and manages_account(self.request.user, self.account)
)
@@ -2588,7 +2596,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View):
if reseller_for_user(self.request.user) is not None:
return False
if is_tenant(self.request.user):
return getattr(self.request, "impersonation", None) is None
return not restricted_preview(self.request)
return super().has_permission()
def post(self, request, pk):
@@ -2628,9 +2636,7 @@ class MailboxCreate(ResourceRequestCreate):
domain = self.request.GET.get("domain")
if domain is None:
return None
if self.customer is None or getattr(
self.request, "impersonation", None
):
if self.customer is None or restricted_preview(self.request):
raise Http404
from .domain_policies import managed_mail_domains
from .domain_services import allowed_domains
@@ -2702,7 +2708,7 @@ class MailboxQuotaEdit(PermissionRequiredMixin, UpdateView):
return customer_for_user(self.request.user)
def has_permission(self):
if getattr(self.request, "impersonation", None):
if restricted_preview(self.request):
return False
if self.customer is not None:
return panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
+2 -1
View File
@@ -24,6 +24,7 @@ from .access import (
can_manage_hosting,
owns_customer_operations,
)
from .impersonation import restricted_preview
from .independent_websites import active_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount
@@ -39,7 +40,7 @@ def can_manage_website_files(request):
user = request.user
return (
panel_feature_allowed("WEB_FILE_MANAGER")
and getattr(request, "impersonation", None) is None
and not restricted_preview(request)
and can_manage_hosting(user, MANAGE_FILES)
)
+2 -1
View File
@@ -16,6 +16,7 @@ from coulobre.domain_names import canonical_domain
from .access import customer_for_user, is_tenant
from .certificate_views import account_certificate_sites, queue_certificate
from .dns_forms import record_rows
from .impersonation import restricted_preview
from .independent_websites import account_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias
@@ -48,7 +49,7 @@ NOT_MAPPED = HostStatus("", "Not mapped to a website")
def may_manage_https(request, account):
if getattr(request, "impersonation", None):
if restricted_preview(request):
return False
customer = customer_for_user(request.user)
if customer is not None:
+2 -1
View File
@@ -20,6 +20,7 @@ from .access import (
can_manage_hosting,
owns_customer_operations,
)
from .impersonation import restricted_preview
from .independent_websites import check_actor
from .installation_features import panel_feature_allowed
from .models import HostingAccount
@@ -35,7 +36,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
def can_access_website_jobs(request):
impersonating = getattr(request, "impersonation", None) is not None
impersonating = restricted_preview(request)
return not impersonating and can_manage_hosting(request.user, MANAGE_JOBS)
+2 -1
View File
@@ -14,6 +14,7 @@ from coulobre.wordpress_import import inspect_export
from coulobre.wordpress_updates import WordPressUpdate
from .access import TenantScopeMixin, customer_for_user, is_tenant
from .impersonation import restricted_preview
from .installation_features import panel_feature_allowed
from .models import HostingAccount
from .wordpress_import_workflow import (
@@ -136,7 +137,7 @@ class AccountWordPressView(
def has_permission(self):
return (
not getattr(self.request, "impersonation", None)
not restricted_preview(self.request)
and super().has_permission()
and can_manage_wordpress(self.request.user, self.get_object())
)
+16 -4
View File
@@ -147,6 +147,12 @@ def customer_pages(request):
return pages
def customer_account_key(request):
if getattr(request, "impersonation", None):
return "support_hosting_account"
return CUSTOMER_ACCOUNT
@require_safe
@never_cache
def customer_workspace(request, page):
@@ -165,10 +171,10 @@ def customer_workspace(request, page):
):
raise Http404
account = get_object_or_404(accounts, pk=int(selected))
request.session[CUSTOMER_ACCOUNT] = account.pk
request.session[customer_account_key(request)] = account.pk
else:
account = accounts.filter(
pk=request.session.get(CUSTOMER_ACCOUNT)
pk=request.session.get(customer_account_key(request))
).first()
account = account or accounts.first()
if account is None:
@@ -336,7 +342,9 @@ def groups_for(request, *, customer, manager):
user = request.user
if not user.is_authenticated:
return ()
if getattr(request, "impersonation", None):
from .impersonation import restricted_preview
if restricted_preview(request):
return (("Account Manager", [link("accounts", "My hosting")]),)
if customer:
pages = customer_pages(request)
@@ -378,7 +386,11 @@ def groups_for(request, *, customer, manager):
"Advanced Features",
[
*hosted("backups", "tasks"),
link("account_security", "Security"),
*(
[]
if getattr(request, "impersonation", None)
else [link("account_security", "Security")]
),
],
),
]