: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(skills): add access control (#71985)
Reece Jonesce8e180d9872
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex f1ca7fd5d2fa..8e71878d51ae 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -91,6 +91,7 @@ export const getStorybookAppContext = (): AppContext => ({activity_log: 'viewer',customer_analytics: 'manager',llm_analytics: 'manager',+ llm_skill: 'manager',toolbar: 'viewer',error_tracking: 'manager',metrics: 'manager',diff --git a/ee/migrations/0052_backfill_llm_skill_access_control.py b/ee/migrations/0052_backfill_llm_skill_access_control.pynew file mode 100644index 000000000000..b5fffd84475b--- /dev/null+++ b/ee/migrations/0052_backfill_llm_skill_access_control.py@@ -0,0 +1,49 @@+from django.db import migrations++CHUNK_SIZE = 200+++def backfill_llm_skill_access_control(apps, schema_editor):+ # llm_skill used to inherit its access level from llm_analytics (RESOURCE_INHERITANCE_MAP); now+ # that it's an independent resource, mirror every resource-wide llm_analytics grant onto a+ # matching llm_skill row so existing permissions keep working instead of silently falling back+ # to the default access level (editor, for everyone).+ #+ # Only resource-wide (resource_id=None) rows are in scope: RESOURCE_INHERITANCE_MAP only ever+ # backs the resource-level fallback (_access_controls_filters_for_resource hardcodes+ # resource_id=None) - object-level checks never consult it and always query the child resource+ # directly (see has_access_levels_for_resource in user_access_control.py). A resource_id-scoped+ # llm_analytics row is therefore a per-object grant on one of its OTHER children (dataset,+ # evaluation, tagger, llm_provider_key, llm_prompt - each queried under its own resource string)+ # and was never part of llm_skill's access resolution, so it's excluded here.+ #+ # llm_skill is also the scope_object for review_hog's config viewsets (blind spots, perspectives,+ # validators), which reused it rather than getting their own resource - so this also covers teams+ # that use those without ever touching Skills.+ 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_skill",+ 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", "0051_backfill_ai_observability_clusters_access_control"),+ ]++ operations = [+ migrations.RunPython(backfill_llm_skill_access_control, reverse_func),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex 2cf5ce4bb2f5..0809a51236a6 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0051_backfill_ai_observability_clusters_access_control+0052_backfill_llm_skill_access_controldiff --git a/ee/migrations/test/test_migration_0052.py b/ee/migrations/test/test_migration_0052.pynew file mode 100644index 000000000000..36a8a3f74da5--- /dev/null+++ b/ee/migrations/test/test_migration_0052.py@@ -0,0 +1,109 @@+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.0052_backfill_llm_skill_access_control")+backfill_llm_skill_access_control = migration_module.backfill_llm_skill_access_control+++class TestBackfillLlmSkillAccessControl(BaseTest):+ @parameterized.expand(+ [+ ("member_scoped",),+ ("role_scoped",),+ ("org_default",),+ ]+ )+ def test_backfills_resource_wide_row(self, case):+ role = (+ Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None+ )+ scope_kwargs = {+ "organization_member": self.organization_membership if case == "member_scoped" else None,+ "role": role,+ }++ AccessControl.objects.create(+ team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs+ )++ backfill_llm_skill_access_control(apps, None)++ backfilled = AccessControl.objects.filter(resource="llm_skill", team=self.team, **scope_kwargs).first()+ assert backfilled is not None+ assert backfilled.access_level == "viewer"++ def test_ignores_object_scoped_llm_analytics_rows(self):+ # A resource_id-scoped llm_analytics row is a per-object grant on one of its OTHER children+ # (dataset/evaluation/tagger/...) - those are always looked up under their own resource+ # string, never through llm_analytics, so this row has nothing to do with llm_skill.+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id="123",+ access_level="editor",+ organization_member=self.organization_membership,+ )++ backfill_llm_skill_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="llm_skill").exists()++ 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_skill_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="llm_skill").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_skill",+ resource_id=None,+ access_level="none",+ organization_member=self.organization_membership,+ )++ backfill_llm_skill_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="llm_skill", organization_member=self.organization_membership)+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.access_level == "none"++ def test_idempotent_on_repeat_run(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id=None,+ access_level="viewer",+ organization_member=self.organization_membership,+ )++ backfill_llm_skill_access_control(apps, None)+ backfill_llm_skill_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="llm_skill", organization_member=self.organization_membership)+ assert rows.count() == 1diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2e6b67234871..5126f8457d05 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6959,9 +6959,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.35ab1c3442aaccdbb00253b12ad6089831b2209787d912bfc01f1a5abf755143.vVggYZAeyiGeJdZ8z_TKe4kK28uMUWsAJAMcPlkWalg+ hash: v1.k794b7964.9a85d1e551f875692d6f1ffec62f8db8e27c384e2e2b5ce505c2647d604fbd14.Sdhkzdt1LZM6P9-gz98b5hIczvxj3QsmiQVZI0FTyeEscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.3978b710d289d946d4edc8d7f40937b8c9150a6d8bbe8a4bdeb146f6fd407392.MuAto5ws3gu7dkA9fPauGjGoIrDkKuOE12h_D7DBoQQ+ hash: v1.k794b7964.432e453fa102c92bf70534288829d72f0e4c36ec027701bf5522af3e94ea7209.RnsHAOIeR-82mYRPBBwrqKeJxpZpiMml7wuf8xuN3dAscenes-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 51881391a672..381dc0a714a6 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@@ -13,6 +13,7 @@ import {IconLive,IconListTree,IconLlmAnalytics,+ IconLlmPromptManagement,IconMessage,IconNotebook,IconNotification,@@ -69,6 +70,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconTrends />case 'llm_analytics':return <IconLlmAnalytics />+ case 'llm_skill':+ return <IconLlmPromptManagement />case 'ai_observability_clusters':return <IconScatter />case 'live_debugger':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 50189b089a21..f633659f4105 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@@ -181,6 +181,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.FeatureFlag,AccessControlResourceType.Insight,AccessControlResourceType.LlmAnalytics,+ AccessControlResourceType.LlmSkill,AccessControlResourceType.AiObservabilityClusters,AccessControlResourceType.Metrics,AccessControlResourceType.Notebook,diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.tsindex 5f59c382b469..4044cd2900e4 100644--- a/frontend/src/lib/utils/accessControlUtils.ts+++ b/frontend/src/lib/utils/accessControlUtils.ts@@ -61,6 +61,8 @@ export const pluralizeResource = (resource: APIScopeObject): string => {return 'customer analytics'} else if (resource === AccessControlResourceType.LlmAnalytics) {return 'AI observability'+ } else if (resource === AccessControlResourceType.LlmSkill) {+ return 'skills'} else if (resource === AccessControlResourceType.AiObservabilityClusters) {return 'AI trace clusters'} else if (resource === AccessControlResourceType.RevenueAnalytics) {@@ -125,6 +127,8 @@ export const resourceTypeToString = (resourceType: AccessControlResourceType): sreturn 'customer analytics resource'} else if (resourceType === AccessControlResourceType.LlmAnalytics) {return 'AI observability resource'+ } else if (resourceType === AccessControlResourceType.LlmSkill) {+ return 'skill'} 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 f42cdc2f165b..36ca4388ca29 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -164,6 +164,8 @@ export enum Scene {Settings = 'Settings',Signup = 'Signup',Site = 'Site',+ Skill = 'Skill',+ Skills = 'Skills',Coupons = 'Coupons',Sources = 'Sources',StartupProgram = 'StartupProgram',@@ -422,6 +424,10 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.AIObservabilityTrace]: AccessControlResourceType.LlmAnalytics,[Scene.AIObservabilityUsers]: AccessControlResourceType.LlmAnalytics,+ // Skills+ [Scene.Skill]: AccessControlResourceType.LlmSkill,+ [Scene.Skills]: AccessControlResourceType.LlmSkill,+// Data warehouse sources - not included here because self-managed sources don't have access control.// Managed sources handle access control at the logic level via SIDE_PANEL_CONTEXT_KEY.}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 134aba05070c..d1fcc703eae3 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -292,6 +292,7 @@ export enum AccessControlResourceType {Dashboard = 'dashboard',DashboardTemplate = 'dashboard_template',LlmAnalytics = 'llm_analytics',+ LlmSkill = 'llm_skill',AiObservabilityClusters = 'ai_observability_clusters',Notebook = 'notebook',SessionRecording = 'session_recording',diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex e2bef593ec8e..1d7afb9825b4 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -72,6 +72,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("hog_flow","insight","llm_analytics",+ "llm_skill","ai_observability_clusters","notebook","revenue_analytics",@@ -99,7 +100,6 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {"dataset": "llm_analytics","llm_provider_key": "llm_analytics","llm_prompt": "llm_analytics",- "llm_skill": "llm_analytics","account": "customer_analytics","customer_journey": "customer_analytics","experiment_saved_metric": "experiment",diff --git a/products/agent_platform/backend/logic/skill_editing.py b/products/agent_platform/backend/logic/skill_editing.pyindex a1ef8ec65fdc..47b426c7101e 100644--- a/products/agent_platform/backend/logic/skill_editing.py+++ b/products/agent_platform/backend/logic/skill_editing.py@@ -64,8 +64,7 @@ def assert_skills_writable(returns ``None`` for it), so ``check_access_level_for_object`` passesunconditionally and must not be mistaken for a boundary. The resource-levelcheck is what ``LLMSkillViewSet`` actually enforces — it honours both- team-wide lockdowns and member-specific grants on the inherited- ``llm_analytics`` resource.+ team-wide lockdowns and member-specific grants on the ``llm_skill`` resource."""if not names:returndiff --git a/products/agent_platform/backend/tests/test_bundle_editing.py b/products/agent_platform/backend/tests/test_bundle_editing.pyindex 153d568b980e..a2a046802f0d 100644--- a/products/agent_platform/backend/tests/test_bundle_editing.py+++ b/products/agent_platform/backend/tests/test_bundle_editing.py@@ -556,8 +556,7 @@ class TestBundleEditing(APIBaseTest):def _lock_down_skills(self) -> None:# Grant-based skill access: demote the user to member and restrict the- # skills resource (llm_skill inherits its access-control resource from- # llm_analytics) to viewer team-wide, so only explicit grants can edit.+ # llm_skill resource to viewer team-wide, so only explicit grants can edit.self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},{"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},@@ -565,7 +564,7 @@ class TestBundleEditing(APIBaseTest):self.organization.save()self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()- AccessControl.objects.create(team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer")+ AccessControl.objects.create(team=self.team, resource="llm_skill", resource_id=None, access_level="viewer")def test_import_of_new_skill_denied_without_resource_level_editor_access(self) -> None:# A brand-new id means the import CREATES a shared store skill, so it@@ -606,7 +605,7 @@ class TestBundleEditing(APIBaseTest):self._lock_down_skills()AccessControl.objects.create(team=self.team,- resource="llm_analytics",+ resource="llm_skill",resource_id=None,access_level="editor",organization_member=self.organization_membership,diff --git a/products/review_hog/backend/api/blind_spots.py b/products/review_hog/backend/api/blind_spots.pyindex 2f07038d04c0..f0a705f61236 100644--- a/products/review_hog/backend/api/blind_spots.py+++ b/products/review_hog/backend/api/blind_spots.py@@ -67,7 +67,7 @@ class ReviewBlindSpotsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewfloor is needed."""- # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_analytics RBAC+ # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_skill RBAC# gate must apply — INTERNAL short-circuits AccessControlPermission before it checks anything.scope_object = "llm_skill"# Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.diff --git a/products/review_hog/backend/api/perspectives.py b/products/review_hog/backend/api/perspectives.pyindex dd4480c1cea6..6c22289ea2ca 100644--- a/products/review_hog/backend/api/perspectives.py+++ b/products/review_hog/backend/api/perspectives.py@@ -57,7 +57,7 @@ class ReviewPerspectiveConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViecall). At least one perspective must stay enabled."""- # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_analytics RBAC+ # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_skill RBAC# gate must apply — INTERNAL short-circuits AccessControlPermission before it checks anything.scope_object = "llm_skill"# Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.diff --git a/products/review_hog/backend/api/validators.py b/products/review_hog/backend/api/validators.pyindex b4b9c19e7f18..c5e868bba527 100644--- a/products/review_hog/backend/api/validators.py+++ b/products/review_hog/backend/api/validators.py@@ -65,7 +65,7 @@ class ReviewValidatorConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSsame call. There is always a default (the canonical), so no minimum floor is needed."""- # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_analytics RBAC+ # llm_skill, not INTERNAL: responses carry skill body/description, so the llm_skill RBAC# gate must apply — INTERNAL short-circuits AccessControlPermission before it checks anything.scope_object = "llm_skill"# Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.diff --git a/products/review_hog/backend/tests/test_blind_spots_config_api.py b/products/review_hog/backend/tests/test_blind_spots_config_api.pyindex c4a74dce6e79..91f3d2ad9aa0 100644--- a/products/review_hog/backend/tests/test_blind_spots_config_api.py+++ b/products/review_hog/backend/tests/test_blind_spots_config_api.py@@ -153,7 +153,7 @@ class TestReviewBlindSpotsConfigAPI(APIBaseTest):def test_list_api_key_scope_is_llm_skill(self, _name: str, scopes: list[str], expected_status: int) -> None:# The menu returns skill body/description, so the endpoint is scoped `llm_skill` like the# skills API — a revert to INTERNAL would reject the read-scoped key here AND silently skip- # the llm_analytics RBAC gate for session users.+ # the llm_skill RBAC gate for session users.api_key = self.create_personal_api_key_with_scopes(scopes)self.client.logout()self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")diff --git a/products/review_hog/backend/tests/test_perspective_config_api.py b/products/review_hog/backend/tests/test_perspective_config_api.pyindex 0039dc3b7b37..0b4a848a8bf9 100644--- a/products/review_hog/backend/tests/test_perspective_config_api.py+++ b/products/review_hog/backend/tests/test_perspective_config_api.py@@ -150,7 +150,7 @@ class TestReviewPerspectiveConfigAPI(APIBaseTest):def test_list_api_key_scope_is_llm_skill(self, _name: str, scopes: list[str], expected_status: int) -> None:# The menu returns skill body/description, so the endpoint is scoped `llm_skill` like the# skills API — a revert to INTERNAL would reject the read-scoped key here AND silently skip- # the llm_analytics RBAC gate for session users.+ # the llm_skill RBAC gate for session users.api_key = self.create_personal_api_key_with_scopes(scopes)self.client.logout()self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")diff --git a/products/review_hog/backend/tests/test_validator_config_api.py b/products/review_hog/backend/tests/test_validator_config_api.pyindex 168aa5bd3d58..64904370b0db 100644--- a/products/review_hog/backend/tests/test_validator_config_api.py+++ b/products/review_hog/backend/tests/test_validator_config_api.py@@ -189,7 +189,7 @@ class TestReviewValidatorConfigAPI(APIBaseTest):def test_list_api_key_scope_is_llm_skill(self, _name: str, scopes: list[str], expected_status: int) -> None:# The menu returns skill body/description, so the endpoint is scoped `llm_skill` like the# skills API — a revert to INTERNAL would reject the read-scoped key here AND silently skip- # the llm_analytics RBAC gate for session users.+ # the llm_skill RBAC gate for session users.api_key = self.create_personal_api_key_with_scopes(scopes)self.client.logout()self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.pyindex edeb7daffb21..f40ee0f44484 100644--- a/products/skills/backend/api/test/test_marketplace_endpoints.py+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py@@ -548,10 +548,9 @@ class TestSkillMarketplaceRBAC(APIBaseTest):AccessControl.objects.create(team=self.team, resource="project", resource_id=str(self.team.id), access_level="member")- # Skills inherit their access-control resource from llm_analytics (RESOURCE_INHERITANCE_MAP).# Make access grant-based: the resource default is "none", so a member only gets in with an# explicit grant — restricting the default is how skill access is actually gated.- AccessControl.objects.create(team=self.team, resource="llm_analytics", resource_id=None, access_level="none")+ AccessControl.objects.create(team=self.team, resource="llm_skill", resource_id=None, access_level="none")LLMSkill.objects.create(team=self.team,name="make-fractals",@@ -582,7 +581,7 @@ class TestSkillMarketplaceRBAC(APIBaseTest):def test_member_with_skill_access_can_clone(self):AccessControl.objects.create(team=self.team,- resource="llm_analytics",+ resource="llm_skill",resource_id=None,access_level="viewer",organization_member=self._membership(),diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 1687dfc1259a..613db29929d5 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -2,13 +2,18 @@ import uuidfrom posthog.test.base import APIBaseTest+from django.core.cache import cachefrom django.db import connectionfrom django.test.utils import CaptureQueriesContextfrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models import User+from posthog.models.organization import OrganizationMembership++from ee.models.rbac.access_control import AccessControlfrom ...api.skill_serializers import DEFAULT_BODY_PAGE_LENGTHfrom ...api.skill_services import MAX_SKILL_FILE_COUNT@@ -1321,3 +1326,119 @@ class TestLLMSkillAPI(APIBaseTest):assert len(data["versions"]) == 2assert data["versions"][0]["version"] == 2assert data["versions"][1]["version"] == 1+++# llm_skill is its own access-control resource (see ACCESS_CONTROL_RESOURCES in+# posthog/rbac/user_access_control.py) - same as TestSkillMarketplaceRBAC in+# test_marketplace_endpoints.py covers for the git clone endpoint, this covers the JSON skill API.+class TestSkillAccessControlRBAC(APIBaseTest):+ def setUp(self):+ super().setUp()+ cache.clear()+ 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"+ )+ # Default is "none" - a member only gets skill access via an explicit grant below.+ AccessControl.objects.create(team=self.team, resource="llm_skill", resource_id=None, access_level="none")+ self.skill = LLMSkill.objects.create(+ team=self.team,+ name="make-fractals",+ description="d",+ body="# x\n",+ version=1,+ is_latest=True,+ created_by=self.user,+ )+ self.member = User.objects.create_and_join(self.organization, "[email protected]", "pw")+ self.client.force_login(self.member)++ def _url(self, path: str = "") -> str:+ return f"/api/environments/{self.team.id}/llm_skills/{path}"++ def _grant_llm_skill_access(self, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=None,+ access_level=access_level,+ organization_member=membership,+ )++ @parameterized.expand(+ [+ ("list",),+ ("get_by_name",),+ ]+ )+ def test_member_without_skill_access_cannot_read(self, action):+ path = "" if action == "list" else f"name/{self.skill.name}"+ response = self.client.get(self._url(path))+ assert response.status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(+ [+ ("create",),+ ("update_by_name",),+ ]+ )+ def test_member_without_skill_access_cannot_write(self, action):+ if action == "create":+ response = self.client.post(+ self._url(), data={"name": "new-skill", "description": "d", "body": "x"}, format="json"+ )+ else:+ response = self.client.patch(+ self._url(f"name/{self.skill.name}"),+ data={"description": "d2", "base_version": 1},+ format="json",+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_viewer_can_read_but_not_write(self):+ self._grant_llm_skill_access("viewer")++ assert self.client.get(self._url()).status_code == status.HTTP_200_OK+ assert self.client.get(self._url(f"name/{self.skill.name}")).status_code == status.HTTP_200_OK++ create_response = self.client.post(+ self._url(), data={"name": "new-skill", "description": "d", "body": "x"}, format="json"+ )+ assert create_response.status_code == status.HTTP_403_FORBIDDEN++ update_response = self.client.patch(+ self._url(f"name/{self.skill.name}"),+ data={"description": "d2", "base_version": 1},+ format="json",+ )+ assert update_response.status_code == status.HTTP_403_FORBIDDEN++ def test_editor_can_create_and_update(self):+ self._grant_llm_skill_access("editor")++ create_response = self.client.post(+ self._url(), data={"name": "new-skill", "description": "d", "body": "x"}, format="json"+ )+ assert create_response.status_code == status.HTTP_201_CREATED++ update_response = self.client.patch(+ self._url(f"name/{self.skill.name}"),+ data={"description": "d2", "base_version": 1},+ format="json",+ )+ assert update_response.status_code == status.HTTP_200_OK++ def test_org_admin_has_full_access_without_explicit_grant(self):+ membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ response = self.client.post(+ self._url(), data={"name": "new-skill", "description": "d", "body": "x"}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATEDdiff --git a/products/skills/frontend/LLMSkillScene.tsx b/products/skills/frontend/LLMSkillScene.tsxindex 642d1298ba2b..5d6e3270db02 100644--- a/products/skills/frontend/LLMSkillScene.tsx+++ b/products/skills/frontend/LLMSkillScene.tsx@@ -24,6 +24,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonMarkdownWithMermaid } from 'lib/lemon-ui/LemonMarkdown/LemonMarkdownWithMermaid'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { userHasAccess } from 'lib/utils/accessControlUtils'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { lazyWithRetry } from 'lib/utils/retryImport'import { SceneExport } from 'scenes/sceneTypes'@@ -93,174 +94,96 @@ export function LLMSkillScene(): JSX.Element {)}- const content = isViewMode ? (- <SceneContent>- <SceneTitleSection- name={skill && 'name' in skill ? skill.name : 'Skill'}- resourceType={{ type: 'llm_analytics' }}- isLoading={skillLoading}- actions={- <>- {isSkill(skill) && skill.is_latest ? (- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- icon={<IconPencil />}- onClick={() => setMode(SkillMode.Edit)}- size="small"- data-attr="llma-skill-edit-button"- >- Edit latest- </LemonButton>- </AccessControlAction>- ) : (- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- onClick={() => {- if (isSkill(skill)) {- setSkillFormValues({- name: skill.name,- description: skill.description,- body: skill.body,- license: skill.license || '',- compatibility: skill.compatibility || '',- })- setMode(SkillMode.Edit)- }- }}- size="small"- data-attr="llma-skill-use-as-latest-button"- >- Use as latest- </LemonButton>- </AccessControlAction>- )}-- {isSkill(skill) && (- <LemonButton- type="secondary"- icon={<IconDownload />}- onClick={downloadSkill}- loading={downloadingZip}- size="small"- tooltip="Download this skill as a spec-compliant .zip (SKILL.md + bundled files)"- data-attr="llma-skill-download-zip-button"- >- Download .zip- </LemonButton>- )}-- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="secondary"- status="danger"- icon={<IconTrash />}- onClick={() => openArchiveSkillDialog(deleteSkill)}- size="small"- data-attr="llma-skill-delete-button"- >- Archive- </LemonButton>- </AccessControlAction>- </>- }- />-- <div className="flex flex-col gap-6 2xl:flex-row">- <div className="min-w-0 flex-1">- <SkillViewDetails />- </div>-- {!isNewSkill && (- <SkillVersionSidebar- skillName={isSkill(skill) ? skill.name : ''}- skill={isSkill(skill) ? skill : null}- versions={versions}- versionsLoading={versionsLoading}- canLoadMoreVersions={canLoadMoreVersions}- loadMoreVersions={loadMoreVersions}- searchParams={searchParams ?? {}}- />- )}- </div>- </SceneContent>- ) : (- <Form id="skill-form" formKey="skillForm" logic={llmSkillLogic}>+ // A direct link with `?edit=true` shouldn't grant edit access the Edit/Use-as-latest buttons+ // wouldn't otherwise give — fall back to the read-only view when the user can't actually publish.+ const canEditSkill = userHasAccess(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor)+ const content =+ isViewMode || !canEditSkill ? (<SceneContent><SceneTitleSection- name={skillForm.name || 'New skill'}- resourceType={{ type: 'llm_analytics' }}+ name={skill && 'name' in skill ? skill.name : 'Skill'}+ resourceType={{ type: 'llm_skill' }}isLoading={skillLoading}actions={<>- <LemonButton- type="secondary"- onClick={() => {- if (isNewSkill) {- router.actions.push(urls.skills())- } else {- setMode(SkillMode.View)- }- }}- disabledReason={isSkillFormSubmitting ? 'Saving...' : undefined}- size="small"- data-attr="llma-skill-cancel-button"- >- Cancel- </LemonButton>-- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- onClick={submitSkillForm}- loading={isSkillFormSubmitting}- size="small"- data-attr={isNewSkill ? 'skill-create-button' : 'skill-save-button'}+ {isSkill(skill) && skill.is_latest ? (+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}>- {isNewSkill ? 'Create skill' : 'Publish version'}- </LemonButton>- </AccessControlAction>-- {!isNewSkill && (+ <LemonButton+ type="primary"+ icon={<IconPencil />}+ onClick={() => setMode(SkillMode.Edit)}+ size="small"+ data-attr="llma-skill-edit-button"+ >+ Edit latest+ </LemonButton>+ </AccessControlAction>+ ) : (<AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton- type="secondary"- status="danger"- icon={<IconTrash />}- onClick={() => openArchiveSkillDialog(deleteSkill)}+ type="primary"+ onClick={() => {+ if (isSkill(skill)) {+ setSkillFormValues({+ name: skill.name,+ description: skill.description,+ body: skill.body,+ license: skill.license || '',+ compatibility: skill.compatibility || '',+ })+ setMode(SkillMode.Edit)+ }+ }}size="small"- data-attr="llma-skill-delete-button"+ data-attr="llma-skill-use-as-latest-button">- Archive+ Use as latest</LemonButton></AccessControlAction>)}++ {isSkill(skill) && (+ <LemonButton+ type="secondary"+ icon={<IconDownload />}+ onClick={downloadSkill}+ loading={downloadingZip}+ size="small"+ tooltip="Download this skill as a spec-compliant .zip (SKILL.md + bundled files)"+ data-attr="llma-skill-download-zip-button"+ >+ Download .zip+ </LemonButton>+ )}++ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ onClick={() => openArchiveSkillDialog(deleteSkill)}+ size="small"+ data-attr="llma-skill-delete-button"+ >+ Archive+ </LemonButton>+ </AccessControlAction></>}/><div className="flex flex-col gap-6 2xl:flex-row"><div className="min-w-0 flex-1">- <SkillEditForm- isHistoricalVersion={isHistoricalVersion}- fileContentsLoading={fileContentsLoading}- />+ <SkillViewDetails /></div>{!isNewSkill && (@@ -276,8 +199,90 @@ export function LLMSkillScene(): JSX.Element {)}</div></SceneContent>- </Form>- )+ ) : (+ <Form id="skill-form" formKey="skillForm" logic={llmSkillLogic}>+ <SceneContent>+ <SceneTitleSection+ name={skillForm.name || 'New skill'}+ resourceType={{ type: 'llm_analytics' }}+ isLoading={skillLoading}+ actions={+ <>+ <LemonButton+ type="secondary"+ onClick={() => {+ if (isNewSkill) {+ router.actions.push(urls.skills())+ } else {+ setMode(SkillMode.View)+ }+ }}+ disabledReason={isSkillFormSubmitting ? 'Saving...' : undefined}+ size="small"+ data-attr="llma-skill-cancel-button"+ >+ Cancel+ </LemonButton>++ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ onClick={submitSkillForm}+ loading={isSkillFormSubmitting}+ size="small"+ data-attr={isNewSkill ? 'skill-create-button' : 'skill-save-button'}+ >+ {isNewSkill ? 'Create skill' : 'Publish version'}+ </LemonButton>+ </AccessControlAction>++ {!isNewSkill && (+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmSkill}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ onClick={() => openArchiveSkillDialog(deleteSkill)}+ size="small"+ data-attr="llma-skill-delete-button"+ >+ Archive+ </LemonButton>+ </AccessControlAction>+ )}+ </>+ }+ />++ <div className="flex flex-col gap-6 2xl:flex-row">+ <div className="min-w-0 flex-1">+ <SkillEditForm+ isHistoricalVersion={isHistoricalVersion}+ fileContentsLoading={fileContentsLoading}+ />+ </div>++ {!isNewSkill && (+ <SkillVersionSidebar+ skillName={isSkill(skill) ? skill.name : ''}+ skill={isSkill(skill) ? skill : null}+ versions={versions}+ versionsLoading={versionsLoading}+ canLoadMoreVersions={canLoadMoreVersions}+ loadMoreVersions={loadMoreVersions}+ searchParams={searchParams ?? {}}+ />+ )}+ </div>+ </SceneContent>+ </Form>+ )return content}diff --git a/products/skills/frontend/LLMSkillsScene.tsx b/products/skills/frontend/LLMSkillsScene.tsxindex f1fc76fbcc73..601d645fc4b4 100644--- a/products/skills/frontend/LLMSkillsScene.tsx+++ b/products/skills/frontend/LLMSkillsScene.tsx@@ -151,7 +151,7 @@ function buildSkillColumns(</LemonButton><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -187,7 +187,7 @@ function buildSkillColumns(</AccessControlAction><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -350,7 +350,7 @@ function MarketplaceCredentialSection(): JSX.Element {{!justIssued && (<div><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -493,7 +493,7 @@ export function LLMSkillsScene(): JSX.Element {Load skills in your agent</LemonButton><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -509,7 +509,7 @@ export function LLMSkillsScene(): JSX.Element {</LemonButton></AccessControlAction><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.LlmSkill}minAccessLevel={AccessControlLevel.Editor}><LemonButton