: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(skills): restrict community publishing to the skill's owners (#88360)
Andrew Maguire0530e9b535fa
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.mdindex 5c0af545695b..348724dc86f5 100644--- a/docs/internal/skills/community-skills-api.md+++ b/docs/internal/skills/community-skills-api.md@@ -157,10 +157,31 @@ The target repo is public, so a failed publish must not leave anything behind:- Content becomes public at the branch write, before the pull request that moderates it. Confirmingthat with the user is a UI concern, and it gates enabling the flag rather than shipping this code.-Errors surface as `400` (invalid payload), `404` (unknown skill), `502` (GitHub refused a step), or-`503` when the instance has no publisher App configured. The 503 is the fail-safe that keeps-publishing off until the GitHub App is installed. A private key that cannot sign is a 503 too: it is-a deployment nobody can retry their way out of, so it must not read as GitHub being down.+### Who can publish++Publishing a skill is restricted to that skill's own owners (`LLMSkillOwner`), on top of the access+`AccessControlPermission` already requires. `CommunityPublishOwnerPermission` enforces it.++Ownership is an audit claim on top of editor access, not a separate authorization boundary. Any+member with edit access to a skill can add themselves as an owner through `PATCH name/<slug>`, so+publishing means an editor took ownership of that skill explicitly, and the `LLMSkillOwner` row+records who did and when. Reach across skills is closed by the object-level check on every+`name/<slug>` action, not by ownership. Owner rows are filtered by current project access rather+than deleted when access goes away, so a member who regains access is an owner again; that is+equivalent to them adding themselves back, and it keeps a skill whose owners all left readable as+"owned, nobody current" rather than as unowned.++A skill with no current owners is publishable by nobody, and answers `403`. Owners leave the set when+a member loses project access, and a skill can be created with an explicit empty owner list, so the+alternative is a fallback to edit access for exactly the skills that have nobody to answer for them.+Adding an owner is the remedy. There is no exemption for project or organization admins; an admin who+wants to publish adds themselves as an owner first.++Errors surface as `400` (invalid payload), `403` (the requester does not own the skill, or it has no+owners), `404` (unknown skill), `502` (GitHub refused a step), or `503` when the instance has no+publisher App configured. The 503 is the fail-safe that keeps publishing off until the GitHub App is+installed. A private key that cannot sign is a 503 too: it is a deployment nobody can retry their way+out of, so it must not read as GitHub being down.The three are kept apart on purpose, because each sends the publisher somewhere different. The skillis rendered before GitHub is touched, so a skill that has to be edited answers `400` even while thediff --git a/products/signals/backend/management/commands/reset_signals_self_driving.py b/products/signals/backend/management/commands/reset_signals_self_driving.pyindex b9a895ea3efc..3ceb3248ae4d 100644--- a/products/signals/backend/management/commands/reset_signals_self_driving.py+++ b/products/signals/backend/management/commands/reset_signals_self_driving.py@@ -19,7 +19,7 @@ from products.signals.backend.models import (SignalSourceConfig,)from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX-from products.skills.backend.models.skills import LLMSkill+from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner# Seed tag stamped on canonical scouts + the `authoring-scouts` companion; this DEBUG# reset preserves tagged rows. Not a perfect canonical marker (`_scout_origin` also checks the@@ -157,6 +157,11 @@ class Command(BaseCommand):skills_deleted = 0if custom_scout_names:skills_deleted, _ = LLMSkill.objects.filter(team_id=team.id, name__in=custom_scout_names).delete()+ # Owner rows key on the logical name, not the version row, so they do not cascade. A+ # scout recreated under the same name would otherwise inherit the old owners.+ LLMSkillOwner.objects.for_team(team.id, canonical=True).filter(+ skill_name__in=custom_scout_names+ ).delete()# Scout fleet config (canonical + custom). Deleting — not disabling — restores the# fresh-team shape: the next wizard `sync` re-creates canonical configs enabled.diff --git a/products/signals/backend/test/test_reset_signals_self_driving.py b/products/signals/backend/test/test_reset_signals_self_driving.pyindex 1cbf65d7fc1f..3984b3b63e5e 100644--- a/products/signals/backend/test/test_reset_signals_self_driving.py+++ b/products/signals/backend/test/test_reset_signals_self_driving.py@@ -6,6 +6,8 @@ from unittest import mockfrom django.core.management import call_commandfrom django.test import override_settings+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+from products.skills.backend.api.skill_services import create_skill, resolve_skill_owners, set_skill_ownersfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource_SERVICE = "products.data_warehouse.backend.logic.data_load.service"@@ -153,3 +155,18 @@ class TestResetSignalsSelfDrivingProductToggles(BaseTest):assert "should have enabled, but didn't" in outputfor label in ("Session Replay", "Error Tracking", "Support / Conversations"):assert label in output+++@override_settings(DEBUG=True)+class TestResetSignalsSelfDrivingCustomScouts(BaseTest):+ def test_deleting_custom_scouts_also_drops_their_owner_rows(self) -> None:+ # Owner rows key on (team, name) rather than the version row, so the hard delete does not+ # cascade to them. A scout recreated under the same name would inherit the old owners and+ # let a stale owner publish it.+ name = f"{SIGNALS_SCOUT_SKILL_PREFIX}custom-checkout"+ create_skill(self.team, user=self.user, name=name, description="d", body="# b")+ set_skill_owners(self.team, name, [self.user])++ call_command("reset_signals_self_driving", team_id=self.team.id, yes=True, keep_findings=True, keep_log=True)++ assert resolve_skill_owners(self.team, name) == []diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 83091537e051..12414988a1fa 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -11,10 +11,13 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schemafrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import NotFoundfrom rest_framework.parsers import FormParser, MultiPartParser+from rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer+from rest_framework.views import APIViewfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -101,6 +104,7 @@ from .skill_services import (publish_skill_version,rename_skill_file,resolve_owner_users,+ resolve_skill_owners,resolve_skill_owners_for_names,resolve_versions_page,set_skill_owners,@@ -184,6 +188,54 @@ class CommunityPublishFeatureFlagPermission(CommunitySkillFeatureFlagPermission)return super().has_permission(request, view)+class CommunityPublishOwnerPermission(BasePermission):+ """Restricts publishing to the community to the skill's own owners, and gates nothing else here.++ Publishing writes the skill into a public repository, so it asks for a stronger claim on the skill+ than editing it does. The claim must also be per skill. `AccessControlPermission.has_permission`+ passes a member who holds an object-level grant on any one skill, and the `name/<slug>` actions+ then load whichever skill the URL names, so edit access alone reaches every skill in the project.++ A skill with no current owners is publishable by nobody. Owners leave the set when a member loses+ project access, and a skill can be created with an explicit empty owner list, so the alternative is+ a fallback to edit access for exactly the skills that have nobody to answer for them. Adding an+ owner is the remedy, and the message says so.+ """++ NO_OWNERS_MESSAGE = "This skill has no owners. Add an owner to publish it."+ NOT_OWNER_MESSAGE = (+ "Only an owner can publish this skill to the community. Ask an owner to publish it, or to add you as one."+ )++ def has_permission(self, request: Request, view: APIView) -> bool:+ if getattr(view, "action", None) != "publish_to_community":+ return True++ user = request.user+ if not user or not user.is_authenticated:+ return False++ skill_view = cast("LLMSkillViewSet", view)+ try:+ team = skill_view.team+ except (ValueError, KeyError, AttributeError):+ return False++ skill_name = skill_view.kwargs.get("skill_name") or ""+ owners = resolve_skill_owners(team, skill_name)+ if any(owner.pk == user.pk for owner in owners):+ return True++ # A slug that names no skill answers 404, the way every other `name/<slug>` action answers it,+ # because a skill that does not exist has no owners either. Raising here rather than passing+ # keeps the action from loading a skill another request creates in between.+ if get_skill_by_name_from_db(team, skill_name) is None:+ raise NotFound(f"Skill with name '{skill_name}' not found.")++ self.message = self.NO_OWNERS_MESSAGE if not owners else self.NOT_OWNER_MESSAGE+ return False++class _CommunityPublishThrottle(PersonalApiKeyOrUserRateThrottle):# Publishing opens a pull request in a public repo, so the ceiling is "a handful, by hand", not# the API-shaped hundreds-per-minute of BurstRateThrottle. That one also extends@@ -218,7 +270,11 @@ class LLMSkillViewSet(scope_object = "llm_skill"queryset = LLMSkill.objects.all()serializer_class = LLMSkillSerializer- permission_classes = [AccessControlPermission, CommunityPublishFeatureFlagPermission]+ permission_classes = [+ AccessControlPermission,+ CommunityPublishFeatureFlagPermission,+ CommunityPublishOwnerPermission,+ ]def safely_get_queryset(self, queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:return get_active_skill_queryset(self.team)diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 1f65d84e4ee9..99cba5721bf9 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -53,7 +53,8 @@ class TestLLMSkillAPI(APIBaseTest):category: str = "",created_by: User | None = None,) -> LLMSkill:- return LLMSkill.objects.create(+ owner = created_by or self.user+ skill = LLMSkill.objects.create(team=self.team,name=name,description=description,@@ -66,8 +67,12 @@ class TestLLMSkillAPI(APIBaseTest):allowed_tools=allowed_tools or [],metadata=metadata or {},category=category,- created_by=created_by or self.user,+ created_by=owner,)+ # The create endpoint seeds the creator as owner, so a fixture built straight from the ORM+ # has to as well. Publishing to the community is owner-only.+ set_skill_owners(self.team, name, [owner])+ return skill# --- Create ---@@ -1496,6 +1501,75 @@ class TestSkillAccessControlRBAC(APIBaseTest):)assert update_response.status_code == status.HTTP_200_OK+ @patch(COMMUNITY_FLAG, return_value=True)+ def test_an_object_level_grant_on_one_skill_does_not_allow_publishing_another(self, _mock_flag):+ # AccessControlPermission.has_permission passes anyone holding an object-level grant for the+ # resource, and the name/<slug> actions then load whichever skill the URL names. Ownership is+ # the per-skill claim that stops one grant reaching every skill in the project.+ theirs = LLMSkill.objects.create(+ team=self.team,+ name="theirs",+ description="d",+ body="# x\n",+ version=1,+ is_latest=True,+ created_by=self.user,+ )+ membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=str(theirs.id),+ access_level="editor",+ organization_member=membership,+ )+ set_skill_owners(self.team, theirs.name, [self.member])+ set_skill_owners(self.team, self.skill.name, [self.user])++ response = self.client.post(+ self._url(f"name/{self.skill.name}/publish-community"),+ data={"author_handle": "someone"},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(+ [+ ("a skill nobody owns", "make-fractals", status.HTTP_403_FORBIDDEN),+ ("a skill that does not exist", "no-such-skill", status.HTTP_404_NOT_FOUND),+ ]+ )+ @patch(COMMUNITY_FLAG, return_value=True)+ def test_publishing_without_ownership_is_refused(self, _label, skill_name, expected_status, _mock_flag):+ # Resource-level editor is not enough on its own. An ownerless skill is publishable by nobody,+ # because the alternative fallback to edit access reaches every skill in the project again.+ # An unknown slug still answers 404, the way the other name/<slug> actions answer it.+ self._grant_llm_skill_access("editor")++ response = self.client.post(+ self._url(f"name/{skill_name}/publish-community"),+ data={"author_handle": "someone"},+ format="json",+ )++ assert response.status_code == expected_status++ @patch(COMMUNITY_FLAG, return_value=True)+ @patch("products.skills.backend.api.skills.publish_skill_to_community")+ def test_an_owner_with_editor_access_can_publish(self, mock_publish, _mock_flag):+ mock_publish.return_value = {"pr_url": "https://example.com/pull/1", "pr_number": 1, "branch": "b"}+ self._grant_llm_skill_access("editor")+ set_skill_owners(self.team, self.skill.name, [self.member])++ response = self.client.post(+ self._url(f"name/{self.skill.name}/publish-community"),+ data={"author_handle": "someone"},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED+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