:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(admin): make user deletion complete instead of timing out (#82731)
Yasen97f6f9a32f69
diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.pyindex 45b1989d9473..8e14f7871197 100644--- a/posthog/admin/admins/user_admin.py+++ b/posthog/admin/admins/user_admin.py@@ -1,14 +1,21 @@import datetime-from typing import Any+import dataclasses+from collections.abc import Iterable+from typing import Any, castfrom django.contrib import admin, messages+from django.contrib.admin.models import DELETION, LogEntryfrom django.contrib.auth.admin import UserAdmin as DjangoUserAdminfrom django.contrib.auth.forms import (ReadOnlyPasswordHashWidget as DjangoReadOnlyPasswordHashWidget,UserChangeForm as DjangoUserChangeForm,)from django.core.exceptions import ValidationError-from django.http import HttpResponseRedirect+from django.db.models import CASCADE, PROTECT, RESTRICT, Model+from django.db.models.deletion import get_candidate_relations_to_delete+from django.db.models.fields.related import ForeignObject+from django.db.models.fields.reverse_related import ForeignObjectRel+from django.http import HttpRequest, HttpResponseRedirectfrom django.urls import reversefrom django.utils.html import format_htmlfrom django.utils.translation import (@@ -26,7 +33,15 @@ from posthog.admin.inlines.user_social_auth_inline import UserSocialAuthInlinefrom posthog.api.authentication import password_reset_token_generatorfrom posthog.api.email_verification import EmailVerifierfrom posthog.api.two_factor_reset import TwoFactorResetVerifier+from posthog.dataclasses import frozen+from posthog.helpers.impersonation import get_impersonated_user, is_impersonatedfrom posthog.models import User+from posthog.models.activity_logging.activity_log import (+ ActivityContextBase,+ Detail,+ LogActivityEntry,+ bulk_log_activity,+)from posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.session.activity import revoke_other_sessionsfrom posthog.tasks.email import send_password_reset, send_two_factor_reset_email@@ -34,6 +49,12 @@ from posthog.tasks.email import send_password_reset, send_two_factor_reset_email# Django's default widget masks salt/hash but still shows their first few characters; keep those out of the admin entirely._HIDDEN_SUMMARY_LABELS = {"salt", "hash", "checksum"}+# Every relation is counted with its own capped query, so this bounds how much of a table the+# confirmation page reads. The exact figure past the cap doesn't change the operator's decision.+DELETION_SUMMARY_COUNT_CAP = 100++DELETION_REASON_FIELD = "deletion_reason"+class ReadOnlyPasswordHashWidget(DjangoReadOnlyPasswordHashWidget):def get_context(self, name: str, value: str | None, attrs: dict[str, Any] | None) -> dict[str, Any]:@@ -43,6 +64,25 @@ class ReadOnlyPasswordHashWidget(DjangoReadOnlyPasswordHashWidget):return context[email protected](frozen=True)+class UserDeletionActivityContext(ActivityContextBase):+ reason: str+ # The item_id of the log entry points at a row that no longer exists, so the address the+ # account was deleted under is the only thing that identifies it afterwards.+ email: str+++@frozen+class _CascadeSummary:+ counts: dict[str, str]+ perms_needed: set[str]+ protected: list[str]+++def _deletion_reason(request: HttpRequest) -> str:+ return request.POST.get(DELETION_REASON_FIELD, "").strip()++class UserChangeForm(DjangoUserChangeForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -282,6 +322,169 @@ class UserAdmin(DjangoUserAdmin):return super().change_view(request, object_id, form_url, extra_context)+ def has_delete_permission(self, request, obj=None):+ if self._is_acting_as(request, obj):+ return False+ return super().has_delete_permission(request, obj)++ def _is_acting_as(self, request: HttpRequest, obj: User | None) -> bool:+ # Deleting the account you're acting as would end the session mid-request, and the+ # deletion's own activity log entries record the actor by foreign key, which the cascade+ # would take out from under them.+ if obj is None:+ return False+ if obj.pk == request.user.pk:+ return True+ # On `/admin/` paths `AdminImpersonationMiddleware` swaps `request.user` back to the staff+ # operator, so the impersonated account passes the check above while its session is the one+ # the delete would break. `get_impersonated_user` reads the session instead of `request.user`.+ impersonated = get_impersonated_user(request)+ return impersonated is not None and obj.pk == impersonated.pk++ def get_actions(self, request):+ actions = super().get_actions(request)+ # Bulk delete has nowhere to ask for a reason, and it would collect the cascade for every+ # selected account into one page.+ actions.pop("delete_selected", None)+ return actions++ def get_deleted_objects(self, objs, request):+ # Django builds this page with NestedObjects, which loads every row that cascades from the+ # user and renders a list item per row. Recorded views alone (session recordings, insights,+ # file tree entries) reach into the millions on a long-lived account, so both the+ # confirmation page and the POST that re-collects them time out before anything is deleted.+ # A capped count per relation answers the same question for the operator in bounded work.+ summary = self._cascade_summary(objs, request)+ return [], summary.counts, summary.perms_needed, summary.protected++ def _cascade_summary(self, objs: list[User], request: HttpRequest) -> _CascadeSummary:+ counts: list[tuple[str, int]] = []+ perms_needed: set[str] = set()+ protected: list[str] = []+ # The same relations Django's own collector walks. `User._meta.related_objects` drops the+ # ones declared with `related_name="+"`, which still cascade and include some of the+ # highest-volume tables, so the summary would understate what gets deleted.+ # Only relations that hang straight off the user are counted. Reaching the rows that+ # cascade one step further, through a relation of a relation, means joining back through+ # every parent table, which is the unbounded work this page exists to avoid. The+ # confirmation page says the counts stop at the account's own rows.+ relations = cast(Iterable[ForeignObjectRel], get_candidate_relations_to_delete(User._meta))+ for related in relations:+ field = related.field+ related_model = field.model+ # Auto-created through models (groups, permissions) are noise next to the fields that+ # already show them on the change form.+ if related_model._meta.auto_created:+ continue+ on_delete = field.remote_field.on_delete+ if on_delete in (PROTECT, RESTRICT):+ protected.extend(self._protected_rows(field, objs))+ continue+ if on_delete is not CASCADE:+ continue+ count = (+ # nosemgrep: orm-field-injection -- field.name comes from User._meta, never a request+ related_model._base_manager.filter(**{f"{field.name}__in": objs})+ .order_by()[: DELETION_SUMMARY_COUNT_CAP + 1]+ .count()+ )+ if count:+ counts.append((str(related_model._meta.verbose_name_plural), count))+ if not self._may_delete_related(request, related_model):+ perms_needed.add(str(related_model._meta.verbose_name))++ counts.sort(key=lambda entry: (-entry[1], entry[0]))+ summary = {str(User._meta.verbose_name_plural): str(len(objs))}+ for label, count in counts:+ summary[label] = f"{DELETION_SUMMARY_COUNT_CAP}+" if count > DELETION_SUMMARY_COUNT_CAP else str(count)+ return _CascadeSummary(counts=summary, perms_needed=perms_needed, protected=protected)++ def _may_delete_related(self, request: HttpRequest, related_model: type[Model]) -> bool:+ # Django's own collector reports a model in `perms_needed` when the operator can't delete+ # it in the admin, and `ModelAdmin._delete_view` then withholds the confirm button and+ # raises PermissionDenied on the POST. Reporting nothing here would cascade through models+ # whose admin refuses deletion outright, such as the one for AI assistant conversations.+ # A model with no admin has nobody to ask, which Django also treats as nothing to check.+ related_admin = self.admin_site._registry.get(related_model)+ if related_admin is None:+ return True+ # Django asks per row. Asking once per model is what keeps this page bounded, so an admin+ # that refuses only some of its rows is answered by whatever it says for the model as a+ # whole.+ return related_admin.has_delete_permission(request)++ def _protected_rows(self, field: ForeignObject, objs: list[User]) -> list[str]:+ # Django refuses a delete that a PROTECT or RESTRICT relation blocks by raising from inside+ # the delete itself, which here would be after the confirmation page has already accepted+ # the reason. Returning the rows as `protected` instead makes the admin render its own+ # blocked page and withhold the confirm button. RESTRICT is included even though Django+ # clears it when the same row also cascades away through another relation: refusing a delete+ # that could have gone through is recoverable, and a failure part-way through a delete is not.+ related_model = field.model+ rows = list(+ # nosemgrep: orm-field-injection -- field.name comes from User._meta, never a request+ related_model._base_manager.filter(**{f"{field.name}__in": objs}).order_by()[+ : DELETION_SUMMARY_COUNT_CAP + 1+ ]+ )+ labels = [f"{related_model._meta.verbose_name}: {row}" for row in rows[:DELETION_SUMMARY_COUNT_CAP]]+ if len(rows) > DELETION_SUMMARY_COUNT_CAP:+ labels.append(f"More {related_model._meta.verbose_name_plural}, not listed here")+ return labels++ def delete_view(self, request, object_id, extra_context=None):+ if request.method == "POST" and not _deletion_reason(request):+ messages.error(request, "Add a reason for deleting this user, then confirm again.")+ return HttpResponseRedirect(request.get_full_path())+ return super().delete_view(+ request,+ object_id,+ {"deletion_summary_count_cap": DELETION_SUMMARY_COUNT_CAP, **(extra_context or {})},+ )++ def log_deletions(self, request, queryset):+ # An ActivityLog row has to be scoped to an organization or a team, so an account that has+ # already left every organization has nowhere to record one. Django's own admin log always+ # takes the reason, and it's where "recent actions" reads from.+ return LogEntry.objects.log_actions(+ user_id=request.user.pk,+ queryset=queryset,+ action_flag=DELETION,+ change_message=f"Reason: {_deletion_reason(request)}",+ )++ def delete_model(self, request, obj):+ # Read what the log entries need first: the cascade takes the memberships that scope them,+ # and the delete blanks the instance's primary key.+ reason = _deletion_reason(request)+ organization_ids = list(obj.organization_memberships.values_list("organization_id", flat=True))+ deleted_user_id = obj.pk+ name = f"{obj.first_name} {obj.last_name}".strip() or obj.email+ email = obj.email++ super().delete_model(request, obj)++ detail = Detail(+ name=name,+ type="admin_user_deletion",+ context=UserDeletionActivityContext(reason=reason, email=email),+ )+ bulk_log_activity(+ [+ LogActivityEntry(+ organization_id=organization_id,+ team_id=None,+ user=request.user,+ item_id=deleted_user_id,+ scope="User",+ activity="deleted",+ detail=detail,+ was_impersonated=is_impersonated(request),+ )+ for organization_id in organization_ids+ ]+ )+def user_change_password(self, request, id, form_url=""):# We don't let admins set passwords directly (change_password_form is None), but Django's# inherited get_urls() still registers this route — which would 500 on NoneType form.diff --git a/posthog/admin/test_user_admin.py b/posthog/admin/test_user_admin.pyindex 6faa7c0bceb0..12e73b811ecd 100644--- a/posthog/admin/test_user_admin.py+++ b/posthog/admin/test_user_admin.py@@ -5,15 +5,29 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.conf import settings+from django.contrib.admin import ModelAdmin+from django.contrib.admin.models import DELETION, LogEntryfrom django.contrib.admin.sites import AdminSite-from django.contrib.auth import SESSION_KEY+from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEYfrom django.contrib.messages.storage.fallback import FallbackStorage+from django.core.exceptions import PermissionDenied+from django.db.models import PROTECTfrom django.test import RequestFactoryfrom django.urls import reverse+from loginas import settings as la_settings+from parameterized import parameterized+from posthog.admin.admins.user_admin import UserAdmin, UserChangeForm-from posthog.models import User+from posthog.models import OrganizationMembership, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.session.models import Session+from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed+++class _RefusesDeletionAdmin(ModelAdmin):+ def has_delete_permission(self, request, obj=None) -> bool:+ return Falseclass TestUserAdminSessions(BaseTest):@@ -110,3 +124,168 @@ class TestUserChangeFormPasswordField(BaseTest):self.assertNotIn("/reset/", help_text)self.assertNotIn("href", help_text)+++class TestUserAdminDeletion(BaseTest):+ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.factory = RequestFactory()+ self.admin = UserAdmin(User, AdminSite())+ self.target = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.delete_path = f"/admin/posthog/user/{self.target.pk}/delete/"++ def _request(self, method: str = "post", data: dict | None = None):+ request = getattr(self.factory, method)(self.delete_path, data or {})+ request.user = self.user+ request.session = {}+ request._messages = FallbackStorage(request)+ # Django's delete view is wrapped in csrf_protect, which a RequestFactory POST can't satisfy.+ request._dont_enforce_csrf_checks = True+ return request++ def _deletion_logs(self):+ return ActivityLog.objects.filter(scope="User", activity="deleted", item_id=str(self.target.pk))++ def test_confirmation_page_counts_the_cascade_instead_of_listing_every_row(self):+ # The reported timeout: Django's NestedObjects collector loads and renders every cascading+ # row, and recorded views alone run into the millions on a long-lived account.+ for session_id in ("one", "two"):+ SessionRecordingViewed.objects.create(team=self.team, user=self.target, session_id=session_id)++ deleted_objects, model_count, perms_needed, protected = self.admin.get_deleted_objects(+ [self.target], self._request(method="get")+ )++ self.assertEqual(deleted_objects, [])+ self.assertEqual(perms_needed, set())+ self.assertEqual(protected, [])+ self.assertEqual(model_count[str(User._meta.verbose_name_plural)], "1")+ self.assertEqual(model_count[str(SessionRecordingViewed._meta.verbose_name_plural)], "2")+ self.assertEqual(model_count[str(OrganizationMembership._meta.verbose_name_plural)], "1")++ @patch("posthog.admin.admins.user_admin.DELETION_SUMMARY_COUNT_CAP", 1)+ def test_confirmation_page_caps_each_count(self):+ for session_id in ("one", "two", "three"):+ SessionRecordingViewed.objects.create(team=self.team, user=self.target, session_id=session_id)++ _, model_count, _, _ = self.admin.get_deleted_objects([self.target], self._request(method="get"))++ self.assertEqual(model_count[str(SessionRecordingViewed._meta.verbose_name_plural)], "1+")++ def test_confirmation_page_asks_for_a_reason(self):+ response = self.admin.delete_view(self._request(method="get"), str(self.target.pk))+ response.render()++ self.assertIn('name="deletion_reason"', response.content.decode())++ def test_delete_without_a_reason_keeps_the_user(self):+ response = self.admin.delete_view(self._request(data={"post": "yes"}), str(self.target.pk))++ self.assertEqual(response.status_code, 302)+ self.assertEqual(response.url, self.delete_path)+ self.assertTrue(User.objects.filter(pk=self.target.pk).exists())++ def test_delete_with_a_reason_records_it_for_every_organization(self):+ other_organization, _, _ = User.objects.bootstrap("Other org", "[email protected]", None)+ self.target.join(organization=other_organization)+ target_id = self.target.pk++ response = self.admin.delete_view(+ self._request(data={"post": "yes", "deletion_reason": "Duplicate account after an email change"}),+ str(target_id),+ )++ self.assertEqual(response.status_code, 302)+ self.assertFalse(User.objects.filter(pk=target_id).exists())+ logs = self._deletion_logs()+ self.assertEqual(+ {log.organization_id for log in logs},+ {self.organization.id, other_organization.id},+ )+ for log in logs:+ self.assertEqual(log.user, self.user)+ self.assertEqual(+ (log.detail or {}).get("context"),+ {"reason": "Duplicate account after an email change", "email": "[email protected]"},+ )++ def test_delete_records_the_reason_in_the_admin_log(self):+ # An ActivityLog row needs an organization or team to be scoped to, so a user who has left+ # every organization would otherwise have their deletion recorded with no reason at all.+ self.target.organization_memberships.all().delete()+ target_id = self.target.pk++ self.admin.delete_view(+ self._request(data={"post": "yes", "deletion_reason": "Requested by the customer"}),+ str(target_id),+ )++ self.assertFalse(User.objects.filter(pk=target_id).exists())+ self.assertFalse(self._deletion_logs().exists())+ entry = LogEntry.objects.get(object_id=str(target_id), action_flag=DELETION)+ self.assertIn("Requested by the customer", entry.change_message)++ def test_staff_cannot_delete_the_account_they_are_acting_as(self):+ request = self._request()++ self.assertFalse(self.admin.has_delete_permission(request, self.user))+ self.assertTrue(self.admin.has_delete_permission(request, self.target))++ def test_staff_cannot_delete_the_account_they_are_impersonating(self):+ # AdminImpersonationMiddleware swaps `request.user` back to the staff operator on /admin/+ # paths, so a check against `request.user` alone lets the impersonated account through.+ request = self._request()+ request.session = {+ la_settings.USER_SESSION_FLAG: "signed-original-user",+ SESSION_KEY: str(self.target.pk),+ BACKEND_SESSION_KEY: "django.contrib.auth.backends.ModelBackend",+ }++ self.assertFalse(self.admin.has_delete_permission(request, self.target))++ def test_a_protected_relation_blocks_the_delete_instead_of_failing_part_way_through(self):+ # No relation to User is PROTECT or RESTRICT today. When one lands, reporting no protected+ # objects would let the confirmation page take the reason and then raise ProtectedError from+ # inside the delete, with part of the cascade already gone.+ membership_user_field = OrganizationMembership._meta.get_field("user")+ target_id = self.target.pk++ with patch.object(membership_user_field.remote_field, "on_delete", PROTECT):+ _, _, _, protected = self.admin.get_deleted_objects([self.target], self._request(method="get"))+ self.admin.delete_view(+ self._request(data={"post": "yes", "deletion_reason": "Duplicate account"}),+ str(target_id),+ )++ self.assertEqual(len(protected), 1)+ self.assertTrue(User.objects.filter(pk=target_id).exists())++ @parameterized.expand([("with recorded views", 1, True), ("without recorded views", 0, False)])+ def test_an_admin_that_refuses_deletion_blocks_the_cascade_through_its_model(+ self, _name: str, view_count: int, blocked: bool+ ):+ # Django reports such a model in `perms_needed`, which withholds the confirm button and+ # raises PermissionDenied on the POST. Reporting none would hard-delete rows behind the+ # back of an admin that refuses deletion, such as the one for AI assistant conversations.+ site = AdminSite()+ site.register(SessionRecordingViewed, _RefusesDeletionAdmin)+ admin_with_registry = UserAdmin(User, site)+ for index in range(view_count):+ SessionRecordingViewed.objects.create(team=self.team, user=self.target, session_id=str(index))+ target_id = self.target.pk++ _, _, perms_needed, _ = admin_with_registry.get_deleted_objects([self.target], self._request(method="get"))++ self.assertEqual(perms_needed, {str(SessionRecordingViewed._meta.verbose_name)} if blocked else set())+ request = self._request(data={"post": "yes", "deletion_reason": "Duplicate account"})+ if blocked:+ with self.assertRaises(PermissionDenied):+ admin_with_registry.delete_view(request, str(target_id))+ else:+ admin_with_registry.delete_view(request, str(target_id))+ self.assertEqual(User.objects.filter(pk=target_id).exists(), blocked)++ def test_bulk_delete_action_is_unavailable(self):+ self.assertNotIn("delete_selected", self.admin.get_actions(self._request(method="get")))diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex e64bda1aca4a..054ad9e15e37 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -437,7 +437,7 @@ activity_visibility_restrictions: list[dict[str, Any]] = [},{"scope": "User",- "activities": ["created", "updated"],+ "activities": ["created", "updated", "deleted"],"exclude_when": {},"allow_staff": True,},diff --git a/posthog/templates/admin/posthog/user/delete_confirmation.html b/posthog/templates/admin/posthog/user/delete_confirmation.htmlnew file mode 100644index 000000000000..2ec5fc704563--- /dev/null+++ b/posthog/templates/admin/posthog/user/delete_confirmation.html@@ -0,0 +1,36 @@+{% extends "admin/delete_confirmation.html" %}++{% block delete_confirm %}+ <p>+ Deleting <strong>{{ object }}</strong> removes their account, their personal API keys, their+ two-factor devices, and their membership of every organization they belong to. Insights,+ dashboards, and anything else they created stays, with no creator on it. You can't undo this.+ </p>+ <p>+ If the account is only in the way of a new one, changing its email address is usually the+ better fix.+ </p>++ {% include "admin/includes/object_delete_summary.html" %}+ <p>+ Counts stop at {{ deletion_summary_count_cap }}+, so a big account doesn't slow this page down.+ Only rows attached directly to the account are counted. Rows that belong to those go too.+ </p>++ <form method="post">{% csrf_token %}+ <div>+ <input type="hidden" name="post" value="yes">+ {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1">{% endif %}+ {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}">{% endif %}++ <p>+ <label for="deletion_reason">Why are you deleting this account? Saved to the activity log.</label><br>+ <input type="text" id="deletion_reason" name="deletion_reason" size="80" maxlength="400" required+ placeholder="e.g. duplicate account left over from an email change, ticket 1234">+ </p>++ <input type="submit" value="Yes, delete this user">+ <a href="#" class="button cancel-link">No, take me back</a>+ </div>+ </form>+{% endblock %}