: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
chore(replay-vision): reach signals scout access and charts through its facade (#125832)
Julian Bez8093d4cf87a9
diff --git a/products/replay_vision/backend/api/scanner_scouts.py b/products/replay_vision/backend/api/scanner_scouts.pyindex 19754f553f0f..95fb12d42b96 100644--- a/products/replay_vision/backend/api/scanner_scouts.py+++ b/products/replay_vision/backend/api/scanner_scouts.py@@ -10,13 +10,14 @@ from posthog.event_usage import report_user_actionfrom posthog.models import Userfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.replay_vision.backend.api.scout_permissions import ScoutDataAccessPermissionfrom products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.scanner_access import scanner_for_recording_derived_readfrom products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCTfrom products.replay_vision.backend.variant_analysis import VARIANT_ANALYSIS_TAG, variant_analysis_configfrom products.signals.backend.facade import api as signals_facadefrom products.signals.backend.scout_harness.serializers import SignalScoutConfigSerializer, SignalScoutCreateSerializer-from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission, scout_config_context+from products.signals.backend.scout_harness.views import scout_config_contextclass ScannerScoutCreateSerializer(SignalScoutCreateSerializer):@@ -68,7 +69,7 @@ class ScannerScoutViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# environment would otherwise read and write another team's rows. Signals' own scout endpoints# carry this for the same reason.# Appended to the standard stack by `TeamAndOrgViewSetMixin.get_permissions`.- permission_classes = [ScoutCanonicalTeamAccessPermission]+ permission_classes = [ScoutDataAccessPermission]scope_object = "replay_scanner"# Every object this touches: the scanner and the recordings behind it, the skill a scout is,# and the scout config itself.diff --git a/products/replay_vision/backend/api/scout_permissions.py b/products/replay_vision/backend/api/scout_permissions.pynew file mode 100644index 000000000000..31f9aad335fb--- /dev/null+++ b/products/replay_vision/backend/api/scout_permissions.py@@ -0,0 +1,31 @@+from typing import cast++from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.views import APIView++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.permissions import get_authenticator_user_credential++from products.signals.backend.facade.scout_access import CANONICAL_TEAM_ACCESS_DENIED_MESSAGE, has_canonical_team_access+++class ScoutDataAccessPermission(BasePermission):+ """Authorize requests that read or write scout data against the project that owns that data.++ Scout rows canonicalize to the parent team on save. A caller authorized only against a child+ environment would otherwise read and write another team's rows. Signals makes the same check+ on its own scout endpoints.+ """++ message = CANONICAL_TEAM_ACCESS_DENIED_MESSAGE++ def has_permission(self, request: Request, view: APIView) -> bool:+ team_view = cast(TeamAndOrgViewSetMixin, view)+ if not request.user.is_authenticated:+ # Unreachable while `IsAuthenticated` runs ahead of this class, but deny rather than+ # allow, so this class can never be the reason an anonymous request gets through.+ return False+ credential = get_authenticator_user_credential(request.successful_authenticator)+ scoped_team_ids = credential.scoped_teams if credential is not None else None+ return has_canonical_team_access(team_view.team, team_view.user_permissions, scoped_team_ids)diff --git a/products/replay_vision/backend/api/scout_reports.py b/products/replay_vision/backend/api/scout_reports.pyindex 924b862d5a7b..326e1178eba4 100644--- a/products/replay_vision/backend/api/scout_reports.py+++ b/products/replay_vision/backend/api/scout_reports.py@@ -1,4 +1,6 @@-from drf_spectacular.utils import extend_schema+from typing import Any++from drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import serializers, viewsetsfrom rest_framework.exceptions import NotFoundfrom rest_framework.request import Request@@ -6,14 +8,23 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin+from products.replay_vision.backend.api.scout_permissions import ScoutDataAccessPermissionfrom products.replay_vision.backend.scanner_access import scanner_for_recording_derived_readfrom products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT-from products.signals.backend.facade import api as signals_facade-from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission+from products.signals.backend.facade import (+ api as signals_facade,+ scout_reports as signals_scout_reports,+)+++# Points at the Signals chart component rather than redeclaring it: two components with this name+# generate an incorrect schema, and the charts here are the same shape the inbox renders.+@extend_schema_field({"type": "array", "items": signals_scout_reports.REPORT_CHART_SCHEMA})+class ReportChartsField(serializers.Field):+ """A report's charts, rendered by Signals."""-# Reused rather than redeclared: two components with this name generate an incorrect schema, and-# the charts here are the same shape the inbox renders.-from products.signals.backend.serializers import ReportChartSerializer+ def to_representation(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return signals_scout_reports.render_report_charts(value)class ScoutReportSerializer(serializers.Serializer):@@ -27,8 +38,7 @@ class ScoutReportSerializer(serializers.Serializer):)title = serializers.CharField(help_text="The report's title. Empty when the scout left it unset.")summary = serializers.CharField(help_text="The report body, as markdown. Empty when the scout left it unset.")- charts = ReportChartSerializer(- many=True,+ charts = ReportChartsField(help_text=("Charts the scout attached. The summary places one inline with a ""`[label](chart:<chart_id>)` link; any it does not place render after the body."@@ -47,7 +57,7 @@ class ScannerScoutReportViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# The reports these scouts filed are canonical-team rows, so access is checked against that# team and not just the environment in the URL.# Appended to the standard stack by `TeamAndOrgViewSetMixin.get_permissions`.- permission_classes = [ScoutCanonicalTeamAccessPermission]+ permission_classes = [ScoutDataAccessPermission]scope_object = "replay_scanner"# `task` is the scope object Signals gates its own report reads on, so a token that cannot read# reports there cannot read them through a scanner either.diff --git a/products/replay_vision/backend/api/variants.py b/products/replay_vision/backend/api/variants.pyindex fce31ac0ea02..481d3f5e65cf 100644--- a/products/replay_vision/backend/api/variants.py+++ b/products/replay_vision/backend/api/variants.py@@ -10,10 +10,10 @@ from posthog.api.documentation import PostHogAutoSchemafrom posthog.api.routing import TeamAndOrgViewSetMixinfrom products.replay_vision.backend.api.observations import ReplayObservationSerializer+from products.replay_vision.backend.api.scout_permissions import ScoutDataAccessPermissionfrom products.replay_vision.backend.experiment_variants import experiment_variants_readoutfrom products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.scanner_access import scanner_for_recording_derived_read-from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermissionclass VariantsExperimentSerializer(serializers.Serializer):@@ -152,7 +152,7 @@ class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# The variant analysis is read from the scout's canonical-team records, so access is checked# against that team and not just the environment in the URL.# Appended to the standard stack by `TeamAndOrgViewSetMixin.get_permissions`.- permission_classes = [ScoutCanonicalTeamAccessPermission]+ permission_classes = [ScoutDataAccessPermission]schema = _ReadoutSchema()scope_object = "replay_scanner"required_scopes = ["replay_scanner:read", "session_recording:read"]diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex d164f5a4965f..ada4173c99c4 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -366,7 +366,7 @@ class CompareReplayVisionVariantsTool(ReplayVisionGatesMixin, MaxTool):]analysis = readout.analysis# The scout's records live on the parent project. The variants endpoint checks the caller's- # parent access and credential scope with ScoutCanonicalTeamAccessPermission, and a tool sees+ # parent access and credential scope with ScoutDataAccessPermission, and a tool sees# no credential, so a child environment gets its analysis only from the Variants tab.in_child_environment = self._team.parent_team_id is not None and self._team.parent_team_id != self._team.idif analysis is not None and in_child_environment:diff --git a/products/replay_vision/backend/scout_source.py b/products/replay_vision/backend/scout_source.pyindex 85e932fb009c..9627bfb07af6 100644--- a/products/replay_vision/backend/scout_source.py+++ b/products/replay_vision/backend/scout_source.py@@ -1,4 +1,4 @@-from products.signals.backend.enums import SignalSourceProduct+from products.signals.backend.facade.taxonomy import SignalSourceProduct# pinned: what a scout's config records as its owner. Signals stores it as `(source_product,# source_id)`, where source_id is the scanner's id, and that pair is what ties a scout back to thediff --git a/products/signals/backend/facade/scout_access.py b/products/signals/backend/facade/scout_access.pynew file mode 100644index 000000000000..095e1d090532--- /dev/null+++ b/products/signals/backend/facade/scout_access.py@@ -0,0 +1,28 @@+"""Who may read and write scout data, for views in signals and in other products."""++from collections.abc import Sequence+from typing import TYPE_CHECKING++from posthog.models import Team++if TYPE_CHECKING:+ from posthog.rbac.user_permissions import UserPermissions++CANONICAL_TEAM_ACCESS_DENIED_MESSAGE = "You don't have access to the project that owns this data."+++def has_canonical_team_access(+ team: Team, user_permissions: "UserPermissions", scoped_team_ids: Sequence[int] | None+) -> bool:+ """Whether an authenticated caller may act on scout data for `team`.++ Scout rows canonicalize to the parent team on save. So for a child environment the caller needs+ membership of the parent team, and a credential scoped to some teams must include the parent.+ `scoped_team_ids` is None or empty when the credential has no team restriction.+ """+ if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:+ return True+ if scoped_team_ids and team.parent_team_id not in scoped_team_ids:+ return False+ level = user_permissions.team(team.parent_team).effective_membership_level+ return level is not Nonediff --git a/products/signals/backend/facade/scout_reports.py b/products/signals/backend/facade/scout_reports.pynew file mode 100644index 000000000000..ce6e6e3bc602--- /dev/null+++ b/products/signals/backend/facade/scout_reports.py@@ -0,0 +1,13 @@+"""Report charts for products that show the reports their scouts filed."""++from typing import Any++from products.signals.backend import report_chart_rendering++# Registered by the Signals report endpoints. A second serializer with this component name breaks the schema.+REPORT_CHART_SCHEMA = {"$ref": "#/components/schemas/ReportChart"}+++def render_report_charts(charts: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Render the stored charts of a `ScoutReport` in the `REPORT_CHART_SCHEMA` shape."""+ return report_chart_rendering.render_report_charts(charts)diff --git a/products/signals/backend/facade/taxonomy.py b/products/signals/backend/facade/taxonomy.pynew file mode 100644index 000000000000..2dce2fe5215b--- /dev/null+++ b/products/signals/backend/facade/taxonomy.py@@ -0,0 +1,13 @@+"""Signal taxonomy and value types that other products pass to and receive from signals."""++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.contracts import SignalRemediation+from products.signals.backend.enums import ReportPriority, SignalSourceProduct, SignalSourceType++__all__ = [+ "ArtefactAttribution",+ "ReportPriority",+ "SignalRemediation",+ "SignalSourceProduct",+ "SignalSourceType",+]diff --git a/products/signals/backend/presentation/scout_permissions.py b/products/signals/backend/presentation/scout_permissions.pyindex a6375ad2c4db..f82f7ff46154 100644--- a/products/signals/backend/presentation/scout_permissions.py+++ b/products/signals/backend/presentation/scout_permissions.py@@ -5,13 +5,15 @@ from rest_framework.request import Requestfrom rest_framework.views import APIViewfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.permissions import get_authenticator_user_credential++from products.signals.backend.facade.scout_access import CANONICAL_TEAM_ACCESS_DENIED_MESSAGE, has_canonical_team_accessclass ScoutCanonicalTeamAccessPermission(BasePermission):"""Authorize requests against the project that owns the scout data."""- message = "You don't have access to the project that owns this data."+ message = CANONICAL_TEAM_ACCESS_DENIED_MESSAGEdef has_permission(self, request: Request, view: APIView) -> bool:team_view = cast(TeamAndOrgViewSetMixin, view)@@ -19,16 +21,6 @@ class ScoutCanonicalTeamAccessPermission(BasePermission):# Unreachable while `IsAuthenticated` runs ahead of this class, but deny rather than# allow, so this class can never be the reason an anonymous request gets through.return False- team = team_view.team- if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:- return True- authenticator = request.successful_authenticator- scoped_teams = None- if isinstance(authenticator, OAuthAccessTokenAuthentication):- scoped_teams = authenticator.access_token.scoped_teams- elif isinstance(authenticator, PersonalAPIKeyAuthentication):- scoped_teams = authenticator.personal_api_key.scoped_teams- if scoped_teams and team.parent_team_id not in scoped_teams:- return False- level = team_view.user_permissions.team(team.parent_team).effective_membership_level- return level is not None+ credential = get_authenticator_user_credential(request.successful_authenticator)+ scoped_team_ids = credential.scoped_teams if credential is not None else None+ return has_canonical_team_access(team_view.team, team_view.user_permissions, scoped_team_ids)diff --git a/products/signals/backend/report_chart_rendering.py b/products/signals/backend/report_chart_rendering.pynew file mode 100644index 000000000000..8cd2b3b3c454--- /dev/null+++ b/products/signals/backend/report_chart_rendering.py@@ -0,0 +1,8 @@+from typing import Any++from products.signals.backend.serializers import ReportChartSerializer+++def render_report_charts(charts: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Render a report's stored charts as the Signals report endpoints do."""+ return list(ReportChartSerializer(charts, many=True).data)