: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(api): require query access for live event tokens (#108166)
Paul D'Ambra5d978ddb6c97
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex f1e49803a9e2..3effeb85dcf2 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -241,6 +241,8 @@ See [Client Types](#client-types) section for detailed explanation.OAuth supports all the same scopes as Personal API Keys. Each scope has a `read` and/or `write` action (e.g., `experiment:read`, `experiment:write`).+Project and environment detail responses return `live_events_token` only when the authenticated caller can read queries. For scoped credentials, this requires `query:read`, `query:write`, or `*`. A key with only `project:read` receives `null` for this field. List responses do not include `live_events_token`.+For a complete list of available scopes, see [frontend/src/lib/scopes.tsx](https://github.com/PostHog/posthog/blob/master/frontend/src/lib/scopes.tsx#L15).### OpenID Connect Scopesdiff --git a/posthog/api/project.py b/posthog/api/project.pyindex ff621b522487..3e1b3783d63d 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -49,11 +49,11 @@ from posthog.api.team import (TeamWorkflowsConfigSerializer,_default_data_color_theme_id,_format_serializer_errors,- get_or_mint_live_events_token,handle_experiments_config,handle_logs_config,handle_tracing_config,heatmaps_screenshot_secret_for_reader,+ live_events_token_for_request,merge_conversations_settings_locked,report_conversations_settings_changes,strip_managed_conversations_settings,@@ -1038,10 +1038,7 @@ class ProjectBackwardCompatSerializer(return cached_group_types_for_project(project)def get_live_events_token(self, project: Project) -> Optional[str]:- team = project.passthrough_team- request = self.context.get("request")- user_id = request.user.id if request and hasattr(request, "user") and request.user.is_authenticated else None- return get_or_mint_live_events_token(team, user_id)+ return live_events_token_for_request(project.passthrough_team, self.context.get("request"))@extend_schema_field(serializers.CharField(allow_null=True))def get_heatmaps_screenshot_secret(self, project: Project) -> Optional[str]:diff --git a/posthog/api/team.py b/posthog/api/team.pyindex bce0bedc06ac..08c088779959 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -101,9 +101,10 @@ from posthog.permissions import (UserCanCreateProjectPermission,get_authenticator_scoped_organization_ids,get_authenticator_scoped_team_ids,+ get_authenticator_scopes,posthog_feature_flag_enabled,)-from posthog.scopes import APIScopeObjectOrNotSupported+from posthog.scopes import APIScopeObjectOrNotSupported, scopes_not_coveredfrom posthog.session_recordings.data_retention import (VALID_RETENTION_PERIODS,parse_feature_to_entitlement,@@ -1443,6 +1444,15 @@ class ConversationsSettingsField(serializers.JSONField):pass+def live_events_token_for_request(team: Team, request: request.Request | None) -> str | None:+ if request is None or not request.user.is_authenticated:+ return None+ scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))+ if scopes is not None and "*" not in scopes and scopes_not_covered(scopes, ["query:read"]):+ return None+ return get_or_mint_live_events_token(team, request.user.id)++class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):instance: Team | None_group_types_cache: list[dict[str, Any]] | None = None@@ -1582,9 +1592,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin@tracer.start_as_current_span("team_serializer.live_events_token")def get_live_events_token(self, team: Team) -> str | None:- request = self.context.get("request")- user_id = request.user.id if request and hasattr(request, "user") and request.user.is_authenticated else None- return get_or_mint_live_events_token(team, user_id)+ return live_events_token_for_request(team, self.context.get("request"))@extend_schema_field(serializers.CharField(allow_null=True))def get_heatmaps_screenshot_secret(self, team: Team) -> str | None:diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 67b934e9cb18..81e09a6b1b56 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -28,6 +28,7 @@ from posthog.api.team import (handle_conversations_token_on_update,merge_conversations_settings,)+from posthog.auth import PersonalAPIKeyAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig, RestrictionType@@ -4260,6 +4261,41 @@ class TestTeamSerializerValidationNoDB(SimpleTestCase):expected["widget_public_token"] = "test-generated-token" if enabling else Noneself.assertEqual(result["conversations_settings"], expected)+ @parameterized.expand(+ [+ (serializer, scopes, allowed)+ for serializer in (TeamSerializer, ProjectBackwardCompatSerializer)+ for scopes, allowed in (+ (None, True),+ (["project:read"], False),+ (["query:read"], True),+ (["query:write"], True),+ (["*"], True),+ )+ ]+ )+ def test_live_events_token_requires_query_access(+ self,+ serializer_class: type[TeamSerializer] | type[ProjectBackwardCompatSerializer],+ scopes: list[str] | None,+ allowed: bool,+ ) -> None:+ authenticator = None+ if scopes is not None:+ authenticator = PersonalAPIKeyAuthentication()+ authenticator.personal_api_key = PersonalAPIKey(scopes=scopes)+ request = MagicMock(user=MagicMock(id=1, is_authenticated=True))+ request.successful_authenticator = authenticator+ team = Team(id=1)+ serializer = serializer_class(context={"request": request})++ with patch("posthog.api.team.get_or_mint_live_events_token", return_value="test-live-token"):+ if isinstance(serializer, TeamSerializer):+ token = serializer.get_live_events_token(team)+ else:+ token = serializer.get_live_events_token(MagicMock(passthrough_team=team))+ self.assertEqual(token, "test-live-token" if allowed else None)+@parameterized.expand([(serializer, value)