: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(customer-analytics): restrict custom property deletion (#90479)
Arthur Moreira de Deus998a8b8dbf2a
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 97e1c31402d3..6d6906623cbe 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -45,6 +45,7 @@ from posthog.models import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.permissions import (PostHogFeatureFlagPermission,+ TeamMemberLightManagementPermission,TeamMemberStrictManagementPermission,get_authenticator_scopes,is_service_auth,@@ -875,6 +876,7 @@ class CustomPropertyDefinitionViewSet(viewsets.GenericViewSet,):scope_object = "account"+ permission_classes = [TeamMemberLightManagementPermission]# ``values`` is a custom read action; without listing it here it carries no required scope and# rejects token auth outright ("does not support personal API key access") before the group gate runs.scope_object_read_actions = ["list", "retrieve", "values"]diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 30e71926a7bb..f2ee12c6bcad 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -42,6 +42,7 @@ from products.customer_analytics.backend.models import (CustomerProfileConfig,CustomPropertyDefinition,CustomPropertySource,+ CustomPropertyValue,DisplayType,Meeting,MeetingParticipant,@@ -1762,9 +1763,20 @@ class TestCustomPropertyDefinitionViewSet(APIBaseTest):self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())self.assertEqual(response.json()["display_type"], "text")- def test_delete_removes_definition_only(self):+ def test_delete_removes_definition_and_values(self):keep = self._create(name="Keep", display_type="text").json()remove = self._create(name="Remove", display_type="text").json()+ remove_definition = CustomPropertyDefinition.objects.unscoped().get(id=remove["id"])+ account = create_account(team_id=self.team.id, external_id="account-with-value")+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id,+ definition=remove_definition,+ account=account,+ value_str="stored value",+ )+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()response = self.client.delete(f"{self.endpoint_base}{remove['id']}/")@@ -1772,6 +1784,8 @@ class TestCustomPropertyDefinitionViewSet(APIBaseTest):# nosemgrep: idor-lookup-without-team (test assertion)self.assertFalse(CustomPropertyDefinition.objects.unscoped().filter(id=remove["id"]).exists())# nosemgrep: idor-lookup-without-team (test assertion)+ self.assertFalse(CustomPropertyValue.objects.unscoped().filter(definition_id=remove["id"]).exists())+ # nosemgrep: idor-lookup-without-team (test assertion)self.assertTrue(CustomPropertyDefinition.objects.unscoped().filter(id=keep["id"]).exists())def test_cannot_access_other_teams_definition(self):@@ -1787,6 +1801,9 @@ class TestCustomPropertyDefinitionViewSet(APIBaseTest):def test_activity_log_on_create_and_delete(self):created = self._create(name="ARR").json()+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()self.client.delete(f"{self.endpoint_base}{created['id']}/")logs = ActivityLog.objects.filter(@@ -1801,7 +1818,8 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):Definitions are a team-wide ``account``-resource config (no per-object ownership), so they aregated at the resource level by the default ``AccessControlPermission`` (keyed on``scope_object="account"``) — the same gate as accounts and journeys, including inheritance from- the ``customer_analytics`` parent resource. Reads need ``viewer``, writes need ``editor``.+ the ``customer_analytics`` parent resource. Reads need ``viewer``, writes need ``editor``,+ and deletion needs a project admin."""def setUp(self):@@ -1822,12 +1840,18 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):)self.endpoint_base = f"/api/environments/{self.team.id}/custom_property_definitions/"- def _set_access_level(self, user: User, resource: str = "customer_analytics", access_level: str = "viewer") -> None:+ def _set_access_level(+ self,+ user: User,+ resource: str = "customer_analytics",+ access_level: str = "viewer",+ resource_id: str | None = None,+ ) -> None:membership = OrganizationMembership.objects.get(user=user, organization=self.organization)AccessControl.objects.create(team=self.team,resource=resource,- resource_id=None,+ resource_id=resource_id,access_level=access_level,organization_member=membership,)@@ -1867,8 +1891,19 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):response = self.client.post(self.endpoint_base, {"name": "Editor Prop", "display_type": "text"}, format="json")self.assertEqual(response.status_code, status.HTTP_201_CREATED)- def test_editor_can_delete(self):+ def test_editor_cannot_delete(self):self._set_access_level(self.editor_user, access_level="editor")+ self._set_access_level(+ self.editor_user, resource="project", access_level="member", resource_id=str(self.team.id)+ )+ self.client.force_login(self.editor_user)+ response = self.client.delete(f"{self.endpoint_base}{self.definition.id}/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_admin_can_delete(self):+ membership = OrganizationMembership.objects.get(user=self.editor_user, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()self.client.force_login(self.editor_user)response = self.client.delete(f"{self.endpoint_base}{self.definition.id}/")self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsxnew file mode 100644index 000000000000..d9bab1b65006--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx@@ -0,0 +1,95 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { CustomPropertiesConfig } from './CustomPropertiesConfig'+import { customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'++jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn(), useValues: jest.fn() }))+jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))+jest.mock('lib/components/RestrictedArea', () => ({+ RestrictionScope: { Project: 'project' },+ useRestrictedArea: jest.fn(() => null),+}))+jest.mock('./CustomPropertyModal', () => ({ CustomPropertyModal: () => null }))++describe('CustomPropertiesConfig', () => {+ const open = LemonDialog.open as jest.Mock+ const deleteDefinition = jest.fn()+ const propertyDefinition: CustomPropertyDefinitionApi = {+ id: 'definition-1',+ name: 'ARR',+ description: null,+ display_type: 'currency',+ is_big_number: false,+ target_type: 'account',+ group_type_index: null,+ is_canonical: false,+ options: null,+ source: null,+ created_at: '2026-01-01T00:00:00Z',+ created_by: 1,+ updated_at: null,+ references: [],+ }++ beforeEach(() => {+ open.mockClear()+ deleteDefinition.mockClear()+ ;(useValues as jest.Mock).mockImplementation((logic) => {+ if (logic === featureFlagLogic) {+ return { featureFlags: {} }+ }+ if (logic === customPropertyDefinitionsLogic) {+ return {+ filteredDefinitions: [propertyDefinition],+ definitionsLoading: false,+ searchTerm: '',+ targetTypeFilter: 'all',+ runsBySourceId: {},+ runsCountBySourceId: {},+ runsOffsetBySourceId: {},+ runsSearchBySourceId: {},+ runsLoadingBySourceId: {},+ runsLoadFailedBySourceId: {},+ }+ }+ throw new Error('Unexpected logic')+ })+ ;(useActions as jest.Mock).mockReturnValue({+ openCreateModal: jest.fn(),+ openEditModal: jest.fn(),+ deleteDefinition,+ setSearchTerm: jest.fn(),+ setTargetTypeFilter: jest.fn(),+ setRunsSearch: jest.fn(),+ loadRuns: jest.fn(),+ })+ })++ afterEach(cleanup)++ it('opens a confirmation dialog before deleting a custom property', () => {+ render(<CustomPropertiesConfig />)++ const deleteButton = document.querySelector('[data-attr="delete-custom-property"]')+ expect(deleteButton).toBeInTheDocument()+ fireEvent.click(deleteButton as HTMLElement)++ expect(open).toHaveBeenCalledTimes(1)+ const dialog = open.mock.calls[0][0]+ const { container } = render(dialog.description)+ expect(container).toHaveTextContent('This action is irreversible.')+ expect(container).toHaveTextContent('All stored values for this custom property will be permanently deleted.')+ expect(deleteDefinition).not.toHaveBeenCalled()++ dialog.primaryButton.onClick()+ expect(deleteDefinition).toHaveBeenCalledWith({ id: propertyDefinition.id })+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsxindex d2be9e26b877..b4d03804ed17 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx@@ -70,7 +70,12 @@ export function CustomPropertiesConfig(): JSX.Element {const confirmDelete = (definition: CustomPropertyDefinitionApi): void => {LemonDialog.open({title: `Delete ${definition.name}?`,- description: `Deleting ${definition.name} removes this custom property. This can't be undone.`,+ description: (+ <>+ <p>This action is irreversible.</p>+ <p>All stored values for this custom property will be permanently deleted.</p>+ </>+ ),primaryButton: {children: 'Delete',status: 'danger',@@ -197,6 +202,7 @@ export function CustomPropertiesConfig(): JSX.Element {tooltip="Delete"onClick={() => confirmDelete(definition)}disabledReason={canonicalReason ?? restrictionReason}+ data-attr="delete-custom-property"/></div>)