: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(playground): add access control (#73946)
Reece Jones71b020715cc2
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex cd9ee11f8477..8829f5ecc34c 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -92,6 +92,7 @@ export const getStorybookAppContext = (): AppContext => ({activity_log: 'viewer',customer_analytics: 'manager',llm_analytics: 'manager',+ llm_playground: 'manager',mcp_analytics: 'manager',tagger: 'manager',llm_skill: 'manager',diff --git a/ee/migrations/0054_backfill_llm_playground_access_control.py b/ee/migrations/0054_backfill_llm_playground_access_control.pynew file mode 100644index 000000000000..e795b01f29f3--- /dev/null+++ b/ee/migrations/0054_backfill_llm_playground_access_control.py@@ -0,0 +1,39 @@+from django.db import migrations++CHUNK_SIZE = 200+++def backfill_llm_playground_access_control(apps, schema_editor):+ # The playground scene used to be gated on llm_analytics; now that it's an independent resource,+ # mirror every resource-wide llm_analytics grant onto a matching playground row so existing+ # permissions keep working instead of silently defaulting to editor. Rows with a resource_id are+ # per-object grants on other llm_analytics sub-resources (datasets, evaluations, ...) and aren't+ # playground-related, so they're excluded.+ # Reads the same resource-wide llm_analytics rows as ee/migrations/0053, so this is similarly near-instant.+ AccessControl = apps.get_model("ee", "AccessControl")++ for row in AccessControl.objects.filter(resource="llm_analytics", resource_id__isnull=True).iterator(+ chunk_size=CHUNK_SIZE+ ):+ AccessControl.objects.get_or_create(+ resource="llm_playground",+ resource_id=None,+ team_id=row.team_id,+ organization_member_id=row.organization_member_id,+ role_id=row.role_id,+ defaults={"access_level": row.access_level, "created_by_id": row.created_by_id},+ )+++def reverse_func(apps, schema_editor):+ pass+++class Migration(migrations.Migration):+ dependencies = [+ ("ee", "0053_backfill_tagger_access_control"),+ ]++ operations = [+ migrations.RunPython(backfill_llm_playground_access_control, reverse_func),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex 1f29fabf9f7c..b1b3900d4598 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0053_backfill_tagger_access_control+0054_backfill_llm_playground_access_controldiff --git a/ee/migrations/test/test_migration_0054.py b/ee/migrations/test/test_migration_0054.pynew file mode 100644index 000000000000..a9db854e1f9d--- /dev/null+++ b/ee/migrations/test/test_migration_0054.py@@ -0,0 +1,118 @@+import importlib++from posthog.test.base import BaseTest++from django.apps import apps++from parameterized import parameterized++from ee.models.rbac.access_control import AccessControl+from ee.models.rbac.role import Role++migration_module = importlib.import_module("ee.migrations.0054_backfill_llm_playground_access_control")+backfill_llm_playground_access_control = migration_module.backfill_llm_playground_access_control+++class TestBackfillLlmPlaygroundAccessControl(BaseTest):+ def _scope_kwargs(self, case):+ role = (+ Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None+ )+ return {+ "organization_member": self.organization_membership if case == "member_scoped" else None,+ "role": role,+ }++ @parameterized.expand(+ [+ ("member_scoped",),+ ("role_scoped",),+ ("org_default",),+ ]+ )+ def test_backfills_resource_wide_row(self, case):+ scope_kwargs = self._scope_kwargs(case)++ AccessControl.objects.create(+ team=self.team, resource="llm_analytics", resource_id=None, access_level="none", **scope_kwargs+ )++ backfill_llm_playground_access_control(apps, None)++ backfilled = AccessControl.objects.filter(resource="llm_playground", team=self.team, **scope_kwargs).first()+ assert backfilled is not None+ assert backfilled.access_level == "none"++ def test_does_not_touch_other_resources(self):+ AccessControl.objects.create(+ team=self.team,+ resource="dataset",+ resource_id=None,+ access_level="editor",+ organization_member=self.organization_membership,+ )++ backfill_llm_playground_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="llm_playground").exists()++ def test_ignores_object_scoped_llm_analytics_rows(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id="123",+ access_level="editor",+ organization_member=self.organization_membership,+ )++ backfill_llm_playground_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="llm_playground").exists()++ def test_does_not_overwrite_existing_row(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id=None,+ access_level="editor",+ organization_member=self.organization_membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="llm_playground",+ resource_id=None,+ access_level="none",+ organization_member=self.organization_membership,+ )++ backfill_llm_playground_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="llm_playground", organization_member=self.organization_membership)++ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.access_level == "none"++ @parameterized.expand(+ [+ ("member_scoped",),+ ("role_scoped",),+ ("org_default",),+ ]+ )+ def test_idempotent_on_repeat_run(self, case):+ # organization_member/role are nullable, and Postgres unique constraints treat NULLs as+ # distinct, so the org_default (both-None) case would silently duplicate on a second run+ # if the migration ever stopped looking up the existing row before creating one.+ scope_kwargs = self._scope_kwargs(case)++ AccessControl.objects.create(+ team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs+ )++ backfill_llm_playground_access_control(apps, None)+ backfill_llm_playground_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="llm_playground", team=self.team, **scope_kwargs)+ assert rows.count() == 1diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 87d65d150766..b1f6878b5629 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6927,9 +6927,9 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--light:hash: v1.k794b7964.b1ae6dbc8feb673159fcc13f4a8fd5ee856c63ad1204e839a1b55ef70d109c81.W5sqRIJDHcdkKlYg4ghfwpbKS2FmlQKF_N-1C83h9Mgscenes-app-settings-environment--settings-environment-access-control--dark:- hash: v1.k794b7964.ae02475ed52a08862e75f53a748ddb98d30a653ba6a7e6723235812b00c58c75.54z1HwOspW4NeLQfCtsLEFfg2YlLuNm6KIJBd7dhvWk+ hash: v1.k794b7964.075bc140216002510c61cf29ee2b3877ca4d08bc7b6acb32d52147f70eea693a.EVC7gN9RyGMHLjpClT3REA2tP0XU-NLdfWzWi66JFZEscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.8da8ddf2ff9ced44baca60ca5f4ff95395b27c0d62b5fe1fe545e38f03d3b604.51JVG37C9A9uqbeF1X_7LuAE3hUneHOglJz3wMt09PQ+ hash: v1.k794b7964.d1717f298b33232ac22ab6de839baaa27fdfeffcded5250a4280b503068303dc.k3zUNlOwV7u8xkEk6HChmLZWfj1Ld2med7VbiF5HZQgscenes-app-settings-environment--settings-environment-autocapture--dark:hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4scenes-app-settings-environment--settings-environment-autocapture--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsxindex b452d2d17fd9..8a7e3adf9a32 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx@@ -23,6 +23,7 @@ import {IconPeople,IconPieChart,IconPiggyBank,+ IconPlaylist,IconPulse,IconRewindPlay,IconRocket,@@ -77,6 +78,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconLlmAnalytics />case 'llm_skill':return <IconLlmPromptManagement />+ case 'llm_playground':+ return <IconPlaylist />case 'ai_observability_clusters':return <IconScatter />case 'live_debugger':diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.tsindex 9201e6958d8c..4ec99cd30b6c 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts@@ -362,6 +362,7 @@ export interface accessControlsLogicActions {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -499,6 +500,7 @@ export interface accessControlsLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -640,6 +642,7 @@ export interface accessControlsLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -754,6 +757,7 @@ export interface accessControlsLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.tsindex 19e5b5f9e6f0..93d41d69792b 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts@@ -83,6 +83,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -201,6 +202,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -311,6 +313,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -434,6 +437,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -557,6 +561,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -687,6 +692,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -797,6 +803,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -946,6 +953,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1058,6 +1066,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1169,6 +1178,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1280,6 +1290,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1392,6 +1403,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1503,6 +1515,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1625,6 +1638,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -1736,6 +1750,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 188dd5ebd568..9b8f18280509 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -358,6 +358,7 @@ export interface accessControlLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -571,6 +572,7 @@ export interface accessControlLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'@@ -682,6 +684,7 @@ export interface accessControlLogicMeta {| 'live_debugger'| 'llm_analytics'| 'llm_gateway'+ | 'llm_playground'| 'llm_prompt'| 'llm_provider_key'| 'llm_skill'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.tsindex 6a74bd4e8ca3..b336a87c6386 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts@@ -197,6 +197,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.Survey,AccessControlResourceType.WebAnalytics,AccessControlResourceType.Toolbar,+ AccessControlResourceType.LlmPlayground,AccessControlResourceType.Workflow,AccessControlResourceType.Tracing,]diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 575892edd9b3..14ae04cb1991 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -115,6 +115,7 @@ export const API_SCOPES: APIScope[] = [disabledActions: ['write'],unprivilegedExcluded: true,},+ { key: 'llm_playground', objectName: 'LLM playground', objectPlural: 'LLM playground' },{ key: 'llm_prompt', objectName: 'LLM prompt', objectPlural: 'LLM prompts' },{ key: 'llm_provider_key', objectName: 'LLM provider key', objectPlural: 'LLM provider keys' },{ key: 'llm_skill', objectName: 'LLM skill', objectPlural: 'LLM skills' },diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.tsindex 39e9c5de7e38..62da9872e299 100644--- a/frontend/src/lib/utils/accessControlUtils.ts+++ b/frontend/src/lib/utils/accessControlUtils.ts@@ -90,6 +90,8 @@ export const pluralizeResource = (resource: APIScopeObject): string => {return 'sharing'} else if (resource === AccessControlResourceType.Toolbar) {return 'toolbar'+ } else if (resource === AccessControlResourceType.LlmPlayground) {+ return 'LLM playground'} else if (resource === AccessControlResourceType.Workflow) {return 'workflows'} else if (resource === AccessControlResourceType.ReplayScanner) {@@ -131,6 +133,8 @@ export const resourceTypeToString = (resourceType: AccessControlResourceType): sreturn 'AI observability resource'} else if (resourceType === AccessControlResourceType.LlmSkill) {return 'skill'+ } else if (resourceType === AccessControlResourceType.LlmPlayground) {+ return 'LLM playground'} else if (resourceType === AccessControlResourceType.AiObservabilityClusters) {return 'AI trace clusters resource'} else if (resourceType === AccessControlResourceType.RevenueAnalytics) {diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex b805511d5dce..fdb44408fba9 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -423,7 +423,7 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.AIObservabilityDatasets]: AccessControlResourceType.LlmAnalytics,[Scene.AIObservabilityEvaluation]: AccessControlResourceType.LlmAnalytics,[Scene.AIObservabilityEvaluations]: AccessControlResourceType.LlmAnalytics,- [Scene.AIObservabilityPlayground]: AccessControlResourceType.LlmAnalytics,+ [Scene.AIObservabilityPlayground]: AccessControlResourceType.LlmPlayground,[Scene.AIObservabilityTag]: AccessControlResourceType.Tagger,[Scene.AIObservabilityTags]: AccessControlResourceType.Tagger,[Scene.AIObservabilityTrace]: AccessControlResourceType.LlmAnalytics,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 90c5740f363c..4bc7251fd46a 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -290,6 +290,7 @@ export enum AccessControlResourceType {LlmAnalytics = 'llm_analytics',Tagger = 'tagger',LlmSkill = 'llm_skill',+ LlmPlayground = 'llm_playground',AiObservabilityClusters = 'ai_observability_clusters',Notebook = 'notebook',SessionRecording = 'session_recording',@@ -5760,6 +5761,7 @@ export const API_SCOPE_OBJECTS = ['llm_analytics','ai_observability_clusters','llm_gateway',+ 'llm_playground','llm_prompt','llm_provider_key','llm_skill',diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex 62d6414cedad..d22d1fb3738f 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -90,6 +90,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("tracing","replay_scanner","toolbar",+ "llm_playground",)# Resource inheritance mapping - child resources inherit access from parent resources@@ -172,6 +173,9 @@ def resource_to_display_name(resource: APIScopeObject) -> str:if resource == "warehouse_objects":# Umbrella label for both warehouse tables and views (both children inherit from this)return "data warehouse tables & views"+ if resource == "llm_playground":+ # The playground is a single page, not a collection of objects+ return "LLM playground"# Default: replace underscores and add 's' for pluralreturn f"{resource.replace('_', ' ')}s"diff --git a/posthog/scopes.py b/posthog/scopes.pyindex be69e0be65a2..e5dad0dce3df 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -71,6 +71,7 @@ APIScopeObject = Literal["llm_analytics","ai_observability_clusters","llm_gateway",+ "llm_playground","llm_prompt","llm_provider_key","llm_skill",diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.pyindex 58eb545c4105..fa8474d8c14f 100644--- a/products/ai_observability/backend/api/proxy.py+++ b/products/ai_observability/backend/api/proxy.py@@ -19,7 +19,7 @@ from django.utils import timezoneimport structlogfrom rest_framework import serializers, viewsetsfrom rest_framework.decorators import action-from rest_framework.permissions import IsAuthenticated+from rest_framework.permissions import BasePermission, IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -35,6 +35,7 @@ from posthog.rate_limit import (LLMProxyDailyRateThrottle,LLMProxySustainedRateThrottle,)+from posthog.rbac.user_access_control import AccessControlLevel, UserAccessControlfrom posthog.renderers import SafeJSONRenderer, ServerSentEventRendererfrom posthog.settings import SERVER_GATEWAY_INTERFACE@@ -90,6 +91,46 @@ class LLMProxyCompletionSerializer(serializers.Serializer):provider_key_id = serializers.UUIDField(required=False, allow_null=True)+class PlaygroundAccessPermission(BasePermission):+ """Resource-level RBAC for the playground.++ The playground is stateless, so there is no model for `AccessControlViewSetMixin` to bind to and no+ object-level grants to consider. This viewset also sits on the root router without+ `TeamAndOrgViewSetMixin`, so it never picks up that mixin's `AccessControlPermission` — the check has+ to be wired up by hand. Deliberately no `scope_object` on the viewset: nothing in this permission+ chain reads it, and it would imply personal API key support that `SessionAuthentication` doesn't allow.+ """++ # Listing models is a read; running a completion spends money, so it's a write.+ ACTION_REQUIRED_LEVELS: dict[str, AccessControlLevel] = {"models": "viewer", "completion": "editor"}++ def has_permission(self, request: Request, view) -> bool:+ user = request.user+ if not user or not user.is_authenticated:+ return False++ # Fail closed so a new @action can't ship ungated+ required_level = self.ACTION_REQUIRED_LEVELS.get(view.action or "")+ if required_level is None:+ self.message = "This playground endpoint isn't available."+ return False++ team = getattr(user, "current_team", None)+ if team is None:+ self.message = "Open a project before using the playground."+ return False++ if UserAccessControl(user=user, team=team).check_access_level_for_resource("llm_playground", required_level):+ return True++ self.message = (+ "You need editor access to the playground to run prompts. Ask a project admin to update your access."+ if required_level == "editor"+ else "You don't have access to the playground. Ask a project admin to update your access."+ )+ return False++class LLMProxyViewSet(viewsets.ViewSet):"""ViewSet for AI observability proxy.@@ -97,7 +138,7 @@ class LLMProxyViewSet(viewsets.ViewSet):"""authentication_classes = [SessionAuthentication]- permission_classes = [IsAuthenticated]+ permission_classes = [IsAuthenticated, PlaygroundAccessPermission]renderer_classes = [SafeJSONRenderer, ServerSentEventRenderer]def get_throttles(self):diff --git a/products/ai_observability/backend/api/test/test_playground_access_control.py b/products/ai_observability/backend/api/test/test_playground_access_control.pynew file mode 100644index 000000000000..3cf08b71ae37--- /dev/null+++ b/products/ai_observability/backend/api/test/test_playground_access_control.py@@ -0,0 +1,101 @@+import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status+from rest_framework.response import Response++from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User++from products.ai_observability.backend.api.proxy import LLMProxyViewSet++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+++COMPLETION_PAYLOAD = {+ "system": "",+ "messages": [{"role": "user", "content": "hello"}],+ "model": "gpt-5-mini",+ "provider": "openai",+}+++class TestPlaygroundAccessControl(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="member",+ organization_member=None,+ role=None,+ )++ def _login_with_playground_level(self, access_level: str) -> User:+ user = User.objects.create_and_join(self.organization, f"{access_level}@posthog.com", "testtest")+ user.current_team = self.team+ user.save()+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="llm_playground",+ resource_id=None,+ access_level=access_level,+ organization_member=membership,+ )+ self.client.force_login(user)+ return user++ def _post_completion(self):+ # Patched so the assertion is about the gate, not the payment-method check or the provider call+ with patch.object(LLMProxyViewSet, "_handle_completion_request", return_value=Response(status=200)):+ return self.client.post("/api/llm_proxy/completion/", COMPLETION_PAYLOAD)++ @parameterized.expand(+ [+ ("none", status.HTTP_403_FORBIDDEN, status.HTTP_403_FORBIDDEN),+ ("viewer", status.HTTP_200_OK, status.HTTP_403_FORBIDDEN),+ ("editor", status.HTTP_200_OK, status.HTTP_200_OK),+ ]+ )+ def test_access_level_gates_each_action(self, access_level, models_status, completion_status):+ self._login_with_playground_level(access_level)++ assert self.client.get("/api/llm_proxy/models/").status_code == models_status+ assert self._post_completion().status_code == completion_status++ def test_denied_without_a_current_team(self):+ user = self._login_with_playground_level("editor")+ user.current_team = None+ user.save()++ assert self._post_completion().status_code == status.HTTP_403_FORBIDDEN++ def test_org_admin_bypasses_a_project_default_of_none(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_playground",+ resource_id=None,+ access_level="none",+ organization_member=None,+ role=None,+ )+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.client.force_login(self.user)++ assert self._post_completion().status_code == status.HTTP_200_OKdiff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsxindex b94f55ac4d6f..4fb793011104 100644--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx@@ -30,6 +30,7 @@ import {LemonDivider,} from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'@@ -43,6 +44,7 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { JSONEditor } from '../components/JSONEditor'import { MetadataHeader } from '../ConversationDisplay/MetadataHeader'@@ -163,23 +165,28 @@ function PlaygroundHeaderActions(): JSX.Element {>Add prompt</LemonButton>- <LemonButton- type={playgroundSubmitting ? 'secondary' : 'primary'}- size="small"- icon={playgroundSubmitting ? <Spinner textColored /> : <IconPlay />}- status={playgroundSubmitting ? 'danger' : undefined}- onClick={() => (playgroundSubmitting ? abortRun() : submitPrompt())}- disabledReason={- playgroundSubmitting- ? undefined- : !hasRunnablePrompts- ? 'Add messages to at least one prompt'- : undefined- }- data-attr="llma-playground-run-button"+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmPlayground}+ minAccessLevel={AccessControlLevel.Editor}>- {playgroundSubmitting ? 'Stop' : 'Run'}- </LemonButton>+ <LemonButton+ type={playgroundSubmitting ? 'secondary' : 'primary'}+ size="small"+ icon={playgroundSubmitting ? <Spinner textColored /> : <IconPlay />}+ status={playgroundSubmitting ? 'danger' : undefined}+ onClick={() => (playgroundSubmitting ? abortRun() : submitPrompt())}+ disabledReason={+ playgroundSubmitting+ ? undefined+ : !hasRunnablePrompts+ ? 'Add messages to at least one prompt'+ : undefined+ }+ data-attr="llma-playground-run-button"+ >+ {playgroundSubmitting ? 'Stop' : 'Run'}+ </LemonButton>+ </AccessControlAction></>)}diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.tsindex 9a1b52f9ea15..a52978bc3cb2 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts@@ -1,17 +1,29 @@import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { lemonToast } from '@posthog/lemon-ui'+import api, { ApiError } from 'lib/api'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'import { llmPlaygroundPromptsLogic } from './llmPlaygroundPromptsLogic'import { appendToolCallChunk, describeError, llmPlaygroundRunLogic, mergeUsage } from './llmPlaygroundRunLogic'+function setPlaygroundAccessLevel(level: AccessControlLevel): void {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: { llm_playground: level },+ } as typeof window.POSTHOG_APP_CONTEXT+}+describe('llmPlaygroundRunLogic', () => {beforeEach(() => {initKeaTests()+ // initKeaTests() leaves resource_access_control unset, which the playground gate reads as "no access"+ setPlaygroundAccessLevel(AccessControlLevel.Editor)useMocks({get: {'/api/llm_proxy/models/': [@@ -90,6 +102,34 @@ describe('llmPlaygroundRunLogic', () => {streamSpy.mockRestore()})+ it('does not run a completion without editor access to the playground and explains why', async () => {+ // Both message textareas submit on Cmd+Enter, bypassing the Run button's disabledReason,+ // so the gate has to hold in the logic itself.+ setPlaygroundAccessLevel(AccessControlLevel.Viewer)+ const streamSpy = jest.spyOn(api, 'stream')+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')++ const logic = llmPlaygroundRunLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ llmPlaygroundPromptsLogic.actions.setModel('gpt-5-mini')+ llmPlaygroundPromptsLogic.actions.setMessages([{ role: 'user', content: 'hello' }])+ llmPlaygroundRunLogic.actions.submitPrompt()++ await expectLogic(logic).toFinishAllListeners()++ expect(streamSpy).not.toHaveBeenCalled()+ expect(toastSpy).toHaveBeenCalledWith(+ "You don't have sufficient permissions for this LLM playground. Your access level (viewer) doesn't meet the required level (editor)."+ )+ await expectLogic(logic).toMatchValues({ submitting: false })++ logic.unmount()+ streamSpy.mockRestore()+ toastSpy.mockRestore()+ })+it('surfaces backend error message and captures exception when stream fails with ApiError', async () => {const apiError = new ApiError('fallback message', 400, undefined, {error: 'Thinking is not supported for this model',diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.tsindex daa463b9bf3a..09743874ce6c 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts@@ -1,12 +1,15 @@-import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api, { ApiError, RateLimitError } from 'lib/api'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { uuid } from 'lib/utils/dom'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import type { ModelOption } from '../modelPickerLogic'import { llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import type { LLMProviderKey } from '../settings/llmProviderKeysLogic'@@ -161,6 +164,7 @@ export interface llmPlaygroundRunLogicValues {providerKeys: LLMProviderKey[] // llmProviderKeysLogiccomparisonItems: ComparisonItem[]rateLimitedUntil: number | null+ runAccessDeniedReason: string | nullsubmitting: booleansubscriptionRequired: boolean}@@ -264,6 +268,16 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([],}),+ selectors({+ // Resource-level only, so this comes from the server-rendered app context rather than the API.+ // A selector keeps it readable from the scene and overridable in tests.+ runAccessDeniedReason: [+ () => [],+ (): string | null =>+ getAccessControlDisabledReason(AccessControlResourceType.LlmPlayground, AccessControlLevel.Editor),+ ],+ }),+listeners(({ actions, values }) => ({abortRun: () => {posthog.capture('llma playground prompt aborted')@@ -279,6 +293,14 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([},submitPrompt: async (_: unknown, breakpoint: () => void) => {+ // Guarding here rather than only on the Run button, because both message textareas+ // submit on Cmd+Enter and bypass the button entirely.+ if (values.runAccessDeniedReason) {+ lemonToast.error(values.runAccessDeniedReason)+ actions.finishSubmitPrompt()+ return+ }+const runnablePrompts = values.promptConfigs.map((prompt: PromptConfig, index: number) => ({prompt,diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 9a937c1fbde6..3e2b4f25a660 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -115,6 +115,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['llm_analytics:write','ai_observability_clusters:read','ai_observability_clusters:write',+ 'llm_playground:read',+ 'llm_playground:write','llm_prompt:read','llm_prompt:write','llm_provider_key:read',