: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(taxonomy): return 400 for malformed property definition filters (#106103)
posthog[bot]8ec7e28f48b8
diff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.pyindex 7a112b80690a..dcd41fd75d53 100644--- a/posthog/api/test/test_property_definition.py+++ b/posthog/api/test/test_property_definition.py@@ -110,6 +110,17 @@ class TestPropertyDefinitionAPI(APIBaseTest):assert len(db_results) == len(self.EXPECTED_PROPERTY_DEFINITIONS) - 1assert "first_visit" not in [r["name"] for r in db_results]+ @parameterized.expand(+ [+ ["malformed excluded_properties", "excluded_properties=abc"],+ ["malformed event_names", "event_names=%27"],+ ]+ )+ def test_list_property_definitions_rejects_malformed_json_query_params(self, _name: str, query: str) -> None:+ response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/?{query}")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_list_property_definitions_with_exclude_restricted(self):from posthog.constants import AvailableFeature@@ -1074,6 +1085,7 @@ class TestPropertyDefinitionQuerySerializer(SimpleTestCase):[["defaults", {}],["event with event_names", {"type": "event", "event_names": '["foo","bar"]'}],+ ["empty excluded_properties list", {"excluded_properties": "[]"}],["person", {"type": "person"}],["group with valid index", {"type": "group", "group_type_index": 3}],]@@ -1084,6 +1096,11 @@ class TestPropertyDefinitionQuerySerializer(SimpleTestCase):@parameterized.expand([["event_names set for non-event type", {"type": "person", "event_names": '["foo","bar"]'}],+ ["event_names not JSON", {"type": "event", "event_names": "abc"}],+ ["event_names not a list", {"type": "event", "event_names": '{"foo": 1}'}],+ ["excluded_properties not JSON", {"excluded_properties": "abc"}],+ ["excluded_properties not a list", {"excluded_properties": "1"}],+ ["excluded_properties with nested list", {"excluded_properties": '[["foo"]]'}],["group type without index", {"type": "group"}],["group_type_index above limit", {"type": "group", "group_type_index": 77}],["negative group_type_index", {"type": "group", "group_type_index": -1}],diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex 159309fc574f..aa2b9928f50b 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -83,6 +83,19 @@ class SeenTogetherQuerySerializer(serializers.Serializer):property_name: serializers.CharField = serializers.CharField(required=True)+# Sent as JSON instead of duplicate parameters like event_names[] to work with the frontend's combineUrl+def parse_json_encoded_list(value: str) -> list[str]:+ try:+ decoded = json.loads(value)+ except json.JSONDecodeError:+ raise ValidationError("Must be a JSON-encoded list of strings")++ if not isinstance(decoded, list) or any(isinstance(item, list | dict) or item is None for item in decoded):+ raise ValidationError("Must be a JSON-encoded list of strings")++ return [str(item) for item in decoded]++class PropertyDefinitionQuerySerializer(serializers.Serializer):search = serializers.CharField(help_text="Searches properties by name",@@ -164,6 +177,12 @@ class PropertyDefinitionQuerySerializer(serializers.Serializer):default=None,)+ def validate_event_names(self, value: str) -> list[str]:+ return parse_json_encoded_list(value)++ def validate_excluded_properties(self, value: str) -> list[str]:+ return parse_json_encoded_list(value)+def validate(self, attrs):type_ = attrs.get("type", "event")@@ -182,7 +201,7 @@ class PropertyDefinitionQuerySerializer(serializers.Serializer):return super().validate(attrs)[email protected](frozen=False)class QueryContext:"""The raw query is used to both query and count these results@@ -300,17 +319,15 @@ class QueryContext:},)- def with_event_property_filter(self, event_names: Optional[str], filter_by_event_names: Optional[bool]) -> Self:+ def with_event_property_filter(+ self, event_names: Optional[list[str]], filter_by_event_names: Optional[bool]+ ) -> Self:event_property_filter = ""event_name_filter = ""event_property_field = "NULL"event_name_join_filter = ""- # Passed as JSON instead of duplicate properties like event_names[] to work with frontend's combineUrl- if event_names:- event_names = json.loads(event_names)-- if event_names and len(event_names) > 0 and self.should_join_event_property:+ if event_names and self.should_join_event_property:event_property_field = f"{self.posthog_eventproperty_table_join_alias}.property IS NOT NULL"event_name_join_filter = "AND event = ANY(%(event_names)s)"@@ -321,7 +338,7 @@ class QueryContext:event_name_join_filter=event_name_join_filter,event_name_filter=event_name_filter,event_property_join_type="INNER JOIN" if filter_by_event_names else "LEFT JOIN",- params={**self.params, "event_names": list(map(str, event_names or []))},+ params={**self.params, "event_names": event_names or []},)def with_search(self, search_query: str, search_kwargs: dict, order_by_search_relevance: bool = False) -> Self:@@ -332,10 +349,8 @@ class QueryContext:params={**self.params, "project_id": self.project_id, **search_kwargs},)- def with_excluded_properties(self, excluded_properties: Optional[str]) -> Self:- excluded_list = []- if excluded_properties:- excluded_list = list(set(json.loads(excluded_properties)))+ def with_excluded_properties(self, excluded_properties: Optional[list[str]]) -> Self:+ excluded_list = list(set(excluded_properties)) if excluded_properties else []return dataclasses.replace(self,@@ -663,8 +678,7 @@ class PropertyDefinitionViewSet(span.set_attribute("property_type", prop_type or "")span.set_attribute("has_search", search is not None and search != "")- parsed_event_names = json.loads(event_names) if event_names else []- span.set_attribute("event_names_count", len(parsed_event_names))+ span.set_attribute("event_names_count", len(event_names or []))span.set_attribute("filter_by_event_names", bool(filter_by_event_names))span.set_attribute("limit", limit or 0)span.set_attribute("offset", offset or 0)@@ -869,7 +883,7 @@ class PropertyDefinitionViewSet(return False# exclusion lists- excluded = set(json.loads(v["excluded_properties"])) if v.get("excluded_properties") else set()+ excluded = set(v["excluded_properties"]) if v.get("excluded_properties") else set()if v.get("exclude_core_properties", False):excluded |= set(EXCLUDED_EVENT_CORE_PROPERTIES)if prop["name"] in excluded:diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex ee8429efe092..e1fba15660e7 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -52,7 +52,6 @@1 posthog/storage/hypercache_verifier.py1 posthog/tasks/alerts/detector.py1 posthog/tasks/alerts/detectors/base.py-1 posthog/taxonomy/property_definition_api.py1 posthog/temporal/ai/anomaly_investigation/notebook.py1 posthog/temporal/ai/anomaly_investigation/runner.py1 posthog/temporal/ai/anomaly_investigation/tools.py