Skip to content

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

feat(admin): add deletion trigger buttons to org and project admin (#71092)

Yasen1763863380c4
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 61223bf9ea22..7123a711a37e 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -12,6 +12,7 @@ from django.utils import timezone
from django.utils.html import format_html
from django.utils.safestring import mark_safe
+from posthog.admin.authorization import can_trigger_admin_deletion
from posthog.admin.inline_registry import extra_inlines_for
from posthog.admin.inlines.organization_domain_inline import OrganizationDomainInline
from posthog.admin.inlines.organization_invite_inline import OrganizationInviteInline
@@ -148,6 +149,7 @@ class OrganizationAdmin(admin.ModelAdmin):
"is_ai_training_opted_in",
"is_ai_training_locked",
"is_ai_training_cta_shown",
+ "trigger_deletion_display",
]
inlines = [
ProjectInline,
@@ -167,6 +169,7 @@ class OrganizationAdmin(admin.ModelAdmin):
"customer_trust_scores",
"bulk_delete_data_display",
"sync_to_billing_display",
+ "trigger_deletion_display",
]
search_fields = ("name", "members__email", "team__api_token")
list_display = (
@@ -322,6 +325,104 @@ class OrganizationAdmin(admin.ModelAdmin):
)
)
+ @admin.display(description="Danger zone")
+ def trigger_deletion_display(self, organization: Organization):
+ if not organization.pk:
+ return "-"
+ request = getattr(self, "_current_request", None)
+ # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
+ return mark_safe(
+ render_to_string(
+ "admin/deletion_button.html",
+ {
+ "action_url": reverse("admin:organization_trigger_deletion", args=[organization.pk]),
+ "button_label": "Trigger deletion",
+ "confirm_message": (
+ f'Trigger deletion for organization "{organization.name}" ({organization.pk})? '
+ "This starts an irreversible Temporal workflow that deletes the organization and all its data."
+ ),
+ "notice": (
+ "Before triggering, make sure no Temporal deletion workflow is already running for this "
+ "organization. Starting a second one while another is mid-flight can cause clashing deletes."
+ ),
+ },
+ request=request,
+ )
+ )
+
+ def trigger_deletion_view(self, request, organization_id):
+ from temporalio.exceptions import WorkflowAlreadyStartedError
+
+ from posthog.event_usage import report_organization_deleted, report_organization_deletion_initiated
+ from posthog.temporal.delete_teams.dispatch import start_delete_organization_workflow
+
+ change_url = reverse("admin:posthog_organization_change", args=[organization_id])
+
+ try:
+ organization = Organization.objects.get(id=organization_id)
+ except Organization.DoesNotExist:
+ messages.error(request, f"Organization with id {organization_id} not found.")
+ return redirect(reverse("admin:posthog_organization_changelist"))
+
+ if request.method != "POST":
+ return redirect(change_url)
+
+ # Staff access alone must not authorize a destructive delete; require explicit
+ # membership in the deletion-authorized group (Django's model permissions are not a
+ # real gate here — User.is_superuser mirrors is_staff, so every staff user passes).
+ if not can_trigger_admin_deletion(request):
+ messages.error(request, "You do not have permission to delete this organization.")
+ return redirect(change_url)
+
+ if settings.DISABLE_BULK_DELETES:
+ messages.error(
+ request, "Bulk deletes are temporarily disabled during a database migration. Try again later."
+ )
+ return redirect(change_url)
+
+ if organization.is_pending_deletion:
+ messages.error(request, f"Organization {organization.name} ({organization.pk}) is already being deleted.")
+ return redirect(change_url)
+
+ teams = list(organization.teams.only("id", "name").all())
+ team_ids = [team.pk for team in teams]
+ project_names = [team.name for team in teams]
+
+ user = request.user
+ report_organization_deleted(user, organization)
+ report_organization_deletion_initiated(user, organization)
+
+ # Mark pending before dispatch so the org is locked out even if this write and the
+ # workflow start race; mirrors the API deletion path.
+ organization.is_pending_deletion = True
+ organization.save(update_fields=["is_pending_deletion"])
+
+ try:
+ start_delete_organization_workflow(
+ team_ids=team_ids,
+ organization_id=str(organization.pk),
+ user_id=user.id,
+ organization_name=organization.name,
+ project_names=project_names,
+ )
+ except WorkflowAlreadyStartedError:
+ messages.error(
+ request,
+ f"A deletion workflow is already running for organization {organization.name} ({organization.pk}).",
+ )
+ return redirect(change_url)
+ except Exception as e:
+ # Dispatch failed, so no workflow is running; unlock the org so it can be retried.
+ organization.is_pending_deletion = False
+ organization.save(update_fields=["is_pending_deletion"])
+ messages.error(request, f"Failed to start deletion workflow: {e}")
+ return redirect(change_url)
+
+ messages.success(
+ request, f"Started deletion workflow for organization {organization.name} ({organization.pk})."
+ )
+ return redirect(change_url)
+
def sync_to_billing_view(self, request, organization_id):
from posthog.tasks.sync_billing import sync_members_to_billing
@@ -407,6 +508,11 @@ class OrganizationAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.sync_to_billing_view),
name="organization_sync_to_billing",
),
+ path(
+ "<path:organization_id>/trigger-deletion/",
+ self.admin_site.admin_view(self.trigger_deletion_view),
+ name="organization_trigger_deletion",
+ ),
]
return custom_urls + urls
diff --git a/posthog/admin/admins/project_admin.py b/posthog/admin/admins/project_admin.py
index f6d286c259b8..745589c6aecf 100644
--- a/posthog/admin/admins/project_admin.py
+++ b/posthog/admin/admins/project_admin.py
@@ -1,7 +1,14 @@
-from django.contrib import admin
-from django.urls import reverse
+from typing import cast
+
+from django.conf import settings
+from django.contrib import admin, messages
+from django.shortcuts import redirect
+from django.template.loader import render_to_string
+from django.urls import path, reverse
from django.utils.html import format_html
+from django.utils.safestring import mark_safe
+from posthog.admin.authorization import can_trigger_admin_deletion
from posthog.admin.inlines.organization_member_for_related_inline import OrganizationMemberForRelatedInline
from posthog.admin.inlines.team_inline import TeamInline
from posthog.models import Project
@@ -25,7 +32,24 @@ class ProjectAdmin(admin.ModelAdmin):
"organization__name",
)
autocomplete_fields = ["organization"]
- readonly_fields = ["created_at"]
+ readonly_fields = ["id", "created_at", "updated_at", "trigger_deletion_display"]
+ fieldsets = (
+ (
+ None,
+ {
+ "fields": (
+ "id",
+ "name",
+ "organization",
+ "product_description",
+ "is_pending_deletion",
+ "created_at",
+ "updated_at",
+ )
+ },
+ ),
+ ("Danger zone", {"fields": ("trigger_deletion_display",)}),
+ )
inlines = [OrganizationMemberForRelatedInline, TeamInline]
def organization_link(self, project: Project):
@@ -34,3 +58,141 @@ class ProjectAdmin(admin.ModelAdmin):
reverse("admin:posthog_organization_change", args=[project.organization.pk]),
project.organization.name,
)
+
+ @admin.display(description="Danger zone")
+ def trigger_deletion_display(self, project: Project):
+ if not project.pk:
+ return "-"
+ # No csrf_token needed in the partial: the button posts the surrounding admin change
+ # form (which carries the token) to the action URL via formaction.
+ # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
+ return mark_safe(
+ render_to_string(
+ "admin/deletion_button.html",
+ {
+ "action_url": reverse("admin:project_trigger_deletion", args=[project.pk]),
+ "button_label": "Trigger deletion",
+ "confirm_message": (
+ f'Trigger deletion for project "{project.name}" ({project.pk})? '
+ "This starts an irreversible Temporal workflow that deletes the project and all its data."
+ ),
+ "notice": (
+ "Before triggering, make sure no Temporal deletion workflow is already running for this "
+ "project. Starting a second one while another is mid-flight can cause clashing deletes."
+ ),
+ },
+ )
+ )
+
+ def get_urls(self):
+ urls = super().get_urls()
+ custom_urls = [
+ path(
+ "<path:project_id>/trigger-deletion/",
+ self.admin_site.admin_view(self.trigger_deletion_view),
+ name="project_trigger_deletion",
+ ),
+ ]
+ return custom_urls + urls
+
+ def trigger_deletion_view(self, request, project_id):
+ from temporalio.exceptions import WorkflowAlreadyStartedError
+
+ from posthog.event_usage import report_user_action
+ from posthog.helpers.impersonation import is_impersonated
+ from posthog.models.activity_logging.activity_log import Detail, log_activity
+ from posthog.models.utils import UUIDT
+ from posthog.temporal.delete_teams.dispatch import start_delete_project_data_workflow
+
+ change_url = reverse("admin:posthog_project_change", args=[project_id])
+
+ try:
+ project = Project.objects.get(id=project_id)
+ except Project.DoesNotExist:
+ messages.error(request, f"Project with id {project_id} not found.")
+ return redirect(reverse("admin:posthog_project_changelist"))
+
+ if request.method != "POST":
+ return redirect(change_url)
+
+ # Staff access alone must not authorize a destructive delete; require explicit
+ # membership in the deletion-authorized group (Django's model permissions are not a
+ # real gate here — User.is_superuser mirrors is_staff, so every staff user passes).
+ if not can_trigger_admin_deletion(request):
+ messages.error(request, "You do not have permission to delete this project.")
+ return redirect(change_url)
+
+ if settings.DISABLE_BULK_DELETES:
+ messages.error(
+ request, "Bulk deletes are temporarily disabled during a database migration. Try again later."
+ )
+ return redirect(change_url)
+
+ if project.is_pending_deletion:
+ messages.error(request, f"Project {project.name} ({project.pk}) is already being deleted.")
+ return redirect(change_url)
+
+ teams = list(project.teams.only("id", "name", "organization_id").all())
+ team_ids = [team.pk for team in teams]
+
+ user = request.user
+ organization_id = project.organization_id
+
+ # Mark pending before dispatch so the project is locked out even if this write and the
+ # workflow start race; mirrors the API deletion path.
+ project.is_pending_deletion = True
+ project.save(update_fields=["is_pending_deletion"])
+
+ try:
+ start_delete_project_data_workflow(
+ team_ids=team_ids,
+ project_id=project.pk,
+ user_id=user.id,
+ project_name=project.name,
+ )
+ except WorkflowAlreadyStartedError:
+ messages.error(
+ request, f"A deletion workflow is already running for project {project.name} ({project.pk})."
+ )
+ return redirect(change_url)
+ except Exception as e:
+ # Dispatch failed, so no workflow is running; unlock the project so it can be retried.
+ project.is_pending_deletion = False
+ project.save(update_fields=["is_pending_deletion"])
+ messages.error(request, f"Failed to start deletion workflow: {e}")
+ return redirect(change_url)
+
+ was_impersonated = is_impersonated(request)
+ for team in teams:
+ log_activity(
+ organization_id=cast(UUIDT, organization_id),
+ team_id=team.pk,
+ user=user,
+ was_impersonated=was_impersonated,
+ scope="Team",
+ item_id=team.pk,
+ activity="deleted",
+ detail=Detail(name=str(team.name)),
+ )
+ report_user_action(user, "team deleted", team=team, request=request)
+ log_activity(
+ organization_id=cast(UUIDT, organization_id),
+ team_id=project.pk,
+ user=user,
+ was_impersonated=was_impersonated,
+ scope="Project",
+ item_id=project.pk,
+ activity="deleted",
+ detail=Detail(name=str(project.name)),
+ )
+ if teams:
+ report_user_action(
+ user,
+ "project deleted",
+ {"project_name": project.name},
+ team=teams[0],
+ request=request,
+ )
+
+ messages.success(request, f"Started deletion workflow for project {project.name} ({project.pk}).")
+ return redirect(change_url)
diff --git a/posthog/admin/authorization.py b/posthog/admin/authorization.py
new file mode 100644
index 000000000000..5ebef6cf08c2
--- /dev/null
+++ b/posthog/admin/authorization.py
@@ -0,0 +1,12 @@
+from django.http import HttpRequest
+
+# Staff access alone must not authorize irreversible org/project deletions from Django
+# admin. Django's model permissions are useless as a gate here: User.is_superuser mirrors
+# is_staff, so every active staff user passes has_delete_permission(). Gate destructive
+# deletions behind explicit membership in this group instead — the same mechanism the
+# data-deletion-request admin uses for its destructive actions.
+DELETION_AUTHORIZED_GROUP = "ClickHouse Team"
+
+
+def can_trigger_admin_deletion(request: HttpRequest) -> bool:
+ return request.user.groups.filter(name=DELETION_AUTHORIZED_GROUP).exists()
diff --git a/posthog/admin/inlines/project_inline.py b/posthog/admin/inlines/project_inline.py
index 501f56b717ff..42143e85415b 100644
--- a/posthog/admin/inlines/project_inline.py
+++ b/posthog/admin/inlines/project_inline.py
@@ -18,7 +18,9 @@ class ProjectInline(TabularInlinePaginated):
"displayed_name",
"created_at",
)
- readonly_fields = [*ProjectAdmin.readonly_fields, "displayed_name"]
+ # Exclude ProjectAdmin's change-page display methods (e.g. trigger_deletion_display) —
+ # they resolve on the admin, not on the inline or the Project model.
+ readonly_fields = [*(f for f in ProjectAdmin.readonly_fields if f != "trigger_deletion_display"), "displayed_name"]
def displayed_name(self, project: Project):
return format_html(
diff --git a/posthog/admin/test_trigger_deletion_admin.py b/posthog/admin/test_trigger_deletion_admin.py
new file mode 100644
index 000000000000..bfb93739cf08
--- /dev/null
+++ b/posthog/admin/test_trigger_deletion_admin.py
@@ -0,0 +1,197 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.contrib.admin.sites import AdminSite
+from django.contrib.auth.models import Group
+from django.contrib.messages.storage.fallback import FallbackStorage
+from django.test import RequestFactory, override_settings
+
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.admin.admins.organization_admin import OrganizationAdmin
+from posthog.admin.admins.project_admin import ProjectAdmin
+from posthog.admin.authorization import DELETION_AUTHORIZED_GROUP
+from posthog.models import Organization, Project
+
+
+def _attach_messages(request) -> None:
+ request.session = {}
+ request._messages = FallbackStorage(request)
+
+
+def _fake_reverse(name, args=None, kwargs=None):
+ if args:
+ return f"/{name}/{'/'.join(str(a) for a in args)}/"
+ return f"/{name}/"
+
+
+class TestOrganizationAdminTriggerDeletion(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.user.groups.add(Group.objects.get_or_create(name=DELETION_AUTHORIZED_GROUP)[0])
+ self.factory = RequestFactory()
+ self.admin = OrganizationAdmin(Organization, AdminSite())
+
+ def _call(self, method: str, start_side_effect=None):
+ path = f"/admin/posthog/organization/{self.organization.pk}/trigger-deletion/"
+ http_request = self.factory.post(path) if method == "POST" else self.factory.get(path)
+ http_request.user = self.user
+ _attach_messages(http_request)
+ with (
+ patch("posthog.admin.admins.organization_admin.reverse", side_effect=_fake_reverse),
+ patch(
+ "posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow",
+ side_effect=start_side_effect,
+ ) as mock_start,
+ ):
+ response = self.admin.trigger_deletion_view(http_request, str(self.organization.pk))
+ return response, mock_start
+
+ def test_post_starts_org_deletion_and_marks_pending(self):
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_called_once()
+ kwargs = mock_start.call_args.kwargs
+ self.assertEqual(kwargs["organization_id"], str(self.organization.pk))
+ self.assertEqual(kwargs["team_ids"], [self.team.pk])
+ self.assertEqual(kwargs["user_id"], self.user.pk)
+ self.assertIn(self.team.name, kwargs["project_names"])
+ self.organization.refresh_from_db()
+ self.assertTrue(self.organization.is_pending_deletion)
+
+ def test_get_does_not_start_workflow(self):
+ response, mock_start = self._call("GET")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.organization.refresh_from_db()
+ self.assertFalse(self.organization.is_pending_deletion)
+
+ @override_settings(DISABLE_BULK_DELETES=True)
+ def test_disable_bulk_deletes_blocks_dispatch(self):
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.organization.refresh_from_db()
+ self.assertFalse(self.organization.is_pending_deletion)
+
+ def test_staff_outside_deletion_group_cannot_dispatch(self):
+ self.user.groups.clear()
+
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.organization.refresh_from_db()
+ self.assertFalse(self.organization.is_pending_deletion)
+
+ def test_already_pending_deletion_is_rejected(self):
+ self.organization.is_pending_deletion = True
+ self.organization.save(update_fields=["is_pending_deletion"])
+
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+
+ def test_dispatch_failure_rolls_back_pending(self):
+ response, mock_start = self._call("POST", start_side_effect=Exception("boom"))
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_called_once()
+ self.organization.refresh_from_db()
+ self.assertFalse(self.organization.is_pending_deletion)
+
+ def test_already_started_workflow_keeps_pending(self):
+ response, mock_start = self._call("POST", start_side_effect=WorkflowAlreadyStartedError("id", "type"))
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_called_once()
+ self.organization.refresh_from_db()
+ self.assertTrue(self.organization.is_pending_deletion)
+
+
+class TestProjectAdminTriggerDeletion(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.user.groups.add(Group.objects.get_or_create(name=DELETION_AUTHORIZED_GROUP)[0])
+ self.factory = RequestFactory()
+ self.admin = ProjectAdmin(Project, AdminSite())
+
+ def _call(self, method: str, start_side_effect=None):
+ path = f"/admin/posthog/project/{self.project.pk}/trigger-deletion/"
+ http_request = self.factory.post(path) if method == "POST" else self.factory.get(path)
+ http_request.user = self.user
+ _attach_messages(http_request)
+ with (
+ patch("posthog.admin.admins.project_admin.reverse", side_effect=_fake_reverse),
+ patch(
+ "posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow",
+ side_effect=start_side_effect,
+ ) as mock_start,
+ ):
+ response = self.admin.trigger_deletion_view(http_request, str(self.project.pk))
+ return response, mock_start
+
+ def test_post_starts_project_deletion_and_marks_pending(self):
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_called_once()
+ kwargs = mock_start.call_args.kwargs
+ self.assertEqual(kwargs["project_id"], self.project.pk)
+ self.assertEqual(kwargs["team_ids"], [self.team.pk])
+ self.assertEqual(kwargs["user_id"], self.user.pk)
+ self.assertEqual(kwargs["project_name"], self.project.name)
+ self.project.refresh_from_db()
+ self.assertTrue(self.project.is_pending_deletion)
+
+ def test_get_does_not_start_workflow(self):
+ response, mock_start = self._call("GET")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.project.refresh_from_db()
+ self.assertFalse(self.project.is_pending_deletion)
+
+ @override_settings(DISABLE_BULK_DELETES=True)
+ def test_disable_bulk_deletes_blocks_dispatch(self):
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.project.refresh_from_db()
+ self.assertFalse(self.project.is_pending_deletion)
+
+ def test_staff_outside_deletion_group_cannot_dispatch(self):
+ self.user.groups.clear()
+
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+ self.project.refresh_from_db()
+ self.assertFalse(self.project.is_pending_deletion)
+
+ def test_already_pending_deletion_is_rejected(self):
+ self.project.is_pending_deletion = True
+ self.project.save(update_fields=["is_pending_deletion"])
+
+ response, mock_start = self._call("POST")
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_not_called()
+
+ def test_dispatch_failure_rolls_back_pending(self):
+ response, mock_start = self._call("POST", start_side_effect=Exception("boom"))
+
+ self.assertEqual(response.status_code, 302)
+ mock_start.assert_called_once()
+ self.project.refresh_from_db()
+ self.assertFalse(self.project.is_pending_deletion)
diff --git a/posthog/templates/admin/deletion_button.html b/posthog/templates/admin/deletion_button.html
new file mode 100644
index 000000000000..f733f74d5502
--- /dev/null
+++ b/posthog/templates/admin/deletion_button.html
@@ -0,0 +1,19 @@
+{% comment %}
+Danger-zone action button for admin change pages. The submit button posts the surrounding
+admin form to action_url via formaction — a nested <form> here would be dropped by the
+browser, so it rides the change form instead (formnovalidate skips its field validation).
+Include from a readonly display method with action_url / button_label / confirm_message /
+notice in context.
+{% endcomment %}
+<button type="submit"
+ formaction="{{ action_url }}"
+ formmethod="post"
+ formnovalidate
+ class="button"
+ style="background: #ba2121; color: #fff;"
+ onclick="return confirm('{{ confirm_message|escapejs }}');">
+ {{ button_label }}
+</button>
+<p class="help" style="margin-top: 8px; max-width: 40em; color: #ba2121;">
+ {{ notice }}
+</p>