: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
feat(product-analytics): validate test account filters for mcp/api (#58129)
Thomas Obermüllerb3d0badfec34
diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 77b4272447fc..062c1dfb82f5 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -16,6 +16,8 @@ from django.utils.dateparse import parse_datetimefrom drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom opentelemetry import trace+from pydantic import TypeAdapter+from pydantic_core import ValidationError as PydanticValidationErrorfrom rest_framework import exceptions, request, response, serializers, viewsetsfrom rest_framework.permissions import BasePermission, IsAuthenticated@@ -73,6 +75,7 @@ from posthog.session_recordings.data_retention import (retention_violates_entitlement,validate_retention_period,)+from posthog.types import AnyPropertyFilterfrom posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixinfrom posthog.utils import (get_instance_realm,@@ -384,6 +387,21 @@ def _validate_trigger_property_filters(properties: object, context: str) -> Noneraise exceptions.ValidationError(f"{context}: property {prop_idx} must have a 'value' field.")+test_account_filters_adapter = TypeAdapter(list[AnyPropertyFilter])+++def validate_test_account_filters(value: object) -> list[dict[str, object]]:+ if not getattr(settings, "TEST_ACCOUNT_FILTERS_STRICT_VALIDATION_ENABLED", False):+ return cast(list[dict[str, object]], value)++ try:+ test_account_filters_adapter.validate_python(value)+ except PydanticValidationError as error:+ raise exceptions.ValidationError(f"Must provide an array of valid property filters. {error}") from error++ return cast(list[dict[str, object]], value)++_default_theme_id_cache: int | None = None@@ -580,6 +598,10 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixindef get_available_setup_task_ids(self, obj) -> list[str]:return [e.value for e in SetupTaskId]+ @staticmethod+ def validate_test_account_filters(value: object) -> list[dict[str, object]]:+ return validate_test_account_filters(value)+@staticmethoddef validate_revenue_analytics_config(value):if value is None:diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 502d4b0e2634..ea92b9bf85a1 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -3230,6 +3230,57 @@ class TestTeamAPI(team_api_test_factory()): # type: ignoreassert sorted(data.keys()) == ["timezone"]assert data["timezone"] in ("UTC", "Europe/London")+ @parameterized.expand(+ [+ (+ "missing_key",+ [{"type": "person", "operator": "exact", "value": "posthog.com"}],+ ),+ (+ "invalid_type",+ [{"key": "email", "type": "not_a_type", "operator": "exact", "value": "posthog.com"}],+ ),+ (+ "invalid_operator",+ [{"key": "email", "type": "person", "operator": "not_an_operator", "value": "posthog.com"}],+ ),+ (+ "invalid_cohort_value",+ [{"key": "id", "type": "cohort", "operator": "in", "value": "not-a-cohort-id"}],+ ),+ ]+ )+ def test_validate_test_account_filters_rejects_invalid_filters(+ self, _name: str, test_account_filters: list[dict[str, Any]]+ ):+ original_test_account_filters = self.team.test_account_filters++ with self.settings(TEST_ACCOUNT_FILTERS_STRICT_VALIDATION_ENABLED=True):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/",+ {"test_account_filters": test_account_filters},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "test_account_filters")+ self.assertIn("Must provide an array of valid property filters.", response.json()["detail"])++ self.team.refresh_from_db()+ self.assertEqual(self.team.test_account_filters, original_test_account_filters)++ def test_validate_test_account_filters_allows_is_set_filters_without_value(self):+ with self.settings(TEST_ACCOUNT_FILTERS_STRICT_VALIDATION_ENABLED=True):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/",+ {"test_account_filters": [{"key": "email", "type": "person", "operator": "is_set"}]},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json()["test_account_filters"],+ [{"key": "email", "type": "person", "operator": "is_set"}],+ )+class TestTeamSerializerHomeViewWins(APIBaseTest):def setUp(self):