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.

feat(flags): auto-select feature_flag:write for survey/EAF key scopes (#67468)

Lucas Fariaadcc233b8d01
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index dcdd96605bc7..2fe1b70260dd 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -15,6 +15,16 @@ export type APIScope = {
warnings?: Partial<Record<'read' | 'write', string | JSX.Element>>
}
+// Scopes whose write action also writes a feature flag as a side effect (survey targeting flag,
+// early access feature linked flag), so they imply `feature_flag:write`. Single source of truth for
+// both the picker warning (attached below) and the auto-select in personalAPIKeysLogic, so the rule
+// and the copy can't drift. `ScopeAccessRow` renders warnings as plain text — no markdown formatting.
+export const SCOPES_IMPLYING_FEATURE_FLAG_WRITE: Partial<Record<APIScopeObject, string>> = {
+ survey: 'Surveys with targeting also manage a feature flag, so this key needs feature_flag:write too.',
+ early_access_feature:
+ 'Early access features manage a linked feature flag, so this key needs feature_flag:write too.',
+}
+
export const API_SCOPES: APIScope[] = [
{ key: 'action', objectName: 'Action', objectPlural: 'actions' },
{ key: 'access_control', objectName: 'Access control', objectPlural: 'access controls' },
@@ -47,7 +57,14 @@ export const API_SCOPES: APIScope[] = [
{ key: 'dashboard', objectName: 'Dashboard', objectPlural: 'dashboards' },
{ key: 'dashboard_template', objectName: 'Dashboard template', objectPlural: 'dashboard templates' },
{ key: 'dataset', objectName: 'Dataset', objectPlural: 'datasets' },
- { key: 'early_access_feature', objectName: 'Early access feature', objectPlural: 'early access features' },
+ {
+ key: 'early_access_feature',
+ objectName: 'Early access feature',
+ objectPlural: 'early access features',
+ warnings: {
+ write: SCOPES_IMPLYING_FEATURE_FLAG_WRITE.early_access_feature,
+ },
+ },
{ key: 'element', objectName: 'Element', objectPlural: 'elements' },
{ key: 'endpoint', objectName: 'Endpoint', objectPlural: 'endpoints' },
{ key: 'engineering_analytics', objectName: 'Engineering analytics', objectPlural: 'engineering analytics' },
@@ -144,7 +161,14 @@ export const API_SCOPES: APIScope[] = [
},
{ key: 'sharing_configuration', objectName: 'Sharing configuration', objectPlural: 'sharing configurations' },
{ key: 'subscription', objectName: 'Subscription', objectPlural: 'subscriptions' },
- { key: 'survey', objectName: 'Survey', objectPlural: 'surveys' },
+ {
+ key: 'survey',
+ objectName: 'Survey',
+ objectPlural: 'surveys',
+ warnings: {
+ write: SCOPES_IMPLYING_FEATURE_FLAG_WRITE.survey,
+ },
+ },
{ key: 'tagger', objectName: 'Tagger', objectPlural: 'taggers' },
{ key: 'ticket', objectName: 'Ticket', objectPlural: 'tickets' },
{ key: 'tracing', objectName: 'Tracing', objectPlural: 'tracing' },
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
index ff97d7a9fad3..9b46781897b8 100644
--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
@@ -109,4 +109,28 @@ describe('personalAPIKeysLogic', () => {
expect(capturedCreatePayload).not.toBeNull()
expect(capturedCreatePayload.scopes).toEqual(['*'])
})
+
+ it.each(['survey', 'early_access_feature'])(
+ 'auto-selects feature_flag:write when %s write is granted',
+ async (scope) => {
+ logic.actions.setEditingKeyId('new')
+ logic.actions.setScopeRadioValue(scope, 'write')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.editingKey.scopes).toContain(`${scope}:write`)
+ expect(logic.values.editingKey.scopes).toContain('feature_flag:write')
+ }
+ )
+
+ it('leaves the auto-selected feature_flag:write removable', async () => {
+ logic.actions.setEditingKeyId('new')
+ logic.actions.setScopeRadioValue('survey', 'write')
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setScopeRadioValue('feature_flag', 'none')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.editingKey.scopes).toContain('survey:write')
+ expect(logic.values.editingKey.scopes).not.toContain('feature_flag:write')
+ })
})
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
index 1f869abf53a7..e5711cd3602b 100644
--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
@@ -10,7 +10,13 @@ import { CodeSnippet } from 'lib/components/CodeSnippet'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { APIScope, API_SCOPES, scopesArrayToObject, scopesObjectToArray } from 'lib/scopes'
+import {
+ APIScope,
+ API_SCOPES,
+ SCOPES_IMPLYING_FEATURE_FLAG_WRITE,
+ scopesArrayToObject,
+ scopesObjectToArray,
+} from 'lib/scopes'
import { hasMembershipLevelOrHigher, organizationAllowsPersonalApiKeysForMembers } from 'lib/utils/permissioning'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -468,6 +474,18 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
scopesObject[key] = action
}
+ // Survey and early access feature writes also write a feature flag (targeting / linked flag),
+ // so they imply feature_flag:write (see SCOPES_IMPLYING_FEATURE_FLAG_WRITE). Auto-select it so
+ // the key works out of the box. Scoped to this toggle action only — not every scopes change —
+ // so it stays visible and removable if the key only manages plain surveys.
+ if (
+ action === 'write' &&
+ key in SCOPES_IMPLYING_FEATURE_FLAG_WRITE &&
+ scopesObject['feature_flag'] !== 'write'
+ ) {
+ scopesObject['feature_flag'] = 'write'
+ }
+
// Convert back to array format
const newScopes = scopesObjectToArray(scopesObject)
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 64f08aedf8ac..39acae232153 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -259,10 +259,19 @@ def assert_feature_flag_write_scope(
)
if _is_enforce_feature_flag_write_scope_enabled(request, team_id=team_id):
+ # Tailor the remediation to the token type — only personal API keys are edited on the
+ # user-api-keys settings page; OAuth / ID-JAG / project-secret keys are managed elsewhere.
+ if auth_kind == "personal_api_key":
+ key_guidance = (
+ f"Add `feature_flag:write` to your personal API key at "
+ f"{settings.SITE_URL}/settings/user-api-keys (editing its scopes keeps the same key value), "
+ f"or use a key with the `*` scope."
+ )
+ else:
+ key_guidance = "Add `feature_flag:write` to the key you're using, or use a key with the `*` scope."
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."
+ f"in addition to `{resource_scope}`. {key_guidance}"
)
diff --git a/products/feature_flags/backend/api/test/test_scope_enforcement.py b/products/feature_flags/backend/api/test/test_scope_enforcement.py
index a7128719e474..9a72e08075fb 100644
--- a/products/feature_flags/backend/api/test/test_scope_enforcement.py
+++ b/products/feature_flags/backend/api/test/test_scope_enforcement.py
@@ -5,6 +5,7 @@ from unittest import TestCase
from unittest.mock import patch
from parameterized import parameterized
+from rest_framework.exceptions import PermissionDenied
from posthog.auth import (
IDJagAccessTokenAuthentication,
@@ -17,6 +18,7 @@ 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,
+ assert_feature_flag_write_scope,
)
@@ -74,6 +76,61 @@ class TestScopeAuditIdentity(TestCase):
assert _scope_audit_identity(None) is None
+class TestEnforcementMessageByTokenType(TestCase):
+ @parameterized.expand(
+ [
+ (
+ "personal_api_key",
+ _make(
+ PersonalAPIKeyAuthentication,
+ personal_api_key=SimpleNamespace(scopes=["survey:write"], id="pak_1", label="key"),
+ ),
+ True,
+ ),
+ (
+ "oauth_access_token",
+ _make(OAuthAccessTokenAuthentication, access_token=SimpleNamespace(scope="survey:write", id=7)),
+ False,
+ ),
+ (
+ "id_jag_access_token",
+ _make(IDJagAccessTokenAuthentication, scopes=["survey:write"]),
+ False,
+ ),
+ (
+ "project_secret_api_key",
+ _make(
+ ProjectSecretAPIKeyAuthentication,
+ project_secret_api_key=SimpleNamespace(scopes=["survey:write"], id=3),
+ ),
+ False,
+ ),
+ ]
+ )
+ def test_only_personal_api_keys_get_the_settings_page_guidance(self, _name, authenticator, expects_settings_link):
+ request = SimpleNamespace(successful_authenticator=authenticator, user=SimpleNamespace(id=1))
+ with patch(
+ "products.feature_flags.backend.api.feature_flag._is_enforce_feature_flag_write_scope_enabled",
+ return_value=True,
+ ):
+ with self.assertRaises(PermissionDenied) as caught:
+ assert_feature_flag_write_scope(
+ request,
+ action="survey.update.targeting_flag_filters",
+ resource_scope="survey:write",
+ team_id=1,
+ )
+
+ message = str(caught.exception.detail)
+ assert "`feature_flag:write`" in message
+ if expects_settings_link:
+ assert "/settings/user-api-keys" in message
+ assert "personal API key" in message
+ else:
+ assert "/settings/user-api-keys" not in message
+ assert "personal API key" not in message
+
+
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