: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(flags): tolerate non-dict request body in flag update (#74125)
Anders0941fe646414
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex c2f9ad9b6253..95137428c8ca 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -5141,6 +5141,31 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(launch_response.status_code, status.HTTP_200_OK)self.assertEqual(launch_response.json()["status"], "running")+ def test_launch_experiment_endpoint_with_list_body(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "List Body Endpoint",+ "feature_flag_key": "list-body-endpoint-flag",+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ experiment_id = response.json()["id"]++ # The endpoint declares no request body, so a JSON array must not reach the flag serializer+ # as a non-dict `request.data`.+ launch_response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment_id}/launch/",+ [],+ format="json",+ )+ self.assertEqual(launch_response.status_code, status.HTTP_200_OK)+ self.assertEqual(launch_response.json()["status"], "running")++ flag = FeatureFlag.objects.get(key="list-body-endpoint-flag", team=self.team)+ self.assertTrue(flag.active)+def test_archive_experiment_endpoint(self):response = self.client.post(f"/api/projects/{self.team.id}/experiments/",diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex bf82105150cb..eb23bb2dde46 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1857,9 +1857,11 @@ class FeatureFlagSerializer(@approval_gate(["feature_flag.enable", "feature_flag.disable", "feature_flag.update"])def update(self, instance: FeatureFlag, validated_data: dict, *args: Any, **kwargs: Any) -> FeatureFlag:request = self.context["request"]- # This is a workaround to ensure update works when called from a scheduled task.- if request and not hasattr(request, "data"):- request.data = {}+ # Service-layer callers may carry no body, and an endpoint that declares no request schema+ # can hand us a non-dict one (e.g. a JSON array posted to /experiments/:id/launch/).+ request_data = getattr(request, "data", None) if request else None+ if not isinstance(request_data, dict):+ request_data = {}validated_data["last_modified_by"] = request.user# Prevent DRF from attempting to set reverse FK relation directly@@ -2001,7 +2003,7 @@ class FeatureFlagSerializer(k: v for k, v in previous_filters.items() if k not in ("holdout_groups", "super_groups")}- version = request.data.get("version", -1)+ version = request_data.get("version", -1)try:with transaction.atomic():@@ -2013,7 +2015,11 @@ class FeatureFlagSerializer(# NOW check for conflicts after all transformationsif version != -1 and version != locked_version:- original_flag = request.data.get("original_flag", {})+ # Not a serializer field, so the client controls its type; the conflict helpers+ # index into it by field name and would raise on a list or string.+ original_flag = request_data.get("original_flag")+ if not isinstance(original_flag, dict):+ original_flag = {}conflicting_changes = self._get_conflicting_changes(locked_instance,validated_data,diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 0d4a85b64f74..9001392cba44 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -2892,6 +2892,34 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):conflicts = serializer._get_conflicting_changes(feature_flag, validated_data, original_flag)self.assertEqual(conflicts, ["name", "filters"])+ @parameterized.expand(+ [+ ("list", ["active"]),+ ("string", "active"),+ ("number", 1),+ ]+ )+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")+ def test_updating_feature_flag_with_non_dict_original_flag(+ self, _name, original_flag, mock_report_user_action+ ) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={"name": "original name", "key": "a-flag-with-a-bad-original-flag"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ flag_id = response.json()["id"]++ # A stale version enters the conflict branch, where original_flag is indexed by field name.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag_id}",+ data={"active": False, "version": 999, "original_flag": original_flag},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertFalse(FeatureFlag.objects.get(id=flag_id).active)+@patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_treats_null_version_as_zero(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime: