: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
refactor(customer-analytics): add single account write path via the manager (#64706)
Arthur Moreira de Deusde6f0a1a9f06
diff --git a/.semgrep/devex-rules/customer-analytics-no-raw-account-properties-write.yaml b/.semgrep/devex-rules/customer-analytics-no-raw-account-properties-write.yamlnew file mode 100644index 000000000000..0042dc3cedb5--- /dev/null+++ b/.semgrep/devex-rules/customer-analytics-no-raw-account-properties-write.yaml@@ -0,0 +1,36 @@+rules:+ - id: customer-analytics-no-raw-account-properties-write+ message: |+ Don't write Account `_properties` directly. Every account write must go through the+ AccountManager chokepoint — `Account.objects.create_account(...)` or+ `Account.objects.update_account(...)` — which validates and coerces properties via+ `AccountProperties.from_input`.++ Passing `_properties=` to `.create(...)` or assigning `account._properties = ...`+ bypasses that validation and can persist malformed properties.++ Pass `properties=<dict>` to the manager instead. Tags and the surrounding transaction+ are the caller's responsibility (see `api/serializers.py` and `max_tools/upsert_account.py`+ for the pattern).++ Test setup may build fixtures directly, so this rule excludes tests. For a genuine+ non-test exception, add+ `# nosemgrep: customer-analytics-no-raw-account-properties-write` with a short reason.+ severity: ERROR+ languages: [python]+ paths:+ include:+ - '/products/customer_analytics/backend/**'+ exclude:+ - '/products/customer_analytics/backend/models/account.py'+ - '**/test_*.py'+ - '**/*_test.py'+ - '**/test/**'+ - '**/migrations/**'+ pattern-either:+ - pattern: $X.create(..., _properties=$V, ...)+ - pattern: $OBJ._properties = $V+ metadata:+ category: best-practice+ subcategory:+ - auditdiff --git a/products/customer_analytics/backend/api/serializers.py b/products/customer_analytics/backend/api/serializers.pyindex 78535c267f66..9009c7abaf34 100644--- a/products/customer_analytics/backend/api/serializers.py+++ b/products/customer_analytics/backend/api/serializers.py@@ -1,15 +1,17 @@import json+from django.db import IntegrityError, transaction+from drf_spectacular.utils import extend_schema_fieldfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializersfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin+from posthog.exceptions import Conflictfrom posthog.models import OrganizationMembershipfrom products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig-from products.customer_analytics.backend.models.account import AccountPropertiesfrom products.notebooks.backend.models import Notebook_ACCOUNT_ASSIGNMENT_SCHEMA = {@@ -194,33 +196,51 @@ class AccountSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):def validate_properties(self, value):if value is None:return {}-if not isinstance(value, dict):raise serializers.ValidationError("properties must be a JSON object.")-try:json.dumps(value)except (TypeError, ValueError):raise serializers.ValidationError("properties must be JSON-serializable.")-- try:- AccountProperties.model_validate(value)- except PydanticValidationError as exc:- raise serializers.ValidationError(_format_pydantic_errors(exc))-return valuedef create(self, validated_data):- from django.db import IntegrityError+ properties = validated_data.pop("_properties", {})+ validated_data.pop("tags", None)+ try:+ with transaction.atomic():+ account = Account.objects.create_account(+ team=self.context["get_team"](),+ created_by=self.context["request"].user,+ name=validated_data["name"],+ external_id=validated_data.get("external_id"),+ properties=properties,+ )+ self._attempt_set_tags(self.initial_data.get("tags"), account)+ except PydanticValidationError as exc:+ raise serializers.ValidationError({"properties": _format_pydantic_errors(exc)})+ except IntegrityError:+ raise Conflict("An account with this external_id already exists for this team.")+ return account- from posthog.exceptions import Conflict+ def update(self, instance, validated_data):+ update_kwargs: dict = {}+ if "name" in validated_data:+ update_kwargs["name"] = validated_data["name"]+ if "external_id" in validated_data:+ update_kwargs["external_id"] = validated_data["external_id"]+ if "_properties" in validated_data:+ update_kwargs["properties"] = validated_data["_properties"]- validated_data["created_by"] = self.context["request"].user- validated_data["team_id"] = self.context["team_id"]try:- return super().create(validated_data)+ with transaction.atomic():+ account = Account.objects.update_account(instance, **update_kwargs)+ self._attempt_set_tags(self.initial_data.get("tags"), account)+ except PydanticValidationError as exc:+ raise serializers.ValidationError({"properties": _format_pydantic_errors(exc)})except IntegrityError:raise Conflict("An account with this external_id already exists for this team.")+ return accountdef _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.pyindex f2b3cd1b42de..4dd48e94a21e 100644--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py@@ -164,12 +164,12 @@ class Command(BaseCommand):for index, (group_key, props) in enumerate(groups):account = existing.get(group_key)if account is None:- account = Account.objects.create(+ account = Account.objects.create_account(team=team,name=props.get("name") or group_key,external_id=group_key,created_by=creator,- _properties=self._account_roles(assignments, index, group_key).model_dump(mode="json"),+ properties=self._account_roles(assignments, index, group_key),)created += 1accounts.append(account)diff --git a/products/customer_analytics/backend/max_tools/upsert_account.py b/products/customer_analytics/backend/max_tools/upsert_account.pyindex 92d697e096f2..64158dd7e2fa 100644--- a/products/customer_analytics/backend/max_tools/upsert_account.py+++ b/products/customer_analytics/backend/max_tools/upsert_account.py@@ -183,12 +183,12 @@ class UpsertAccountTool(MaxTool):@sync_to_asyncdef _create_account(self, action: CreateAccountAction, properties: dict[str, Any]) -> Account:with transaction.atomic():- account = Account.objects.unscoped().create(+ account = Account.objects.create_account(team=self._team,created_by=self._user,- name=action.name[:400],- external_id=(action.external_id[:400] if action.external_id else None),- _properties=properties,+ name=action.name,+ external_id=(action.external_id or None),+ properties=properties,)if action.tags is not None:set_tags_on_object(action.tags, account)@@ -196,20 +196,17 @@ class UpsertAccountTool(MaxTool):@sync_to_asyncdef _update_account(self, account: Account, action: UpdateAccountAction) -> Account:+ update_kwargs: dict[str, Any] = {}+ if action.name is not None:+ update_kwargs["name"] = action.name+ if action.external_id is not None:+ update_kwargs["external_id"] = action.external_id or None+ if action.properties is not None:+ properties = account.properties.model_dump(mode="json")+ properties.update(action.properties.model_dump(exclude_unset=True))+ update_kwargs["properties"] = propertieswith transaction.atomic():- update_fields: list[str] = []- if action.name is not None:- account.name = action.name[:400]- update_fields.append("name")- if action.external_id is not None:- account.external_id = action.external_id[:400] or None- update_fields.append("external_id")- if action.properties is not None:- merged = {**(account._properties or {}), **action.properties.model_dump(exclude_unset=True)}- account._properties = merged- update_fields.append("_properties")- if update_fields:- account.save(update_fields=update_fields)+ account = Account.objects.update_account(account, **update_kwargs)if action.tags is not None:set_tags_on_object(action.tags, account)return accountdiff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.pyindex a672a2269d99..be9756622ef1 100644--- a/products/customer_analytics/backend/models/account.py+++ b/products/customer_analytics/backend/models/account.py@@ -1,4 +1,5 @@-from typing import Any+from enum import Enum+from typing import TYPE_CHECKING, castfrom django.apps import appsfrom django.core.exceptions import ValidationError@@ -13,6 +14,9 @@ from posthog.models.scoping.manager import TeamScopedManagerfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel+if TYPE_CHECKING:+ from posthog.models import Team, User+class AccountAssignment(BaseModel):id: int@@ -36,22 +40,66 @@ class AccountProperties(BaseModel):slack_channel_id: str | None = Noneusage_dashboard_link: str | None = None+ @classmethod+ def from_input(cls, data: "dict | AccountProperties") -> "AccountProperties":+ if isinstance(data, AccountProperties):+ data = data.model_dump(mode="json", exclude_unset=True)+ return cls.model_validate(data)+++class _Unset(Enum):+ UNSET = "unset"+++_UNSET = _Unset.UNSET+class AccountManager(TeamScopedManager["Account"]):- def create(+ def create_account(self,*,+ team: "Team",+ name: str,+ created_by: "User | None" = None,+ external_id: str | None = None,properties: "dict | AccountProperties | None" = None,- **kwargs: Any,) -> "Account":- if properties is not None:- validated = (- properties- if isinstance(properties, AccountProperties)- else AccountProperties.model_validate(properties)+ validated = AccountProperties.from_input(properties or {})+ return self.unscoped().create(+ team=team,+ created_by=created_by,+ name=self._cap_to_field_length("name", name),+ external_id=self._cap_to_field_length("external_id", external_id) if external_id is not None else None,+ _properties=validated.model_dump(mode="json", exclude_unset=True),+ )++ def update_account(+ self,+ account: "Account",+ *,+ name: str | _Unset = _UNSET,+ external_id: str | None | _Unset = _UNSET,+ properties: "dict | AccountProperties | _Unset" = _UNSET,+ ) -> "Account":+ update_fields: list[str] = []+ if name is not _UNSET:+ account.name = self._cap_to_field_length("name", name)+ update_fields.append("name")+ if external_id is not _UNSET:+ account.external_id = (+ self._cap_to_field_length("external_id", external_id) if external_id is not None else None)- kwargs["_properties"] = validated.model_dump(mode="json")- return super().create(**kwargs)+ update_fields.append("external_id")+ if properties is not _UNSET:+ account._properties = AccountProperties.from_input(properties).model_dump(mode="json", exclude_unset=True)+ update_fields.append("_properties")+ if update_fields:+ account.save(update_fields=update_fields)+ return account++ def _cap_to_field_length(self, field_name: str, value: str) -> str:+ max_length = cast(models.CharField, self.model._meta.get_field(field_name)).max_length+ return value[:max_length]class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.pyindex 2d7f6f326bca..6b52ed7620ac 100644--- a/products/customer_analytics/backend/models/account_test.py+++ b/products/customer_analytics/backend/models/account_test.py@@ -1,10 +1,12 @@from contextlib import AbstractContextManager+from typing import castimport pytestfrom posthog.test.base import BaseTestfrom django.core.exceptions import ValidationError as DjangoValidationError-from django.db import IntegrityError, transaction+from django.db import IntegrityError, models, transaction+from django.test import SimpleTestCasefrom parameterized import parameterizedfrom pydantic import ValidationError as PydanticValidationError@@ -124,3 +126,56 @@ class TeamCustomerAnalyticsConfigDriftPolicyTest(_AccountTeamScopedTestMixin, Baself.config.save()self.config.refresh_from_db()assert self.config.account_group_type_index == new_index+++class AccountManagerWriteTest(_AccountTeamScopedTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ self.user = User.objects.create_user(+ email="[email protected]", password=None, first_name="Mgr", is_email_verified=True+ )++ def test_update_account_replaces_properties_wholesale(self):+ account = Account.objects.create_account(+ team=self.team,+ created_by=self.user,+ name="Acme",+ properties={"csm": {"id": self.user.id, "email": self.user.email}},+ )+ Account.objects.update_account(account, properties={"stripe_customer_id": "cus_123"})+ account.refresh_from_db()+ assert account.properties.csm is None+ assert account.properties.stripe_customer_id == "cus_123"++ def test_update_account_leaves_properties_untouched_when_not_passed(self):+ account = Account.objects.create_account(+ team=self.team,+ created_by=self.user,+ name="Acme",+ properties={"stripe_customer_id": "cus_123"},+ )++ Account.objects.update_account(account, name="Renamed")++ account.refresh_from_db()+ assert account.name == "Renamed"+ assert account.properties.stripe_customer_id == "cus_123"++ def test_update_account_updates_name_and_external_id(self):+ account = Account.objects.create_account(team=self.team, created_by=self.user, name="Old")+ Account.objects.update_account(account, name="New", external_id="acme-1")+ account.refresh_from_db()+ assert account.name == "New"+ assert account.external_id == "acme-1"+++class AccountManagerCapToFieldLengthTest(SimpleTestCase):+ @parameterized.expand([("name",), ("external_id",)])+ def test_caps_value_to_field_max_length(self, field_name):+ max_length = cast(models.CharField, Account._meta.get_field(field_name)).max_length+ assert max_length is not None+ result = Account.objects._cap_to_field_length(field_name, "x" * (max_length + 50))+ assert result == "x" * max_length++ def test_leaves_value_within_limit_unchanged(self):+ assert Account.objects._cap_to_field_length("name", "Acme") == "Acme"