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): require feature_flag:write for survey and EAF flag writes (#64128)

Lucas Faria562064574a9f
diff --git a/posthog/permissions.py b/posthog/permissions.py
index c7d5ce75868e..98e93c16a397 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -508,6 +508,23 @@ class ScopeBasePermission(BasePermission):
return None
+def get_authenticator_scopes(authenticator) -> list[str] | None:
+ """The API scopes carried by a scoped-token authenticator, or None for session and
+ other non-token auth. Single source of truth for the token->scopes mapping, shared by
+ APIScopePermission and cross-resource scope checks so the two cannot drift — if they
+ did, one path could grant access while the other skipped its check."""
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ return list(authenticator.personal_api_key.scopes or [])
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ # OAuth tokens store scopes as a space-separated string.
+ return str(authenticator.access_token.scope or "").split()
+ if isinstance(authenticator, IDJagAccessTokenAuthentication):
+ return list(authenticator.scopes or [])
+ if isinstance(authenticator, ProjectSecretAPIKeyAuthentication):
+ return list(authenticator.project_secret_api_key.scopes or [])
+ return None
+
+
class APIScopePermission(ScopeBasePermission):
"""
The request is via an API key or OAuth token and the user has the appropriate scopes.
@@ -529,28 +546,9 @@ class APIScopePermission(ScopeBasePermission):
authenticator = request.successful_authenticator
is_psak = isinstance(authenticator, ProjectSecretAPIKeyAuthentication)
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- key_scopes = authenticator.personal_api_key.scopes
- elif isinstance(authenticator, OAuthAccessTokenAuthentication):
- # OAuth tokens store scopes as space-separated string
- token_scope_string = authenticator.access_token.scope
- key_scopes = token_scope_string.split() if token_scope_string else []
- # OAuth tokens with no scopes should not have access
- if not key_scopes:
- self.message = "OAuth token has no scopes and cannot access this resource"
- return False
- elif isinstance(request.successful_authenticator, IDJagAccessTokenAuthentication):
- key_scopes = list(request.successful_authenticator.scopes)
- if not key_scopes:
- self.message = "ID-JAG access token has no scopes and cannot access this resource"
- return False
- elif is_psak:
- psak_allowed_actions = getattr(view, "psak_allowed_actions", self.psak_allowed_actions)
- if self._get_action(request, view) not in psak_allowed_actions:
- self.message = "This action does not support project secret API key access"
- return False
- key_scopes = authenticator.project_secret_api_key.scopes or []
- else:
+ key_scopes = get_authenticator_scopes(authenticator)
+
+ if key_scopes is None:
# Session (and other non-token) auth normally bypasses API-scope checks — scopes
# are a PAK/OAuth concept; logged-in users are gated by team membership + access
# control instead. But INTERNAL scope objects are a programmatic-only security
@@ -566,6 +564,19 @@ class APIScopePermission(ScopeBasePermission):
return False
return True
+ # Token auth: per-type preconditions the shared scope extractor doesn't cover.
+ if isinstance(authenticator, OAuthAccessTokenAuthentication) and not key_scopes:
+ self.message = "OAuth token has no scopes and cannot access this resource"
+ return False
+ if isinstance(authenticator, IDJagAccessTokenAuthentication) and not key_scopes:
+ self.message = "ID-JAG access token has no scopes and cannot access this resource"
+ return False
+ if is_psak:
+ psak_allowed_actions = getattr(view, "psak_allowed_actions", self.psak_allowed_actions)
+ if self._get_action(request, view) not in psak_allowed_actions:
+ self.message = "This action does not support project secret API key access"
+ return False
+
required_scopes = self._get_required_scopes(request, view)
if not required_scopes:
diff --git a/products/early_access_features/backend/api.py b/products/early_access_features/backend/api.py
index 749f663a24b3..88a234e803fe 100644
--- a/products/early_access_features/backend/api.py
+++ b/products/early_access_features/backend/api.py
@@ -23,7 +23,7 @@ from posthog.utils_cors import cors_response
from products.feature_flags.backend.api.feature_flag import (
FeatureFlagSerializer,
MinimalFeatureFlagSerializer,
- warn_if_missing_feature_flag_write_scope,
+ assert_feature_flag_write_scope,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -120,18 +120,20 @@ class EarlyAccessFeatureSerializer(serializers.ModelSerializer):
serialized_previous = MinimalEarlyAccessFeatureSerializer(instance).data
if instance.stage != stage:
- if "stage" in self.initial_data and instance.feature_flag is not None:
- warn_if_missing_feature_flag_write_scope(
- request,
- action="early_access_feature.stage_change",
- team_id=instance.team_id,
- feature_flag_id=instance.feature_flag.id,
- )
send_events_for_early_access_feature_stage_change.delay(str(instance.id), instance.stage, stage)
+ # The branches below each mutate the linked flag's enrollment filters, so they require
+ # feature_flag:write. A stage change that writes no flag row is intentionally not gated.
if instance.stage != stage and stage == EarlyAccessFeature.Stage.GENERAL_AVAILABILITY and rollout_to_all:
related_feature_flag = instance.feature_flag
if related_feature_flag:
+ assert_feature_flag_write_scope(
+ request,
+ action="early_access_feature.stage_change",
+ resource_scope="early_access_feature:write",
+ team_id=instance.team_id,
+ feature_flag_id=related_feature_flag.id,
+ )
serialized_data_filters = _set_enrollment_filters(
related_feature_flag.filters,
enrolled=None,
@@ -149,6 +151,13 @@ class EarlyAccessFeatureSerializer(serializers.ModelSerializer):
elif instance.stage not in EarlyAccessFeature.ActiveStage and stage in EarlyAccessFeature.ActiveStage:
related_feature_flag = instance.feature_flag
if related_feature_flag:
+ assert_feature_flag_write_scope(
+ request,
+ action="early_access_feature.stage_change",
+ resource_scope="early_access_feature:write",
+ team_id=instance.team_id,
+ feature_flag_id=related_feature_flag.id,
+ )
serialized_data_filters = _set_enrollment_filters(related_feature_flag.filters, enrolled=True)
serializer = FeatureFlagSerializer(
@@ -162,6 +171,13 @@ class EarlyAccessFeatureSerializer(serializers.ModelSerializer):
elif stage is not None and (stage not in EarlyAccessFeature.ActiveStage):
related_feature_flag = instance.feature_flag
if related_feature_flag:
+ assert_feature_flag_write_scope(
+ request,
+ action="early_access_feature.stage_change",
+ resource_scope="early_access_feature:write",
+ team_id=instance.team_id,
+ feature_flag_id=related_feature_flag.id,
+ )
related_feature_flag.filters = _set_enrollment_filters(related_feature_flag.filters, enrolled=None)
related_feature_flag.save()
@@ -253,13 +269,6 @@ class EarlyAccessFeatureSerializerCreateOnly(EarlyAccessFeatureSerializer):
def create(self, validated_data):
validated_data["team_id"] = self.context["team_id"]
- warn_if_missing_feature_flag_write_scope(
- self.context["request"],
- action="early_access_feature.create",
- team_id=self.context["team_id"],
- feature_flag_id=validated_data.get("feature_flag_id"),
- )
-
feature_flag_id = validated_data.get("feature_flag_id", None)
default_condition = [
@@ -269,7 +278,16 @@ class EarlyAccessFeatureSerializerCreateOnly(EarlyAccessFeatureSerializer):
if feature_flag_id:
feature_flag = FeatureFlag.objects.get(pk=feature_flag_id, team_id=self.context["team_id"])
+ # Only require feature_flag:write when we actually mutate the linked flag (active
+ # stage). Linking an existing flag without changing it is not a flag write.
if validated_data.get("stage") in EarlyAccessFeature.ActiveStage:
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="early_access_feature.create",
+ resource_scope="early_access_feature:write",
+ team_id=self.context["team_id"],
+ feature_flag_id=feature_flag.id,
+ )
serialized_data_filters = _set_enrollment_filters(feature_flag.filters, enrolled=True)
serializer = FeatureFlagSerializer(
@@ -281,6 +299,13 @@ class EarlyAccessFeatureSerializerCreateOnly(EarlyAccessFeatureSerializer):
serializer.is_valid(raise_exception=True)
serializer.save()
else:
+ # No existing flag: we create one, which is a flag write.
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="early_access_feature.create",
+ resource_scope="early_access_feature:write",
+ team_id=self.context["team_id"],
+ )
feature_flag_key = slugify(validated_data["name"])
filters: dict[str, Any] = {
@@ -323,11 +348,12 @@ class EarlyAccessFeatureViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
related_feature_flag = instance.feature_flag
if related_feature_flag:
- warn_if_missing_feature_flag_write_scope(
+ assert_feature_flag_write_scope(
request,
action="early_access_feature.destroy",
team_id=instance.team_id,
feature_flag_id=related_feature_flag.id,
+ resource_scope="early_access_feature:write",
)
related_feature_flag.filters = _set_enrollment_filters(related_feature_flag.filters, enrolled=None)
related_feature_flag.save()
diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.py
index 75b8223ce167..bf7fc025d3de 100644
--- a/products/early_access_features/backend/test/test_early_access_feature.py
+++ b/products/early_access_features/backend/test/test_early_access_feature.py
@@ -1318,3 +1318,98 @@ class TestEarlyAccessFeatureScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert self._warning_events(mock_logger) == []
+
+
+class TestEarlyAccessFeatureScopeEnforcement(PersonalAPIKeysBaseTest, APIBaseTest):
+ # Enforcement (raise 403) is gated behind a rollout flag; force it on for this class.
+ CREATE_PAYLOAD = {
+ "name": "Scope enforcement feature",
+ "description": "x",
+ "stage": "concept",
+ }
+
+ def setUp(self):
+ super().setUp()
+ self.key.scopes = ["early_access_feature:write"]
+ self.key.save()
+ self.auth_headers = {"authorization": f"Bearer {self.value}"}
+ enforce_patcher = patch(
+ "products.feature_flags.backend.api.feature_flag._is_enforce_feature_flag_write_scope_enabled",
+ return_value=True,
+ )
+ enforce_patcher.start()
+ self.addCleanup(enforce_patcher.stop)
+
+ def _create_feature(self, **extra):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/early_access_feature/",
+ data={**self.CREATE_PAYLOAD, **extra},
+ format="json",
+ headers=self.auth_headers,
+ )
+
+ def _create_feature_as_admin(self):
+ self.key.scopes = ["*"]
+ self.key.save()
+ feature_id = self._create_feature().json()["id"]
+ self.key.scopes = ["early_access_feature:write"]
+ self.key.save()
+ return feature_id
+
+ @parameterized.expand(
+ [
+ ("eaf_write_only", ["early_access_feature:write"], status.HTTP_403_FORBIDDEN),
+ ("with_feature_flag_write", ["early_access_feature:write", "feature_flag:write"], status.HTTP_201_CREATED),
+ ("wildcard", ["*"], status.HTTP_201_CREATED),
+ ]
+ )
+ def test_create_scope_matrix(self, _name, scopes, expected_status):
+ self.key.scopes = scopes
+ self.key.save()
+ response = self._create_feature()
+ assert response.status_code == expected_status, response.json()
+ if expected_status == status.HTTP_403_FORBIDDEN:
+ assert "feature_flag:write" in response.json()["detail"]
+
+ def test_update_stage_change_is_denied(self):
+ feature_id = self._create_feature_as_admin()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/early_access_feature/{feature_id}/",
+ data={"stage": "beta"},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_update_without_stage_change_is_allowed(self):
+ feature_id = self._create_feature_as_admin()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/early_access_feature/{feature_id}/",
+ data={"description": "updated"},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_create_linking_existing_flag_without_mutation_is_allowed(self):
+ # Linking an existing flag at a non-active stage writes no flag row, so it is not gated.
+ flag = FeatureFlag.objects.create(team=self.team, key="eaf-link-only", created_by=self.user)
+ response = self._create_feature(feature_flag_id=flag.id, stage="concept")
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ def test_destroy_is_denied(self):
+ feature_id = self._create_feature_as_admin()
+ response = self.client.delete(
+ f"/api/projects/{self.team.id}/early_access_feature/{feature_id}/",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_session_auth_is_allowed(self):
+ self.client.force_login(self.user)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/early_access_feature/",
+ data=self.CREATE_PAYLOAD,
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index ea7ae4f40748..c2f02c15d1f8 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -38,7 +38,12 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSet
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action
from posthog.approvals.decorators import approval_gate
from posthog.approvals.mixins import ApprovalHandlingMixin
-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication
+from posthog.auth import (
+ IDJagAccessTokenAuthentication,
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ TeamSecretTokenAuthentication,
+)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.constants import FlagRequestType
from posthog.event_usage import report_user_action
@@ -54,7 +59,7 @@ from posthog.models.person.point_in_time_properties import (
get_person_and_distinct_ids_for_identifier,
)
from posthog.models.property import Property
-from posthog.permissions import TeamSecretTokenPermission
+from posthog.permissions import TeamSecretTokenPermission, get_authenticator_scopes
from posthog.queries.base import determine_parsed_date_for_property_matching
from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
@@ -104,6 +109,12 @@ BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"
REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"
EARLY_EXIT_FLAG = "feature-flag-early-exit"
+# Gates enforcement of `feature_flag:write` on cross-resource flag mutations
+# (Survey / Early Access Feature endpoints). Kept off during the migration grace
+# period so we can notify affected customers before flipping it on per-org, then
+# to 100%. Remove the gate and make enforcement unconditional once fully rolled out.
+ENFORCE_FEATURE_FLAG_WRITE_SCOPE_FLAG = "enforce-feature-flag-write-scope-cross-resource"
+
def parse_created_by_ids(value: Any) -> list[int]:
"""Parse a `created_by_id` filter value into a list of user IDs.
@@ -158,34 +169,66 @@ RUST_FLAG_FIELDS = (
)
-def warn_if_missing_feature_flag_write_scope(
+def _is_enforce_feature_flag_write_scope_enabled(request, *, team_id: int | None) -> bool:
+ # Rollout gate for the feature_flag:write enforcement below. Evaluated against the
+ # organization that owns the *target* team, not the actor's current organization —
+ # otherwise a multi-org user could dodge enforcement by switching their current org
+ # to one where the rollout is off. Fails open (returns False) on missing context or
+ # any error, so a flag-service outage degrades to warn-only rather than blocking
+ # writes; the error is logged so a persistent failure is visible rather than silent.
+ user = getattr(request, "user", None)
+ if user is None or user.is_anonymous or team_id is None:
+ return False
+ try:
+ organization_id = str(Team.objects.values_list("organization_id", flat=True).get(pk=team_id))
+ return posthoganalytics.feature_enabled(
+ ENFORCE_FEATURE_FLAG_WRITE_SCOPE_FLAG,
+ user.distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("enforce_feature_flag_write_scope_eval_failed", exc_info=True)
+ return False
+
+
+def _scope_audit_identity(authenticator) -> tuple[list[str], str, str | None, str | None] | None:
+ # (scopes, auth_kind, auth_id, auth_label) for a scoped token, or None for session and
+ # other non-token auth. Scope extraction is single-sourced via get_authenticator_scopes
+ # so the enforcement decision can't drift from APIScopePermission; the auth_kind/id/label
+ # below are audit-log metadata only.
+ scopes = get_authenticator_scopes(authenticator)
+ if scopes is None:
+ return None
+ if isinstance(authenticator, PersonalAPIKeyAuthentication):
+ key = authenticator.personal_api_key
+ return scopes, "personal_api_key", key.id, key.label
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ raw_id = getattr(authenticator.access_token, "id", None)
+ return scopes, "oauth_access_token", str(raw_id) if raw_id is not None else None, None
+ if isinstance(authenticator, IDJagAccessTokenAuthentication):
+ return scopes, "id_jag_access_token", None, None
+ psak = authenticator.project_secret_api_key
+ return scopes, "project_secret_api_key", str(getattr(psak, "id", "")) or None, None
+
+
+def assert_feature_flag_write_scope(
request,
*,
action: str,
+ resource_scope: str,
team_id: int | None = None,
feature_flag_id: int | None = None,
) -> None:
- # Temporary observability for a cross-resource scope bypass: SurveyViewSet and
- # EarlyAccessFeatureViewSet mutate FeatureFlag rows under their own scope
- # (`survey:write` / `early_access_feature:write`). Before enforcing
- # `feature_flag:write` on these paths we want to know which customers rely on
- # the transitive access so we can notify them. Remove this helper and its
- # call sites once the scope is enforced.
- authenticator = getattr(request, "successful_authenticator", None)
- if isinstance(authenticator, PersonalAPIKeyAuthentication):
- scopes = list(authenticator.personal_api_key.scopes or [])
- auth_kind = "personal_api_key"
- auth_id: str | None = authenticator.personal_api_key.id
- auth_label: str | None = authenticator.personal_api_key.label
- elif isinstance(authenticator, OAuthAccessTokenAuthentication):
- scope_string = authenticator.access_token.scope or ""
- scopes = scope_string.split()
- auth_kind = "oauth_access_token"
- raw_id = getattr(authenticator.access_token, "id", None)
- auth_id = str(raw_id) if raw_id is not None else None
- auth_label = None
- else:
- return
+ # Survey and Early Access Feature endpoints write FeatureFlag rows under their own
+ # scope. Require feature_flag:write for those writes too: always audit-log when it's
+ # missing, and raise once the rollout gate is enabled for the org.
+ identity = _scope_audit_identity(getattr(request, "successful_authenticator", None))
+ if identity is None:
+ return # session / cookie auth has no scopes; access control is handled elsewhere
+ scopes, auth_kind, auth_id, auth_label = identity
if "*" in scopes or "feature_flag:write" in scopes:
return
@@ -202,6 +245,13 @@ def warn_if_missing_feature_flag_write_scope(
user_id=getattr(getattr(request, "user", None), "id", None),
)
+ if _is_enforce_feature_flag_write_scope_enabled(request, team_id=team_id):
+ raise exceptions.PermissionDenied(
+ f"This action also modifies a feature flag, which requires the `feature_flag:write` scope "
+ f"in addition to `{resource_scope}`. Add `feature_flag:write` to your API key, or use a key "
+ f"with the `*` scope."
+ )
+
def _is_realtime_cohort_flag_targeting_enabled(request) -> bool:
"""Check whether the realtime cohort flag targeting feature is enabled for this request."""
diff --git a/products/feature_flags/backend/api/test/test_scope_enforcement.py b/products/feature_flags/backend/api/test/test_scope_enforcement.py
new file mode 100644
index 000000000000..c1719267827c
--- /dev/null
+++ b/products/feature_flags/backend/api/test/test_scope_enforcement.py
@@ -0,0 +1,118 @@
+from types import SimpleNamespace
+
+from posthog.test.base import APIBaseTest
+from unittest import TestCase
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.auth import (
+ IDJagAccessTokenAuthentication,
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ ProjectSecretAPIKeyAuthentication,
+)
+from posthog.models import Organization, Team
+
+from products.feature_flags.backend.api.feature_flag import (
+ _is_enforce_feature_flag_write_scope_enabled,
+ _scope_audit_identity,
+)
+
+
+def _make(cls, **attrs):
+ instance = cls.__new__(cls)
+ for key, value in attrs.items():
+ setattr(instance, key, value)
+ return instance
+
+
+class TestScopeAuditIdentity(TestCase):
+ @parameterized.expand(
+ [
+ (
+ "personal_api_key",
+ _make(
+ PersonalAPIKeyAuthentication,
+ personal_api_key=SimpleNamespace(scopes=["survey:write"], id="pak_1", label="key"),
+ ),
+ ["survey:write"],
+ "personal_api_key",
+ ),
+ (
+ "oauth_access_token",
+ _make(OAuthAccessTokenAuthentication, access_token=SimpleNamespace(scope="survey:write a:b", id=7)),
+ ["survey:write", "a:b"],
+ "oauth_access_token",
+ ),
+ (
+ "id_jag_access_token",
+ _make(IDJagAccessTokenAuthentication, scopes=["early_access_feature:write"]),
+ ["early_access_feature:write"],
+ "id_jag_access_token",
+ ),
+ (
+ "project_secret_api_key",
+ _make(
+ ProjectSecretAPIKeyAuthentication,
+ project_secret_api_key=SimpleNamespace(scopes=["survey:write"], id=3),
+ ),
+ ["survey:write"],
+ "project_secret_api_key",
+ ),
+ ]
+ )
+ def test_extracts_scopes_for_every_token_type(self, _name, authenticator, expected_scopes, expected_kind):
+ identity = _scope_audit_identity(authenticator)
+ assert identity is not None
+ scopes, auth_kind, _auth_id, _auth_label = identity
+ assert scopes == expected_scopes
+ assert auth_kind == expected_kind
+
+ def test_returns_none_for_session_auth(self):
+ assert _scope_audit_identity(object()) is None
+ assert _scope_audit_identity(None) is None
+
+
+class TestEnforcementGateTargetsTeamOrg(APIBaseTest):
+ def test_gate_evaluates_against_target_team_org_not_actor_org(self):
+ # A user whose current org differs from the org owning the target team must be
+ # gated by the *target* team's org, so it can't be dodged by switching orgs.
+ other_org = Organization.objects.create(name="other org")
+ other_team = Team.objects.create(organization=other_org, name="other team")
+ request = SimpleNamespace(user=self.user)
+
+ with patch(
+ "products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled",
+ return_value=True,
+ ) as mock_feature_enabled:
+ result = _is_enforce_feature_flag_write_scope_enabled(request, team_id=other_team.id)
+
+ assert result is True
+ groups = mock_feature_enabled.call_args.kwargs["groups"]
+ assert groups["organization"] == str(other_org.id)
+ assert groups["organization"] != str(self.organization.id)
+
+ def test_gate_fails_closed_without_team_id(self):
+ request = SimpleNamespace(user=self.user)
+ assert _is_enforce_feature_flag_write_scope_enabled(request, team_id=None) is False
+
+ def test_gate_returns_false_for_anonymous_user(self):
+ request = SimpleNamespace(user=SimpleNamespace(is_anonymous=True))
+ assert _is_enforce_feature_flag_write_scope_enabled(request, team_id=self.team.id) is False
+
+ def test_gate_fails_closed_and_logs_on_error(self):
+ # A nonexistent team raises during org resolution; the gate logs and fails open.
+ request = SimpleNamespace(user=self.user)
+ with patch("products.feature_flags.backend.api.feature_flag.logger") as mock_logger:
+ result = _is_enforce_feature_flag_write_scope_enabled(request, team_id=999_999_999)
+ assert result is False
+ assert mock_logger.warning.called
+
+ def test_gate_returns_feature_enabled_result(self):
+ request = SimpleNamespace(user=self.user)
+ with patch(
+ "products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled",
+ return_value=False,
+ ):
+ assert _is_enforce_feature_flag_write_scope_enabled(request, team_id=self.team.id) is False
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index fcd54827e577..32baffa89c3b 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -65,7 +65,7 @@ from products.feature_flags.backend.api.feature_flag import (
BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
FeatureFlagSerializer,
MinimalFeatureFlagSerializer,
- warn_if_missing_feature_flag_write_scope,
+ assert_feature_flag_write_scope,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
@@ -1551,12 +1551,24 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
validated_data.pop("remove_targeting_flag")
validated_data["team_id"] = self.context["team_id"]
- warn_if_missing_feature_flag_write_scope(
- self.context["request"],
- action="survey.create",
- team_id=self.context["team_id"],
- )
+ if validated_data.get("targeting_flag_id"):
+ # Attaching an existing flag takes write control of it: its active state is later
+ # synced to the survey's lifecycle (start/stop/archive). Require feature_flag:write
+ # so survey:write alone can't point a survey at an arbitrary flag and toggle it.
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="survey.create.targeting_flag_id",
+ resource_scope="survey:write",
+ team_id=self.context["team_id"],
+ feature_flag_id=validated_data["targeting_flag_id"],
+ )
if validated_data.get("targeting_flag_filters"):
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="survey.create",
+ resource_scope="survey:write",
+ team_id=self.context["team_id"],
+ )
targeting_feature_flag = self._create_or_update_targeting_flag(
None, validated_data["targeting_flag_filters"], validated_data["name"]
)
@@ -1591,11 +1603,23 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
user = self.context["request"].user
changes = []
+ if validated_data.get("targeting_flag_id"):
+ # Re-pointing the survey at an existing flag takes write control of it (the
+ # lifecycle sync below can toggle its active state), so require feature_flag:write.
+ assert_feature_flag_write_scope(
+ self.context["request"],
+ action="survey.update.targeting_flag_id",
+ resource_scope="survey:write",
+ team_id=self.context["team_id"],
+ feature_flag_id=validated_data["targeting_flag_id"],
+ )
+
if validated_data.get("remove_targeting_flag"):
if instance.targeting_flag:
- warn_if_missing_feature_flag_write_scope(
+ assert_feature_flag_write_scope(
self.context["request"],
action="survey.update.remove_targeting_flag",
+ resource_scope="survey:write",
team_id=self.context["team_id"],
feature_flag_id=instance.targeting_flag_id,
)
@@ -1614,9 +1638,10 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
# if the target flag filters come back with data, update the targeting feature flag if there is one, otherwise create a new one
if validated_data.get("targeting_flag_filters"):
- warn_if_missing_feature_flag_write_scope(
+ assert_feature_flag_write_scope(
self.context["request"],
action="survey.update.targeting_flag_filters",
+ resource_scope="survey:write",
team_id=self.context["team_id"],
feature_flag_id=instance.targeting_flag_id,
)
@@ -1728,6 +1753,11 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
should_flag_be_active = self._should_survey_flags_be_active(instance)
+ # Intentionally NOT gated on feature_flag:write: this only syncs the active state of
+ # the survey's OWN dedicated targeting flag to the survey's running state (start/stop/
+ # archive), which survey:write already controls. The flag's definition (its filters)
+ # can only be set via the gated targeting_flag_filters path. Enforcement covers
+ # definition writes, not this lifecycle mirror.
if instance.targeting_flag:
instance.targeting_flag.active = should_flag_be_active
instance.targeting_flag.save()
@@ -2079,12 +2109,16 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
instance = self.get_object()
related_targeting_flag = instance.targeting_flag
related_internal_targeting_flag = instance.internal_targeting_flag
- if related_targeting_flag or related_internal_targeting_flag:
- warn_if_missing_feature_flag_write_scope(
+ # Only the user-defined targeting flag is gated; the internal targeting flag is a
+ # PostHog-managed implementation detail, so deleting a survey that only has one
+ # must not require `feature_flag:write`.
+ if related_targeting_flag:
+ assert_feature_flag_write_scope(
request,
action="survey.destroy",
+ resource_scope="survey:write",
team_id=self.team_id,
- feature_flag_id=(related_targeting_flag or related_internal_targeting_flag).id,
+ feature_flag_id=related_targeting_flag.id,
)
if related_targeting_flag:
related_targeting_flag.delete()
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 58f80f2e4cc2..b4e7c3c2049f 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -6970,6 +6970,7 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
"type": "popover",
"questions": [{"type": "open", "question": "Q?"}],
}
+ TARGETING_FILTERS = {"groups": [{"properties": [], "rollout_percentage": 50}]}
def setUp(self):
super().setUp()
@@ -6992,9 +6993,9 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
headers=self.auth_headers,
)
- def test_create_with_survey_write_only_logs_warning(self):
+ def test_create_with_targeting_flag_filters_and_survey_write_only_logs_warning(self):
with patch("products.feature_flags.backend.api.feature_flag.scope_audit_logger") as mock_logger:
- response = self._create_survey()
+ response = self._create_survey(targeting_flag_filters=self.TARGETING_FILTERS)
assert response.status_code == status.HTTP_201_CREATED, response.json()
events = self._warning_events(mock_logger)
assert len(events) == 1
@@ -7006,11 +7007,19 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
assert extra["auth_id"] == self.key.id
assert extra["user_id"] == self.user.id
+ def test_create_without_targeting_flag_filters_does_not_log(self):
+ # The auto-managed internal targeting flag is not a user-facing flag, so a plain
+ # survey create must not warn (or, once enforced, be blocked).
+ with patch("products.feature_flags.backend.api.feature_flag.scope_audit_logger") as mock_logger:
+ response = self._create_survey()
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert self._warning_events(mock_logger) == []
+
def test_create_with_feature_flag_write_does_not_log(self):
self.key.scopes = ["survey:write", "feature_flag:write"]
self.key.save()
with patch("products.feature_flags.backend.api.feature_flag.scope_audit_logger") as mock_logger:
- response = self._create_survey()
+ response = self._create_survey(targeting_flag_filters=self.TARGETING_FILTERS)
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert self._warning_events(mock_logger) == []
@@ -7018,7 +7027,7 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
self.key.scopes = ["*"]
self.key.save()
with patch("products.feature_flags.backend.api.feature_flag.scope_audit_logger") as mock_logger:
- response = self._create_survey()
+ response = self._create_survey(targeting_flag_filters=self.TARGETING_FILTERS)
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert self._warning_events(mock_logger) == []
@@ -7102,7 +7111,9 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
assert len(events) == 1
assert events[0].kwargs["action"] == "survey.destroy"
- def test_destroy_with_only_internal_targeting_flag_logs_warning(self):
+ def test_destroy_with_only_internal_targeting_flag_does_not_log(self):
+ # The internal targeting flag is PostHog-managed, so deleting a survey that only has
+ # one must not warn (or be blocked once enforced).
survey_id = self._create_survey().json()["id"]
survey = Survey.objects.get(pk=survey_id)
assert survey.targeting_flag_id is None
@@ -7114,10 +7125,7 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
headers=self.auth_headers,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
- events = self._warning_events(mock_logger)
- assert len(events) == 1
- assert events[0].kwargs["action"] == "survey.destroy"
- assert events[0].kwargs["feature_flag_id"] == survey.internal_targeting_flag_id
+ assert self._warning_events(mock_logger) == []
def test_destroy_without_any_flag_does_not_log(self):
survey = Survey.objects.create(
@@ -7144,3 +7152,142 @@ class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert self._warning_events(mock_logger) == []
+
+
+class TestSurveyFeatureFlagScopeEnforcement(PersonalAPIKeysBaseTest, APIBaseTest):
+ # Enforcement (raise 403) is gated behind a rollout flag; force it on for this class.
+ SURVEY_PAYLOAD = {
+ "name": "Scope enforcement survey",
+ "type": "popover",
+ "questions": [{"type": "open", "question": "Q?"}],
+ }
+ TARGETING_FILTERS = {"groups": [{"properties": [], "rollout_percentage": 50}]}
+
+ def setUp(self):
+ super().setUp()
+ self.key.scopes = ["survey:write"]
+ self.key.save()
+ self.auth_headers = {"authorization": f"Bearer {self.value}"}
+ enforce_patcher = patch(
+ "products.feature_flags.backend.api.feature_flag._is_enforce_feature_flag_write_scope_enabled",
+ return_value=True,
+ )
+ enforce_patcher.start()
+ self.addCleanup(enforce_patcher.stop)
+
+ def _create_survey(self, **extra):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={**self.SURVEY_PAYLOAD, **extra},
+ format="json",
+ headers=self.auth_headers,
+ )
+
+ def _create_survey_with_targeting_flag_as_admin(self):
+ self.key.scopes = ["*"]
+ self.key.save()
+ survey_id = self._create_survey(targeting_flag_filters=self.TARGETING_FILTERS).json()["id"]
+ assert Survey.objects.get(pk=survey_id).targeting_flag_id is not None
+ self.key.scopes = ["survey:write"]
+ self.key.save()
+ return survey_id
+
+ @parameterized.expand(
+ [
+ ("survey_write_only", ["survey:write"], status.HTTP_403_FORBIDDEN),
+ ("with_feature_flag_write", ["survey:write", "feature_flag:write"], status.HTTP_201_CREATED),
+ ("wildcard", ["*"], status.HTTP_201_CREATED),
+ ]
+ )
+ def test_create_with_targeting_flag_filters_scope_matrix(self, _name, scopes, expected_status):
+ self.key.scopes = scopes
+ self.key.save()
+ response = self._create_survey(targeting_flag_filters=self.TARGETING_FILTERS)
+ assert response.status_code == expected_status, response.json()
+ if expected_status == status.HTTP_403_FORBIDDEN:
+ assert "feature_flag:write" in response.json()["detail"]
+ assert Survey.objects.filter(name=self.SURVEY_PAYLOAD["name"]).count() == 0
+
+ def test_create_without_targeting_flag_filters_is_allowed(self):
+ # Regression guard: plain survey create only touches the internal flag, which stays ungated.
+ response = self._create_survey()
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ def test_create_attaching_existing_targeting_flag_is_denied(self):
+ # Pointing a survey at an arbitrary existing flag (which the lifecycle sync can toggle)
+ # must require feature_flag:write.
+ flag = FeatureFlag.objects.create(team=self.team, key="survey-attach-existing", created_by=self.user)
+ response = self._create_survey(targeting_flag_id=flag.id)
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert "feature_flag:write" in response.json()["detail"]
+
+ def test_update_attaching_existing_targeting_flag_is_denied(self):
+ flag = FeatureFlag.objects.create(team=self.team, key="survey-attach-existing-2", created_by=self.user)
+ survey_id = self._create_survey().json()["id"]
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ data={"targeting_flag_id": flag.id},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_update_targeting_flag_filters_is_denied(self):
+ survey_id = self._create_survey_with_targeting_flag_as_admin()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ data={"targeting_flag_filters": {"groups": [{"properties": [], "rollout_percentage": 75}]}},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_update_remove_targeting_flag_is_denied(self):
+ survey_id = self._create_survey_with_targeting_flag_as_admin()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ data={"remove_targeting_flag": True},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert Survey.objects.get(pk=survey_id).targeting_flag_id is not None
+
+ def test_update_payload_only_is_allowed(self):
+ survey_id = self._create_survey_with_targeting_flag_as_admin()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ data={"name": "renamed"},
+ format="json",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_destroy_with_targeting_flag_is_denied(self):
+ survey_id = self._create_survey_with_targeting_flag_as_admin()
+ response = self.client.delete(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert Survey.objects.filter(pk=survey_id).exists()
+
+ def test_destroy_with_only_internal_targeting_flag_is_allowed(self):
+ survey_id = self._create_survey().json()["id"]
+ survey = Survey.objects.get(pk=survey_id)
+ assert survey.targeting_flag_id is None
+ assert survey.internal_targeting_flag_id is not None
+ response = self.client.delete(
+ f"/api/projects/{self.team.id}/surveys/{survey_id}/",
+ headers=self.auth_headers,
+ )
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+
+ def test_session_auth_is_allowed(self):
+ self.client.force_login(self.user)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={**self.SURVEY_PAYLOAD, "targeting_flag_filters": self.TARGETING_FILTERS},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()