: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(flags): support system writes through the facade (#71353)
Andersf312ae7353d6
diff --git a/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml b/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yamlindex fbeaa7d46e58..503a371028ee 100644--- a/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml+++ b/.semgrep/rules/devex/feature-flags-no-raw-filters-access.yaml@@ -37,8 +37,6 @@ rules:- '/posthog/tasks/update_survey_iteration.py'- '/products/early_access_features/backend/api.py'- '/products/early_access_features/backend/apps.py'- - '/products/experiments/backend/experiment_service.py'- - '/products/experiments/backend/experiment_summary_data_service.py'patterns:- pattern-either:- pattern: $FLAG.filters[$KEY]diff --git a/posthog/api/utils.py b/posthog/api/utils.pyindex b1ee0395ae2c..931768867e9d 100644--- a/posthog/api/utils.py+++ b/posthog/api/utils.py@@ -61,10 +61,15 @@ class ServiceRequest:Provides the subset of the DRF Request interface that serializers actuallyuse (request.user and friends), without DRF's authentication machinery.++ ``is_system=True`` explicitly declares a system write with no acting user —+ the approval gate skips only requests that declare this, never inferring it+ from a merely absent user."""- def __init__(self, user: Any):+ def __init__(self, user: Any, *, is_system: bool = False):self.user = user+ self.is_system = is_systemself.method = "POST"self.path = "/"self.data: dict = {}diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.pyindex a465a73451db..457bccf66c28 100644--- a/products/approvals/backend/decorators.py+++ b/products/approvals/backend/decorators.py@@ -499,6 +499,15 @@ def approval_gate(action_refs: Union[type, str, list]):request = args[0] if args else kwargs.get("request")_, team, organization = _extract_context(self, request)+ # System writes (facade calls from tasks or service code) bypass the gate:+ # approval policies target human-driven changes, and a ChangeRequest cannot+ # exist without a requester to attribute it to. Only a request explicitly+ # declaring itself a system write takes this path (`is True` so mocks and+ # attribute-forwarding proxies can't) — a merely user-less request, e.g. a+ # pre-auth HttpRequest, still engages the gate.+ if getattr(request, "is_system", False) is True:+ return method(self, *args, **kwargs)+if not team or not organization:logger.warning(f"No team/org context in {'serializer' if is_serializer else 'viewset'}, skipping approval gate"diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.pyindex 1d79f09aa31f..7c107d9dbe36 100644--- a/products/approvals/backend/tests/test_decorators.py+++ b/products/approvals/backend/tests/test_decorators.py@@ -1,10 +1,13 @@+from contextlib import suppressfrom typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from posthog.api.utils import ServiceRequest+from products.approvals.backend.exceptions import ApprovalRequired-from products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -103,3 +106,52 @@ class TestApprovalGateFailsClosed(APIBaseTest):flag.refresh_from_db()assert flag.active is True++ def test_gate_passes_through_for_declared_system_request(self, _mock_enabled):+ flag = self._create_disabled_flag()+ self._create_enable_policy()++ serializer = self._serializer(+ flag,+ {"active": True},+ {+ "request": ServiceRequest(None, is_system=True),+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "get_team": lambda: self.team,+ "get_organization": lambda: self.organization,+ },+ )++ serializer.save()++ flag.refresh_from_db()+ assert flag.active is True+ assert ChangeRequest.objects.count() == 0++ def test_userless_request_without_system_marker_still_engages_gate(self, _mock_enabled):+ flag = self._create_disabled_flag()+ self._create_enable_policy()+ request = self._drf_request({"active": True})+ request.user = None+ request.is_system = False++ serializer = self._serializer(+ flag,+ {"active": True},+ {+ "request": request,+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ "get_team": lambda: self.team,+ "get_organization": lambda: self.organization,+ },+ )++ # A user-less request that doesn't declare itself a system write must not skip+ # the gate — whatever the gate does with it, the write must not apply.+ with suppress(Exception):+ serializer.save()++ flag.refresh_from_db()+ assert flag.active is Falsediff --git a/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.pyindex dffdc9a8c2fb..75c41b4d0efb 100644--- a/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py+++ b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py@@ -43,6 +43,7 @@ from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, Chafrom products.approvals.backend.services import ChangeRequestServicefrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.facade.api import set_flag_activefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -503,6 +504,18 @@ class TestBypassMatrixControls(FeatureFlagBypassMatrixBase):assert flag.active is Trueassert ChangeRequest.objects.count() == 0+ def test_system_disable_under_policy_applies_without_change_request(self, _mock_enabled):+ # System writes (user=None through the facade) are the one sanctioned gate skip:+ # the change applies directly and no ChangeRequest is created.+ _enable_policy_for(self, "feature_flag.disable")+ flag = self._flag(active=True)++ set_flag_active(flag, False, team=self.team, user=None)++ flag.refresh_from_db()+ assert flag.active is False+ assert ChangeRequest.objects.count() == 0+def test_approving_pending_cr_applies_the_change(self, _mock_enabled):_enable_policy_for(self, "feature_flag.enable")flag = self._flag(active=False)diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 126474448b6f..85b193938d82 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -95,7 +95,6 @@ from products.feature_flags.backend.facade.filters import (set_holdout,strip_group_cohort_restriction,)-from products.feature_flags.backend.facade.rules import experiment_rule_from_filtersfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_errorfrom products.notifications.backend.facade.api import (NotificationData,@@ -1223,7 +1222,7 @@ class ExperimentService:if existing_flag:self._validate_existing_flag(existing_flag)- variants = experiment_rule_from_filters(existing_flag.filters or {}).variants or list(DEFAULT_VARIANTS)+ variants = existing_flag.variants or list(DEFAULT_VARIANTS)return existing_flag, variantsconfig = feature_flag_config or {}@@ -2556,11 +2555,10 @@ class ExperimentService:if request is not None:update_flag(flag, {"filters": stripped_filters}, team=self.team, user=self.user, request=request)else:- # FeatureFlagSerializer needs a real request for its context; for non-HTTP callers- # write directly — flag caches still refresh via model save signals, only the flag's- # activity-log entry is skipped.- flag.filters = stripped_filters- flag.save(update_fields=["filters"])+ # Non-HTTP callers have no acting user: a system write (user=None) skips the+ # approval gate — this runs inside the caller's transaction, where an+ # ApprovalRequired could never surface as a 409/change request anyway.+ update_flag(flag, {"filters": stripped_filters}, team=self.team, user=None)flag.refresh_from_db()experiment.feature_flag = flagdiff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 7103f50f0445..6eb326636309 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -28,6 +28,7 @@ from posthog.exceptions import (ClickHouseQueryTimeOut,)from posthog.models import OrganizationMembership, Team, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.actions.backend.models.action import Action@@ -4246,6 +4247,26 @@ class TestExperimentService(APIBaseTest):cohort.refresh_from_db()assert cohort.deleted is True+ def test_reset_experiment_clears_freeze_without_request(self):+ experiment = self._create_running_experiment(name="Reset No Request", feature_flag_key="reset-no-request-flag")+ original_groups = deepcopy(experiment.feature_flag.filters["groups"])+ with self._stub_freeze_population():+ frozen = self._service().freeze_exposure(experiment, request=self._make_request())++ # Non-HTTP callers (no request/user) still route the freeze-strip through the+ # gated facade write, attributed as a system change in the activity log.+ with self.captureOnCommitCallbacks(execute=True):+ reset = self._service().reset_experiment(frozen)++ assert reset.is_draft+ reset.feature_flag.refresh_from_db()+ assert reset.feature_flag.filters["groups"] == original_groups+ log = ActivityLog.objects.filter(+ scope="FeatureFlag", item_id=str(reset.feature_flag_id), activity="updated"+ ).latest("created_at")+ assert log.is_system is True+ assert log.user is None+@parameterized.expand([("referenced_by_another_flag", 'Exposure snapshot for experiment "Victim"'),diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 2cab11487f2a..31de18b098f4 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -647,7 +647,8 @@ class EvaluationTagsChecker:@staticmethoddef is_enabled(request) -> bool:"""Check if evaluation contexts feature is enabled for the request user."""- if not hasattr(request, "user") or request.user.is_anonymous:+ # request.user is None on facade system writes (ServiceRequest(None))+ if getattr(request, "user", None) is None or request.user.is_anonymous:return False# Check FLAG_EVALUATION_TAGS feature flagdiff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex 984507cd52ab..05f1a5e94cb0 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -14,6 +14,13 @@ Approval-gate ordering constraint for callers: a gated write can raise ``Approva(surfacing as a 409 + change_request_id), which conflicts with ``transaction.atomic`` — theexception propagating out of an atomic block would roll back the just-created pendingChangeRequest. Run gated writes before/outside any transaction wrapping your own state.++System writes: callers with no acting user (beat tasks, service code reacting to+lifecycle events) pass ``user=None``. The write still routes through the serializer+(validation, caches, activity logging — attributed as ``is_system``), but the approval+gate does not engage: the request shim explicitly declares ``is_system=True``, the only+signal the gate skips on (its policies target human-driven changes, and a request-less+caller cannot surface a 409/change request), so ``ApprovalRequired`` is never raised."""from typing import Any@@ -35,11 +42,18 @@ def _serializer_context(team: Team, user: Any, request: Any | None) -> dict:Callers without a real request (internal service paths) fall back to a minimalrequest shim carrying the acting user — FeatureFlagSerializer needs request.user.+ ``user=None`` makes this a system write (see module docstring); the shim declares+ it explicitly via ``is_system``, the only signal the approval gate skips on.Pass BOTH get_team and get_organization so the approval gate resolves the policyfrom context rather than falling back to instance derivation."""- flag_request = request if getattr(request, "user", None) is not None else ServiceRequest(user)+ request_has_user = getattr(request, "user", None) is not None+ # A user-bearing request would silently override user=None (gate engages, attribution+ # goes to request.user) — reject the contradiction instead.+ if user is None and request_has_user:+ raise ValueError("user=None is a system write; do not pass a user-bearing request with it")+ flag_request = request if request_has_user else ServiceRequest(user, is_system=user is None)return {"request": flag_request,"team_id": team.id,@@ -53,7 +67,8 @@ def create_flag(data: dict, *, team: Team, user: Any, request: Any | None = None"""Gated create: routes through FeatureFlagSerializer so @approval_gate, validation,and activity logging apply. ``data`` is the flag's own write shape (key, name, filters,active, ...) and is applied as-is — nothing is silently dropped. Raises ApprovalRequired- when a policy requires approval."""+ when a policy requires approval. ``user=None`` is a system write (see module docstring):+ ``created_by`` stays null, activity is logged as system, the approval gate is skipped."""serializer = FeatureFlagSerializer(data=data, context=_serializer_context(team, user, request))serializer.is_valid(raise_exception=True)return serializer.save()@@ -63,7 +78,9 @@ def update_flag(flag: FeatureFlag, data: dict, *, team: Team, user: Any, request"""Gated partial update: routes through FeatureFlagSerializer so @approval_gate,validation, and activity logging apply. ``data`` is a partial flag write payload(fields it omits are untouched) applied as-is — nothing is silently dropped.- Raises ApprovalRequired when a policy requires approval; the flag is left untouched."""+ Raises ApprovalRequired when a policy requires approval; the flag is left untouched.+ ``user=None`` is a system write (see module docstring): ``last_modified_by`` is+ cleared, activity is logged as system, the approval gate is skipped."""serializer = FeatureFlagSerializer(flag, data=data, partial=True, context=_serializer_context(team, user, request))serializer.is_valid(raise_exception=True)return serializer.save()diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 80a2c5e3e23b..e0768c259fa2 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -7,15 +7,20 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError+from posthog.api.utils import ServiceRequestfrom posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLogfrom products.approvals.backend.exceptions import ApprovalRequired-from products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.feature_flags.backend.facade.api import (_roll_out_variant,archive_flag,+ create_flag,flag_disable_requires_approval,+ set_flag_active,ship_variant,+ update_flag,)from products.feature_flags.backend.facade.filters import (group_cohort_restriction_blocker,@@ -116,6 +121,73 @@ class TestFeatureFlagFacadeGatedWrites(APIBaseTest):assert flag.archived is Falseassert flag.active is True+ def test_system_create_logs_system_activity(self):+ with self.captureOnCommitCallbacks(execute=True):+ flag = create_flag(+ {+ "key": "system-created-flag",+ "name": "System created",+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ },+ team=self.team,+ user=None,+ )++ assert flag.created_by is None+ assert flag.last_modified_by is None+ log = ActivityLog.objects.get(scope="FeatureFlag", item_id=str(flag.id), activity="created")+ assert log.is_system is True+ assert log.user is None++ def test_system_update_logs_system_activity(self):+ flag = self._create_flag(active=True)++ with self.captureOnCommitCallbacks(execute=True):+ update_flag(+ flag,+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 55}]}},+ team=self.team,+ user=None,+ )++ flag.refresh_from_db()+ assert flag.filters["groups"][0]["rollout_percentage"] == 55+ assert flag.last_modified_by is None+ log = ActivityLog.objects.get(scope="FeatureFlag", item_id=str(flag.id), activity="updated")+ assert log.is_system is True+ assert log.user is None++ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_system_write_never_raises_approval_required(self, _mock_enabled):+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.disable",+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )+ flag = self._create_flag(active=True)++ set_flag_active(flag, False, team=self.team, user=None)++ flag.refresh_from_db()+ assert flag.active is False+ assert not ChangeRequest.objects.filter(team=self.team).exists()++ def test_system_write_rejects_user_bearing_request(self):+ flag = self._create_flag(active=True)++ with self.assertRaises(ValueError):+ update_flag(flag, {"active": False}, team=self.team, user=None, request=ServiceRequest(self.user))++ flag.refresh_from_db()+ assert flag.active is True+class TestRollOutVariant:def test_transform_filters_default_preserves_groups(self):