Skip to content

: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.

fix(flags): normalize non-string payloads to JSON strings (#61519)

Phil Haack2ec7d851c454
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 24070fb2f573..aa3cf71fda53 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1257,23 +1257,20 @@ class FeatureFlagSerializer(
raise serializers.ValidationError("Payloads must be passed as a dictionary")
for key, value in payloads.items():
- if isinstance(value, dict):
- # Normalize JSON object payloads (e.g. from the API) to strings,
- # matching what the UI sends.
- try:
- payloads[key] = json.dumps(value)
- except (TypeError, ValueError):
- raise serializers.ValidationError("Payload value is not valid JSON")
- elif isinstance(value, str):
- try:
+ try:
+ if isinstance(value, str):
+ # An incoming string is already the canonical stored form; just check it parses.
json.loads(value)
- except json.JSONDecodeError:
- raise serializers.ValidationError("Payload value is not valid JSON")
- else:
- try:
- json.dumps(value)
- except (TypeError, ValueError):
- raise serializers.ValidationError("Payload value is not valid JSON")
+ else:
+ # Normalize any non-string JSON value (objects, arrays, numbers, booleans, null)
+ # to a JSON string, matching what the UI sends.
+ payloads[key] = json.dumps(value)
+ except json.JSONDecodeError:
+ raise serializers.ValidationError("Payload value is not valid JSON")
+ except (TypeError, ValueError):
+ # Defensive: request bodies are JSON-parsed, so values are always JSON-native
+ # (str/int/float/bool/None/dict/list) and serializable. Unreachable via the API.
+ raise serializers.ValidationError("Payload value could not be serialized to JSON")
if filters.get("multivariate"):
if not all(key in variants for key in payloads):
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 39186a337a9a..6217bbf9abac 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -2222,6 +2222,39 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
decrypted = get_decrypted_flag_payload(stored, should_decrypt=True)
self.assertEqual(decrypted, plaintext)
+ @parameterized.expand(
+ [
+ ("number", 42),
+ ("boolean", True),
+ ("null", None),
+ ("array", [1, 2, 3]),
+ ("object", {"key": "value"}),
+ ]
+ )
+ def test_update_encrypted_flag_encrypts_non_string_payload(self, _name, raw_value):
+ # A non-str JSON payload is normalized to a JSON string before encryption,
+ # so it encrypts cleanly instead of raising on `.encode()`.
+ flag = self._create_encrypted_flag()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",
+ {
+ "has_encrypted_payloads": True,
+ "filters": {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": raw_value},
+ },
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ flag.refresh_from_db()
+ stored = flag.filters["payloads"]["true"]
+ self.assertNotEqual(stored, json.dumps(raw_value))
+ decrypted = get_decrypted_flag_payload(stored, should_decrypt=True)
+ self.assertEqual(json.loads(decrypted), raw_value)
+
def test_update_encrypted_flag_downgrade_clears_payload(self):
flag = self._create_encrypted_flag()
@@ -4554,22 +4587,44 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertIsInstance(stored_payload, str)
self.assertEqual(json.loads(stored_payload), {"key": "value"})
- # Other valid JSON types (number, boolean, null, array) should be accepted
- number_payload = self._create_flag_with_properties(
- "number-payload-flag",
+ @parameterized.expand(
+ [
+ ("number", 42),
+ ("boolean", True),
+ ("null", None),
+ ("array", [1, 2, 3]),
+ ]
+ )
+ def test_non_string_payloads_are_normalized_to_json_strings(self, name, raw_value):
+ # Other valid JSON types (number, boolean, null, array) are accepted and
+ # normalized to JSON strings, matching how object payloads are stored.
+ response = self._create_flag_with_properties(
+ f"{name}-payload-flag",
[{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": 42},
+ payloads={"true": raw_value},
expected_status=status.HTTP_201_CREATED,
)
- self.assertEqual(number_payload.status_code, status.HTTP_201_CREATED)
+ stored = response.json()["filters"]["payloads"]["true"]
+ self.assertIsInstance(stored, str)
+ self.assertEqual(json.loads(stored), raw_value)
- boolean_payload = self._create_flag_with_properties(
- "boolean-payload-flag",
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("whitespace", " "),
+ ]
+ )
+ def test_blank_string_payloads_are_rejected(self, name, blank_value):
+ # An empty or whitespace-only string isn't valid JSON (the common "user cleared
+ # the field" case), so it's rejected rather than coerced.
+ response = self._create_flag_with_properties(
+ f"{name}-payload-flag",
[{"key": "key", "value": "value", "type": "person"}],
- payloads={"true": True},
- expected_status=status.HTTP_201_CREATED,
+ payloads={"true": blank_value},
+ expected_status=status.HTTP_400_BAD_REQUEST,
)
- self.assertEqual(boolean_payload.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "Payload value is not valid JSON")
def test_creating_feature_flag_with_behavioral_cohort(self):
cohort_valid_for_ff = Cohort.objects.create(