: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
fix(flags): accept psak on remote_config endpoint (#66557)
Lucky negi0aeb22135e4f
diff --git a/products/endpoints/backend/tests/test_endpoint_psak_auth.py b/products/endpoints/backend/tests/test_endpoint_psak_auth.pyindex f6f862d29442..7d7d27810059 100644--- a/products/endpoints/backend/tests/test_endpoint_psak_auth.py+++ b/products/endpoints/backend/tests/test_endpoint_psak_auth.py@@ -289,10 +289,8 @@ class TestEndpointViewSetPSAKAuth(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)self.assertIn("does not have access to the requested project", response.json().get("detail", ""))- def test_psak_does_not_authenticate_legacy_team_token_surfaces(self):- # remote_config is the remaining Django surface for the legacy per-team- # Team.secret_api_token (local_evaluation now lives in the Rust flags service).- # A PSAK is also phs_-prefixed but must not be accepted there.+ def test_psak_without_feature_flag_read_scope_returns_403_on_remote_config(self):+ # remote_config accepts PSAK but requires feature_flag:read — endpoint-scoped keys must not pass.token, _ = _make_psak(self.team, label="remote-config-key")response = self.client.get(@@ -300,7 +298,8 @@ class TestEndpointViewSetPSAKAuth(ClickhouseTestMixin, APIBaseTest):**self._auth_headers(token),)- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)+ self.assertIn("feature_flag:read", response.json().get("detail", ""))def test_session_auth_still_works_on_endpoint_viewset(self):# Regression: wiring PSAK into authentication_classes must not break session auth.diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex bcda4f492a7a..9bbacd5c5f2d 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -40,6 +40,7 @@ from posthog.auth import (IDJagAccessTokenAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,TeamSecretTokenAuthentication,)from posthog.clickhouse.query_tagging import Feature, Product, tag_queries@@ -58,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, get_authenticator_scopes+from posthog.permissions import TeamSecretTokenPermission, get_authenticator_scopes, is_service_authfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.queries.base import determine_parsed_date_for_property_matchingfrom posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle@@ -2659,6 +2660,7 @@ class FeatureFlagViewSet("""scope_object = "feature_flag"+ psak_allowed_actions = ["remote_config"]# Opt the shared TaggedItemViewSetMixin action into feature_flag:write.# Other inheritors of the mixin don't extend write actions and so still# reject PAT calls — keeps the scope local to this viewset.@@ -4050,6 +4052,7 @@ class FeatureFlagViewSet(required_scopes=["feature_flag:read"],authentication_classes=[TeamSecretTokenAuthentication,+ ProjectSecretAPIKeyAuthentication,],permission_classes=[TeamSecretTokenPermission],throttle_classes=[RemoteConfigThrottle],@@ -4080,10 +4083,11 @@ class FeatureFlagViewSet(return Response(status=status.HTTP_404_NOT_FOUND)# Remote config usage is tracked for telemetry only (never billed), and only genuine SDK- # fetches (team secret token, phs_…) count. Session and personal-key requests are the app's- # own preview/decrypt feature, not customer usage, and a session-authenticated GET would- # otherwise let a cross-site request inflate the team's usage numbers.- should_count = isinstance(request.successful_authenticator, TeamSecretTokenAuthentication)+ # fetches (legacy team secret token or feature-flag-scoped PSAK, both phs_…) count. Session+ # and personal-key requests are the app's own preview/decrypt feature, not customer usage,+ # and a session-authenticated GET would otherwise let a cross-site request inflate the team's+ # usage numbers.+ should_count = is_service_auth(request)if not feature_flag.has_encrypted_payloads:payloads = feature_flag.filters.get("payloads", {})diff --git a/products/feature_flags/backend/api/remote_config_shadow.py b/products/feature_flags/backend/api/remote_config_shadow.pyindex 0b645c2cc179..7f27b9890481 100644--- a/products/feature_flags/backend/api/remote_config_shadow.py+++ b/products/feature_flags/backend/api/remote_config_shadow.py@@ -17,7 +17,7 @@ from requests.adapters import HTTPAdapterfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.auth import PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthenticationfrom posthog.security.outbound_proxy import internal_requests_sessionlogger = structlog.get_logger(__name__)@@ -39,9 +39,13 @@ REMOTE_CONFIG_SHADOW_COMPARISONS = Counter(["result"], # match | mismatch | error | skipped)-# Rust only implements these two SDK credential types. Session-cookie and OAuth requests (Django's+# Rust implements these SDK credential types. Session-cookie and OAuth requests (Django's# own preview/decrypt UI) 401 on Rust by design, so shadowing them would log false mismatches.-_RUST_SUPPORTED_AUTH = (TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication)+_RUST_SUPPORTED_AUTH = (+ TeamSecretTokenAuthentication,+ PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,+)def shadow_compare_remote_config(request: Request, django_response: Response, *, project_id: int, key: str) -> None:diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 0e0d8f226f89..6ad26ffc2d4c 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -33,6 +33,7 @@ from posthog.models import TaggedItem, Userfrom posthog.models.group.util import create_groupfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.db_context_capturing import capture_db_queries@@ -69,6 +70,22 @@ from products.surveys.backend.models import Surveyfrom ee.models.rbac.access_control import AccessControl+def _make_feature_flag_psak(+ team: Team, label: str = "psak", scopes: list[str] | None = None+) -> tuple[str, ProjectSecretAPIKey]:+ # Token must match _SECRET_API_KEY_RE = r"^phs_[a-zA-Z0-9]+$", so only alphanumerics after phs_.+ suffix = "".join(c for c in label if c.isalnum())+ token = "phs_" + ("b" * 35) + suffix+ psak = ProjectSecretAPIKey.objects.create(+ team=team,+ label=label,+ mask_value=f"phs_...{suffix[:4]}",+ secure_value=hash_key_value(token),+ scopes=["feature_flag:read"] if scopes is None else scopes,+ )+ return token, psak++class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):feature_flag: FeatureFlag = None # type: ignore@@ -2112,6 +2129,67 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json(), '{"test": true}')+ def _create_remote_config_flag(self, key: str = "my-remote-config-flag") -> None:+ FeatureFlag.objects.create(+ team=self.team,+ key=key,+ name="Remote Config Flag",+ active=True,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "payloads": {"true": '{"test": true}'},+ },+ is_remote_configuration=True,+ )++ def test_remote_config_with_psak(self):+ self._create_remote_config_flag()+ token, _ = _make_feature_flag_psak(self.team, label="remote-config")+ self.client.logout()+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), '{"test": true}')++ def test_remote_config_psak_wrong_scope_returns_403(self):+ self._create_remote_config_flag()+ token, _ = _make_feature_flag_psak(self.team, label="wrong-scope", scopes=["endpoint:read"])+ self.client.logout()+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_remote_config_psak_cross_team_returns_403(self):+ self._create_remote_config_flag()+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ token, _ = _make_feature_flag_psak(other_team, label="other-team")+ self.client.logout()+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_remote_config_psak_increments_remote_config_bucket(self):+ self._create_remote_config_flag()+ token, _ = _make_feature_flag_psak(self.team, label="telemetry")+ self.client.logout()++ client = redis.get_client()+ client.delete(f"posthog:remote_config_requests:{self.team.pk}")++ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ buckets = client.hgetall(f"posthog:remote_config_requests:{self.team.pk}")+ self.assertEqual(sum(int(count) for count in buckets.values()), 1)+def test_remote_config_returns_response_even_if_shadow_raises(self):# The throwaway Rust shadow (phase 2) must never break the live endpoint, even if it raises.self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)@@ -2148,6 +2226,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):[("project_secret_key", False),("personal_api_key", True),+ ("psak", False),])def test_remote_config_encrypted_payload_auth_dependent(self, _name: str, should_decrypt: bool):@@ -2160,6 +2239,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):PersonalAPIKey.objects.create(label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(auth_token))+ elif _name == "psak":+ auth_token, _ = _make_feature_flag_psak(self.team, label="encrypted")else:self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)secret_token = self.team.secret_api_tokendiff --git a/products/feature_flags/backend/api/test/test_remote_config_shadow.py b/products/feature_flags/backend/api/test/test_remote_config_shadow.pyindex ed55e2089463..df10e60bfe91 100644--- a/products/feature_flags/backend/api/test/test_remote_config_shadow.py+++ b/products/feature_flags/backend/api/test/test_remote_config_shadow.py@@ -6,7 +6,12 @@ from django.test import override_settingsfrom rest_framework.response import Response-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication+from posthog.auth import (+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,+ TeamSecretTokenAuthentication,+)from products.feature_flags.backend.api import remote_config_shadow as shadow@@ -59,7 +64,10 @@ def test_unsupported_auth_is_skipped(authenticator):counter.labels.assert_called_once_with(result="skipped")[email protected]("authenticator", [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication])+ "authenticator",+ [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication],+)def test_supported_auth_is_compared(authenticator):with (patch.object(shadow, "_SHADOW_SESSION") as session,@@ -71,7 +79,10 @@ def test_supported_auth_is_compared(authenticator):counter.labels.assert_called_once_with(result="match")[email protected]("authenticator", [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication])+ "authenticator",+ [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication],+)def test_non_header_credential_is_skipped(authenticator):# Django also authenticates via ?personal_api_key= / request body, but Rust reads only the# Authorization header — so a non-header credential 401s on Rust. Skip rather than log a false mismatch.