: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(experiments): allow experiment:read on project secret API keys (#94006)
Juraj Majerik4a2814f7c606
diff --git a/posthog/api/routing.py b/posthog/api/routing.pyindex c9f5d4283e2b..b63efbd2af30 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -39,6 +39,7 @@ from posthog.permissions import (SharingTokenPermission,TeamMemberAccessPermission,VerifiedDomainEnforcementPermission,+ is_service_auth,)from posthog.products import is_product_modulefrom posthog.scopes import APIScopeObjectOrNotSupported@@ -368,6 +369,13 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):# The reason being, that if we filter out here already, we can't load the object which is required for checking access controls for itreturn queryset+ # Service credentials (TST, PSAK) authenticate as synthetic users UserAccessControl+ # can't evaluate (a `created_by=<synthetic user>` filter would raise). They're gated+ # by API scope + project membership, and their scopes grant project-wide access —+ # mirroring the service-auth short-circuit in AccessControlPermission.+ if is_service_auth(self.request):+ return queryset+# NOTE: Half implemented - for admins, they may want to include listing of results that are not accessible (like private resources)include_all_if_admin = self.request.GET.get("admin_include_all") == "true"diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 004a3b0f3a53..8ff9ed191a28 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -221,6 +221,9 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS# `loops/:id/trigger/`. PSAKs are project-wide, so a leaked key can fire any loop# in the project (accepted and documented in products/tasks/docs/LOOPS.md).("loop", "write"),+ # Read-only export of experiment definitions (list/retrieve), so services syncing+ # experiments into a warehouse don't need a credential tied to one person's account.+ ("experiment", "read"),]# Server-side scope assignment string-set constants (see RFC: server-side scopediff --git a/products/access_control/backend/presentation/access_control.py b/products/access_control/backend/presentation/access_control.pyindex a44c075a91cf..a4b5d5da6ba4 100644--- a/products/access_control/backend/presentation/access_control.py+++ b/products/access_control/backend/presentation/access_control.py@@ -16,6 +16,7 @@ from posthog.models import Userfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObjectOrNotSupported+from posthog.synthetic_user import SyntheticUserfrom products.access_control.backend.facade.object_names import display_modelfrom products.access_control.backend.facade.subject_access_control import SubjectAccessControl@@ -579,6 +580,11 @@ class UserAccessControlSerializerMixin(serializers.Serializer):if request and request.user.is_anonymous:return None+ # Service credentials (TST, PSAK) authenticate as synthetic users UserAccessControl+ # can't evaluate — per-user access levels are meaningless for them, so report none.+ if request and isinstance(request.user, SyntheticUser):+ return None+# NOTE: The user_access_control is typically on the view but in specific cases,# such as rendering HTML (`render_template()`), it is set at the context levelif "user_access_control" in self.context:diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 4ce942b95ed2..9dddb1106349 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -29,7 +29,12 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.auth import (+ IDJagAccessTokenAuthentication,+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,+)from posthog.models.activity_logging.activity_log import ActivityLog, get_activity_pagefrom posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.organization import OrganizationMembership@@ -39,6 +44,8 @@ from posthog.permissions import is_service_auth, posthog_feature_flag_enabledfrom posthog.rate_limit import (ClickHouseBurstRateThrottle,ClickHouseSustainedRateThrottle,+ PersonalOrProjectSecretApiKeyRateThrottle,+ ProjectSecretApiKeyTeamRateThrottle,SessionBucketsBurstRateThrottle,SessionBucketsSustainedRateThrottle,SessionContextsBurstRateThrottle,@@ -250,6 +257,34 @@ def _accessible_session_ids(return [session_id for session_id in session_ids if session_id not in denied_ids]+class ExperimentBurstRateThrottle(PersonalOrProjectSecretApiKeyRateThrottle):+ # Same scope and rate as the default BurstRateThrottle so personal-key and session+ # behavior is unchanged; the subclass only adds per-key throttling for PSAK requests,+ # which the default throttles silently bypass (no personal key, no throttling).+ scope = "burst"+ rate = "480/minute"+++class ExperimentSustainedRateThrottle(PersonalOrProjectSecretApiKeyRateThrottle):+ scope = "sustained"+ rate = "4800/hour"+++class ExperimentProjectSecretApiKeyTeamBurstThrottle(ProjectSecretApiKeyTeamRateThrottle):+ """Per-team aggregate burst budget across all of a project's PSAKs — same size as the+ per-key budget, so minting extra keys never multiplies a project's total burst capacity."""++ scope = "experiment_psak_team_burst"+ rate = "480/minute"+++class ExperimentProjectSecretApiKeyTeamSustainedThrottle(ProjectSecretApiKeyTeamRateThrottle):+ """Per-team aggregate sustained budget across all of a project's PSAKs."""++ scope = "experiment_psak_team_sustained"+ rate = "4800/hour"++@extend_schema_view(# PATCH /experiments/{id}/# DRF mixin calls implementation at ExperimentSerializer.update@@ -366,6 +401,18 @@ class EnterpriseExperimentsViewSet(viewsets.ModelViewSet,):scope_object: Literal["experiment"] = "experiment"+ # Extends the default authenticators (TeamAndOrgViewSetMixin appends session/PAT/OAuth).+ authentication_classes = [ProjectSecretAPIKeyAuthentication]+ # A project secret API key with experiment:read can export experiment definitions+ # (list/retrieve) — a service credential not tied to one person's account. Everything+ # else (writes, lifecycle actions, results) stays session/PAT/OAuth-only.+ psak_allowed_actions = ["list", "retrieve"]+ throttle_classes = [+ ExperimentBurstRateThrottle,+ ExperimentSustainedRateThrottle,+ ExperimentProjectSecretApiKeyTeamBurstThrottle,+ ExperimentProjectSecretApiKeyTeamSustainedThrottle,+ ]serializer_class = ExperimentSerializerqueryset = (Experiment.objects.select_related(diff --git a/products/experiments/backend/test/test_experiment_psak_auth.py b/products/experiments/backend/test/test_experiment_psak_auth.pynew file mode 100644index 000000000000..a0346c6c82ca--- /dev/null+++ b/products/experiments/backend/test/test_experiment_psak_auth.py@@ -0,0 +1,136 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized+from rest_framework import status++from posthog.models.organization import OrganizationMembership+from posthog.models.team import Team+from posthog.test.api_keys import create_project_secret_api_key++from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _create_experiment(team: Team, name: str, flag_key: str) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=team,+ key=flag_key,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )+ return Experiment.objects.create(team=team, name=name, feature_flag=flag)+++class TestExperimentPSAKAuth(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.experiment = _create_experiment(self.team, "First experiment", "psak-flag-1")+ self.other_experiment = _create_experiment(self.team, "Second experiment", "psak-flag-2")+ _, self.token = create_project_secret_api_key(self.team, scopes=["experiment:read"])+ # Log out the test client so only the PSAK header authenticates requests+ self.client.logout()++ def _auth_headers(self, token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}++ def test_psak_can_list_experiments(self) -> None:+ response = self.client.get(+ f"/api/projects/{self.team.id}/experiments/",+ headers=self._auth_headers(self.token),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ data = response.json()+ self.assertEqual(data["count"], 2)+ self.assertEqual(+ {result["name"] for result in data["results"]},+ {"First experiment", "Second experiment"},+ )+ # Per-user access levels are meaningless for a service credential+ self.assertIsNone(data["results"][0]["user_access_level"])++ def test_psak_can_retrieve_experiment(self) -> None:+ response = self.client.get(+ f"/api/projects/{self.team.id}/experiments/{self.experiment.id}/",+ headers=self._auth_headers(self.token),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ data = response.json()+ self.assertEqual(data["id"], self.experiment.id)+ self.assertEqual(data["feature_flag_key"], "psak-flag-1")+ self.assertIsNone(data["user_access_level"])++ @parameterized.expand(+ [+ # PSAK must only authorize list/retrieve — writes, lifecycle actions, and+ # non-allowlisted reads all return 403, whatever scopes the key carries.+ ("create", "post", "", {"name": "New experiment", "feature_flag_key": "psak-new-flag"}),+ ("partial_update", "patch", "{id}/", {"name": "Renamed"}),+ ("launch", "post", "{id}/launch/", None),+ ("flag_cleanup_task", "get", "{id}/flag_cleanup_task/", None),+ ("stats", "get", "stats/", None),+ ]+ )+ def test_psak_blocked_on_non_allowlisted_actions(+ self, _name: str, method: str, path_suffix: str, body: dict | None+ ) -> None:+ _, wide_token = create_project_secret_api_key(+ self.team, label="wide", scopes=["experiment:read", "experiment:write", "activity_log:read"]+ )+ path_suffix = path_suffix.format(id=self.experiment.id)++ response = getattr(self.client, method)(+ f"/api/projects/{self.team.id}/experiments/{path_suffix}",+ data=body,+ content_type="application/json",+ headers=self._auth_headers(wide_token),+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)++ def test_psak_without_experiment_scope_forbidden(self) -> None:+ _, token = create_project_secret_api_key(self.team, label="wrong-scope", scopes=["feature_flag:read"])++ response = self.client.get(+ f"/api/projects/{self.team.id}/experiments/",+ headers=self._auth_headers(token),+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)++ def test_psak_from_another_team_forbidden(self) -> None:+ other_team = self.create_team_with_organization(organization=self.organization)+ _, other_token = create_project_secret_api_key(other_team, label="other-team", scopes=["experiment:read"])++ response = self.client.get(+ f"/api/projects/{self.team.id}/experiments/",+ headers=self._auth_headers(other_token),+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)++ @parameterized.expand(+ [+ ("read_allowed", ["experiment:read"], status.HTTP_201_CREATED),+ ("write_rejected", ["experiment:write"], status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_key_creation_allowlist(self, _name: str, scopes: list[str], expected_status: int) -> None:+ self.client.force_login(self.user)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/project_secret_api_keys",+ {"label": "sync key", "scopes": scopes},+ )++ self.assertEqual(response.status_code, expected_status, response.content)