: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(cohorts): return 400 for malformed legacy groups payload (#70631)
posthog[bot]99dc1c397296
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 2f9e4d5efd26..1381e59ba14f 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -84,6 +84,7 @@ from products.cohorts.backend.models.cohort import (Cohort,CohortOrEmpty,CohortType,+ Group,)from products.cohorts.backend.models.dependencies import get_flag_excluded_behavioral_cohort_idsfrom products.cohorts.backend.models.util import (@@ -998,6 +999,23 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializraise ValidationError(f"Query must be an ActorsQuery or HogQLQuery. Got: {query.get('kind')}")return query+ def validate_groups(self, groups: Optional[list]) -> Optional[list]:+ # Legacy `groups` payloads are turned into `Group` objects during creation, where a group+ # missing all of properties/action_id/event_id (or carrying unexpected keys) raises a plain+ # exception. Validate here so bad input returns a 400 instead of surfacing as a 500.+ if groups is None:+ return groups+ if not isinstance(groups, list):+ raise ValidationError("Groups must be a list of cohort group definitions.")+ for index, group in enumerate(groups):+ if not isinstance(group, dict):+ raise ValidationError(f"Cohort group at index {index} must be an object.")+ try:+ Group(**group)+ except (ValueError, TypeError) as exc:+ raise ValidationError(f"Invalid cohort group at index {index}: {exc}")+ return groups+def _cohort_will_be_static(self) -> bool:if "is_static" in self.initial_data:return str_to_bool(self.initial_data["is_static"])diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex f55c19f2c90c..0d7c6c8de676 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -363,6 +363,24 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchinresponse = self.client.get(f"/api/projects/{self.team.id}/cohorts")assert len(response.json()["results"]) == 3+ @parameterized.expand(+ [+ # A group with none of properties/action_id/event_id used to raise an uncaught+ # ValueError from Group.__init__ and surface as a 500.+ ("missing_all_keys", [{"days": 5}], "properties or action_id or event_id"),+ # A falsy-but-non-list value used to slip past validation and get persisted as-is.+ ("empty_string", "", "must be a list"),+ ("non_dict_entry", ["not-a-dict"], "must be an object"),+ ]+ )+ def test_creating_cohort_with_malformed_groups_returns_400(self, _name, groups, expected_detail):+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts",+ data={"name": "whatever", "groups": groups},+ )+ self.assertEqual(response.status_code, 400, response.content)+ self.assertIn(expected_detail, response.json()["detail"])+def test_static_cohort_csv_upload_end_to_end(self):"""Test CSV upload end-to-end with actual celery task execution"""self.team.app_urls = ["http://somewebsite.com"]