: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(signals): share the scout creation check between endpoint and facade (#106430)
Rafael Audibert726d78d960c6
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex c24d617a9e68..c5f4b7253a31 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -16,10 +16,11 @@ from temporalio.common import WorkflowIDReusePolicyfrom posthog.dataclasses import frozenfrom posthog.event_usage import groupsfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connect+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.signals.backend.artefact_schemas import (# Re-exported so the Slack mention handler can label the task it starts from a report's# notification thread without naming the relationship vocabulary itself.@@ -29,6 +30,7 @@ from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProductfrom products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfigfrom products.signals.backend.report_actionability_repair import RepairedBatch, repair_latest_actionability+from products.signals.backend.scout_harness.create_access import can_create_scoutfrom products.signals.backend.scout_harness.run_gates import (# Re-exported so the workflows endpoint can branch on why a fire was refused without reaching# into the scout harness. Every decision behind them stays Signals-side.@@ -1171,3 +1173,29 @@ def repair_report_actionability_cache(artefact write, so this only repairs rows that drifted."""return repair_latest_actionability(team_id=team_id, batch_size=batch_size, after=after)+++def scout_creation_available(*, team_id: int, user_id: int) -> bool:+ """Whether to offer the user scout creation on the team's project.++ The create endpoint's permission checks run on the requested team: project access and editor+ access to skills. Two more checks run on the canonical project: it runs scouts (enrollment in the+ `signals-scout` flag payload), and the user passes the endpoint's own check (editor access to skills).+ """+ from products.signals.backend.scout_harness.team_limits import (+ team_is_enrolled, # noqa: PLC0415 — keeps the flag-reading harness module off the facade import path+ )++ team = Team.objects.select_related("parent_team").filter(id=team_id).first()+ user = User.objects.filter(id=user_id, is_active=True).first()+ if team is None or user is None:+ return False+ requested_team_access = UserAccessControl(user=user, team=team)+ if not requested_team_access.has_project_access:+ return False+ if not requested_team_access.check_access_level_for_resource("llm_skill", "editor"):+ return False+ canonical_team = team.parent_team or team+ if not team_is_enrolled(canonical_team.id):+ return False+ return can_create_scout(user, canonical_team)diff --git a/products/signals/backend/scout_harness/create_access.py b/products/signals/backend/scout_harness/create_access.pynew file mode 100644index 000000000000..30a2f113ab75--- /dev/null+++ b/products/signals/backend/scout_harness/create_access.py@@ -0,0 +1,9 @@+from posthog.models import Team, User++from products.access_control.backend.facade.user_access_control import UserAccessControl+++def can_create_scout(user: User, canonical_team: Team) -> bool:+ """Whether ``user`` may create a scout on ``canonical_team``: editor access to skills, because the+ skill body is the prompt the scout agent runs. Access to the project itself is a separate check."""+ return UserAccessControl(user=user, team=canonical_team).check_access_level_for_resource("llm_skill", "editor")diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex 411efdef7c27..13973f1117a6 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -560,6 +560,11 @@ def _resolve_enrolled(canonical_team_id: int, enrollment: Enrollment) -> bool:return _is_team_enrolled(canonical_team_id, enrollment.explicit)+def team_is_enrolled(canonical_team_id: int) -> bool:+ """Whether a canonical project runs scouts, as the `signals-scout` flag payload says right now."""+ return _resolve_enrolled(canonical_team_id, _parse_enrollment(_read_flag_payload()))++@dataclass(frozen=True)class ScoutTeamLimits:"""A team's effective scout run caps + current usage, all resolved the way dispatch enforces."""diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex aa91f998b790..c108cf462db6 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -74,6 +74,7 @@ from products.signals.backend.pipeline_identity import pipeline_writer_identityfrom products.signals.backend.report_charts import ChartSizefrom products.signals.backend.report_generation.resolve_reviewers import MAX_PROJECT_MEMBERS, list_project_membersfrom products.signals.backend.scout_harness.config_registry import enabled_scout_count, ensure_scout_category+from products.signals.backend.scout_harness.create_access import can_create_scoutfrom products.signals.backend.scout_harness.deprecation import deprecation_metadata_offrom products.signals.backend.scout_harness.fleet_sync import materialize_scout_fleetfrom products.signals.backend.scout_harness.lazy_seed import (@@ -2933,8 +2934,7 @@ class SignalScoutViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):pagination_class = Nonedef _assert_can_create_scout(self, *, user: User, canonical_team: Team) -> None:- access = UserAccessControl(user=user, team=canonical_team)- if not access.check_access_level_for_resource("llm_skill", "editor"):+ if not can_create_scout(user, canonical_team):raise exceptions.PermissionDenied("Creating a scout requires editor access to skills.")@validated_request(diff --git a/products/signals/backend/test/test_facade_scout_creation_available.py b/products/signals/backend/test/test_facade_scout_creation_available.pynew file mode 100644index 000000000000..1a99c6cd2bdb--- /dev/null+++ b/products/signals/backend/test/test_facade_scout_creation_available.py@@ -0,0 +1,50 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models import Team++from products.signals.backend.facade.api import scout_creation_available++TEAM_LIMITS = "products.signals.backend.scout_harness.team_limits"+CREATE_ACCESS = "products.signals.backend.scout_harness.create_access"+FACADE = "products.signals.backend.facade.api"+++class TestScoutCreationAvailable(BaseTest):+ @parameterized.expand(+ [+ ("enrolled_team", lambda team_id: {"guaranteed_team_ids": [team_id]}, False, True),+ ("wildcard", lambda _team_id: {"guaranteed_team_ids": ["*"]}, False, True),+ ("skipped_team", lambda team_id: {"guaranteed_team_ids": ["*"], "skip_team_ids": [team_id]}, False, False),+ ("other_team_only", lambda team_id: {"guaranteed_team_ids": [team_id + 1000]}, False, False),+ ("child_environment_of_enrolled_project", lambda team_id: {"guaranteed_team_ids": [team_id]}, True, True),+ ]+ )+ def test_follows_the_scout_enrollment_payload(self, _name, payload_for, on_child_environment: bool, expected: bool):+ team_id = self.team.id+ if on_child_environment:+ team_id = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment").id+ with patch(f"{TEAM_LIMITS}._read_flag_payload", return_value=payload_for(self.team.id)):+ assert scout_creation_available(team_id=team_id, user_id=self.user.id) is expected++ def test_requires_skill_editor_access_like_the_create_endpoint(self):+ with (+ patch(f"{TEAM_LIMITS}._read_flag_payload", return_value={"guaranteed_team_ids": ["*"]}),+ patch(f"{CREATE_ACCESS}.UserAccessControl") as user_access_control,+ ):+ user_access_control.return_value.check_access_level_for_resource.return_value = False+ assert scout_creation_available(team_id=self.team.id, user_id=self.user.id) is False++ @parameterized.expand([("project_access", "has_project_access"), ("skill_editor_access", "skill_editor")])+ def test_requires_the_create_endpoint_access_on_the_requested_team(self, _name: str, denied: str):+ with (+ patch(f"{TEAM_LIMITS}._read_flag_payload", return_value={"guaranteed_team_ids": ["*"]}),+ patch(f"{FACADE}.UserAccessControl") as user_access_control,+ ):+ access = user_access_control.return_value+ access.has_project_access = denied != "has_project_access"+ access.check_access_level_for_resource.return_value = denied != "skill_editor"+ assert scout_creation_available(team_id=self.team.id, user_id=self.user.id) is False+ assert user_access_control.call_args.kwargs["team"].id == self.team.iddiff --git a/products/signals/backend/test/test_scout_create_api.py b/products/signals/backend/test/test_scout_create_api.pyindex 361f69434889..0678ab42e218 100644--- a/products/signals/backend/test/test_scout_create_api.py+++ b/products/signals/backend/test/test_scout_create_api.py@@ -315,7 +315,7 @@ class TestSignalScoutCreateAPI(APIBaseTest):parent_team=self.team,name="Child environment",)- with patch("products.signals.backend.scout_harness.views.UserAccessControl") as user_access_control:+ with patch("products.signals.backend.scout_harness.create_access.UserAccessControl") as user_access_control:user_access_control.return_value.check_access_level_for_resource.return_value = Falseresponse = self.client.post(f"/api/projects/{environment.id}/signals/scout/",