: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(api): make advertised read/write API actions reachable via personal API keys (#63504)
Tom Owersa80e7ec0129c
diff --git a/products/data_warehouse/backend/api/data_warehouse.py b/products/data_warehouse/backend/api/data_warehouse.pyindex 0017fe72168a..8ac42dbba649 100644--- a/products/data_warehouse/backend/api/data_warehouse.py+++ b/products/data_warehouse/backend/api/data_warehouse.py@@ -566,7 +566,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):status=status.HTTP_500_INTERNAL_SERVER_ERROR,)- @action(methods=["GET"], detail=False)+ @action(methods=["GET"], detail=False, required_scopes=["warehouse_view:read", "external_data_source:read"])def data_health_issues(self, request: Request, **kwargs) -> Response:"""Returns failed/disabled data pipeline items for the Pipeline status side panel.diff --git a/products/data_warehouse/backend/api/test/test_data_warehouse.py b/products/data_warehouse/backend/api/test/test_data_warehouse.pyindex 3e4a919f22c3..b78e820d0675 100644--- a/products/data_warehouse/backend/api/test/test_data_warehouse.py+++ b/products/data_warehouse/backend/api/test/test_data_warehouse.py@@ -6,6 +6,9 @@ from unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterized+from rest_framework import status+from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJob@@ -650,3 +653,46 @@ class TestDataWarehouseAPI(APIBaseTest):new_id = second_response.json()["dashboard_id"]self.assertNotEqual(new_id, first_id)self.assertIsNotNone(new_id)+++class TestDataHealthIssuesPersonalAPIKey(APIBaseTest):+ """Verify the data_health_issues action is reachable via personal API keys.++ The custom action is not one of the default read actions, so without an explicit+ `required_scopes` it returned None and rejected all personal API key access with a 403.+ The action now declares `warehouse_view:read` + `external_data_source:read`, matching the+ MCP tool definition.+ """++ CONFIG_AUTO_LOGIN = False++ def _get(self, value: str):+ return self.client.get(+ f"/api/projects/{self.team.id}/data_warehouse/data_health_issues/",+ headers={"authorization": f"Bearer {value}"},+ )++ @parameterized.expand(+ [+ ("both_read_scopes", ["warehouse_view:read", "external_data_source:read"]),+ ("wildcard", ["*"]),+ ]+ )+ def test_allowed_with_required_scopes(self, _name, scopes):+ value = self.create_personal_api_key_with_scopes(scopes)+ response = self._get(value)+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert "results" in response.json()++ @parameterized.expand(+ [+ # Both scopes are required; only one is insufficient.+ ("only_warehouse_view", ["warehouse_view:read"]),+ ("only_external_data_source", ["external_data_source:read"]),+ ("unrelated_scope", ["insight:read"]),+ ]+ )+ def test_rejected_without_all_required_scopes(self, _name, scopes):+ value = self.create_personal_api_key_with_scopes(scopes)+ response = self._get(value)+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()diff --git a/products/feature_flags/backend/api/scheduled_change.py b/products/feature_flags/backend/api/scheduled_change.pyindex 384ac3220e54..b6c9733ea8aa 100644--- a/products/feature_flags/backend/api/scheduled_change.py+++ b/products/feature_flags/backend/api/scheduled_change.py@@ -1,9 +1,12 @@from typing import Any+from django.db.models import Q+from croniter import croniter # type: ignore[import-untyped,unused-ignore]from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import serializers, viewsets+from rest_framework.exceptions import PermissionDeniedfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer@@ -231,6 +234,18 @@ class ScheduledChangeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer_class = ScheduledChangeSerializerqueryset = ScheduledChange.objects.all()+ # Scheduled changes only target feature flags, so gate personal API key / OAuth access+ # on feature_flag scopes. The viewset stays INTERNAL (no implicit scope mapping); these+ # per-action overrides selectively open it to programmatic reads/writes — the same pattern+ # used by OrganizationFeatureFlagViewSet.copy_flags. `*` consent still cannot reach an+ # INTERNAL viewset (see posthog/permissions.py).+ def dangerously_get_required_scopes(self, request: Any, view: Any) -> list[str] | None:+ if self.action in ("list", "retrieve"):+ return ["feature_flag:read"]+ if self.action in ("create", "update", "partial_update", "destroy"):+ return ["feature_flag:write"]+ return None+@extend_schema(parameters=[OpenApiParameter(@@ -261,4 +276,45 @@ class ScheduledChangeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if record_id is not None:queryset = queryset.filter(record_id=record_id)+ # A scheduled change inherits the access control of the flag it targets, but the viewset is+ # INTERNAL so the generic per-object ACL filter never runs. Hide schedules whose target flag+ # the caller cannot read, mirroring FeatureFlagViewSet's list/retrieve filtering. Schedules+ # for non-existent (deleted) flags are left visible so orphans stay cleanable.+ blocked_flag_ids = self._unreadable_feature_flag_ids()+ if blocked_flag_ids:+ queryset = queryset.exclude(+ Q(model_name=ScheduledChange.AllowedModels.FEATURE_FLAG) & Q(record_id__in=blocked_flag_ids)+ )+return queryset++ def _unreadable_feature_flag_ids(self) -> set[str]:+ """IDs (as strings, to match record_id) of flags in this project the caller cannot read."""+ from products.feature_flags.backend.models.feature_flag import FeatureFlag++ project_flags = FeatureFlag.objects.filter(team__project_id=self.project_id)+ readable_ids = self.user_access_control.filter_queryset_by_access_level(+ project_flags, include_all_if_admin=True+ ).values_list("id", flat=True)+ blocked = project_flags.exclude(id__in=readable_ids).values_list("id", flat=True)+ return {str(flag_id) for flag_id in blocked}++ def perform_destroy(self, instance):+ # Deleting a schedule changes which mutations get applied to the target flag, so require the+ # same edit permission as create/update (which enforce it through the serializer).+ self._check_target_edit_permission(instance)+ super().perform_destroy(instance)++ def _check_target_edit_permission(self, instance) -> None:+ if instance.model_name != ScheduledChange.AllowedModels.FEATURE_FLAG or not instance.record_id:+ return+ from products.feature_flags.backend.models.feature_flag import FeatureFlag++ try:+ feature_flag = FeatureFlag.objects.get(id=instance.record_id, team_id=instance.team_id)+ except FeatureFlag.DoesNotExist:+ # Target flag is gone; there is no flag-level permission to enforce and removing the+ # orphaned schedule is harmless.+ return+ if not CanEditFeatureFlag().has_object_permission(self.request, self, feature_flag):+ raise PermissionDenied("You don't have edit permissions for this feature flag")diff --git a/products/feature_flags/backend/api/test/test_scheduled_change.py b/products/feature_flags/backend/api/test/test_scheduled_change.pyindex ea119ea4512a..cb0facbb1298 100644--- a/products/feature_flags/backend/api/test/test_scheduled_change.py+++ b/products/feature_flags/backend/api/test/test_scheduled_change.py@@ -6,6 +6,8 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import serializers, status+from posthog.rbac.user_access_control import UserAccessControl+from products.feature_flags.backend.api.scheduled_change import ScheduledChangeSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -598,3 +600,201 @@ class TestScheduledChange(APIBaseTest):assert scheduled_change.scheduled_at == original_scheduled_at, (f"scheduled_at changed to {scheduled_change.scheduled_at} (status={response.status_code})")++ @parameterized.expand(+ [+ ("denied_without_permission", False, status.HTTP_403_FORBIDDEN, True),+ ("allowed_with_permission", True, status.HTTP_204_NO_CONTENT, False),+ ]+ )+ def test_destroy_respects_feature_flag_edit_permission(+ self, _name, has_permission, expected_status, should_still_exist+ ):+ """DELETE must enforce CanEditFeatureFlag, matching the create/update checks."""+ feature_flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key=f"destroy-flag-{_name}", name="Destroy Flag"+ )+ scheduled_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=feature_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": False},+ scheduled_at="2024-01-15T09:00:00Z",+ created_by=self.user,+ )++ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=has_permission,+ ):+ response = self.client.delete(+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled_change.id}/",+ )++ assert response.status_code == expected_status, getattr(response, "data", response)+ assert ScheduledChange.objects.filter(id=scheduled_change.id).exists() is should_still_exist++ def test_destroy_allowed_for_orphaned_schedule_even_without_edit_permission(self):+ """An orphaned schedule (target flag gone) stays deletable: the orphan branch returns before the+ CanEditFeatureFlag check, so DELETE still succeeds even when that check would otherwise deny."""+ feature_flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="orphan-flag", name="Orphan Flag"+ )+ scheduled_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=feature_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": False},+ scheduled_at="2024-01-15T09:00:00Z",+ created_by=self.user,+ )+ feature_flag.delete()++ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=False,+ ):+ response = self.client.delete(+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled_change.id}/",+ )++ assert response.status_code == status.HTTP_204_NO_CONTENT, getattr(response, "data", response)+ assert not ScheduledChange.objects.filter(id=scheduled_change.id).exists()++ def test_reads_exclude_schedules_for_flags_the_caller_cannot_read(self):+ """List/retrieve must hide schedules whose target flag the caller has no read access to."""+ readable_flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="readable-flag", name="Readable Flag"+ )+ restricted_flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="restricted-flag", name="Restricted Flag"+ )+ readable_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=readable_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": False},+ scheduled_at="2024-01-15T09:00:00Z",+ created_by=self.user,+ )+ restricted_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=restricted_flag.id,+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": False},+ scheduled_at="2024-01-15T09:00:00Z",+ created_by=self.user,+ )++ def fake_filter(_self, queryset, include_all_if_admin=False):+ # Only the feature flag access query is restricted; leave other querysets untouched.+ if queryset.model is FeatureFlag:+ return queryset.exclude(id=restricted_flag.id)+ return queryset++ with patch.object(UserAccessControl, "filter_queryset_by_access_level", new=fake_filter):+ list_response = self.client.get(f"/api/projects/{self.team.id}/scheduled_changes/")+ retrieve_response = self.client.get(+ f"/api/projects/{self.team.id}/scheduled_changes/{restricted_change.id}/"+ )++ assert list_response.status_code == status.HTTP_200_OK, list_response.json()+ listed_ids = {item["id"] for item in list_response.json()["results"]}+ assert readable_change.id in listed_ids+ assert restricted_change.id not in listed_ids+ assert retrieve_response.status_code == status.HTTP_404_NOT_FOUND, retrieve_response.json()+++class TestScheduledChangePersonalAPIKey(APIBaseTest):+ """Verify scheduled change actions are reachable via personal API keys carrying feature_flag scopes.++ The viewset declares `scope_object = "INTERNAL"`, which would normally block all personal API key+ access. The per-action `dangerously_get_required_scopes` override opens reads to `feature_flag:read`+ and writes to `feature_flag:write`, matching the MCP tool definitions, while keeping the viewset+ INTERNAL (so `*` consent still cannot reach it).+ """++ CONFIG_AUTO_LOGIN = False++ def setUp(self):+ super().setUp()+ self.feature_flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="scheduled-flag", name="Scheduled Flag"+ )+ self.scheduled_change = ScheduledChange.objects.create(+ team=self.team,+ record_id=str(self.feature_flag.id),+ model_name="FeatureFlag",+ payload={"operation": "update_status", "value": False},+ scheduled_at=datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),+ created_by=self.user,+ )++ def _headers(self, value: str) -> dict:+ return {"authorization": f"Bearer {value}"}++ def test_list_allowed_with_read_scope(self):+ value = self.create_personal_api_key_with_scopes(["feature_flag:read"])+ response = self.client.get(f"/api/projects/{self.team.id}/scheduled_changes/", headers=self._headers(value))+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert any(item["id"] == self.scheduled_change.id for item in response.json()["results"])++ def test_retrieve_allowed_with_read_scope(self):+ value = self.create_personal_api_key_with_scopes(["feature_flag:read"])+ response = self.client.get(+ f"/api/projects/{self.team.id}/scheduled_changes/{self.scheduled_change.id}/",+ headers=self._headers(value),+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] == self.scheduled_change.id++ def test_create_allowed_with_write_scope(self):+ value = self.create_personal_api_key_with_scopes(["feature_flag:write"])+ response = self.client.post(+ f"/api/projects/{self.team.id}/scheduled_changes/",+ data={+ "record_id": str(self.feature_flag.id),+ "model_name": "FeatureFlag",+ "payload": {"operation": "update_status", "value": True},+ "scheduled_at": "2024-02-01T12:00:00Z",+ },+ headers=self._headers(value),+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ # Read scope cannot satisfy a write action.+ ("read_scope_on_write", ["feature_flag:read"]),+ # `*` consent intentionally does not satisfy an INTERNAL viewset even with required_scopes.+ ("wildcard_on_internal_viewset", ["*"]),+ # An unrelated scope is insufficient.+ ("unrelated_scope", ["insight:read"]),+ ]+ )+ def test_create_rejected_without_write_scope(self, _name, scopes):+ value = self.create_personal_api_key_with_scopes(scopes)+ response = self.client.post(+ f"/api/projects/{self.team.id}/scheduled_changes/",+ data={+ "record_id": str(self.feature_flag.id),+ "model_name": "FeatureFlag",+ "payload": {"operation": "update_status", "value": True},+ "scheduled_at": "2024-02-01T12:00:00Z",+ },+ headers=self._headers(value),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()++ @parameterized.expand(+ [+ # `*` consent intentionally does not satisfy an INTERNAL viewset even with required_scopes.+ ("wildcard_on_internal_viewset", ["*"]),+ # An unrelated scope is insufficient.+ ("unrelated_scope", ["insight:read"]),+ ]+ )+ def test_list_rejected_without_read_scope(self, _name, scopes):+ value = self.create_personal_api_key_with_scopes(scopes)+ response = self.client.get(f"/api/projects/{self.team.id}/scheduled_changes/", headers=self._headers(value))+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()diff --git a/products/logs/backend/alerts_api.py b/products/logs/backend/alerts_api.pyindex 2c0e433ac5be..e498f0c9e300 100644--- a/products/logs/backend/alerts_api.py+++ b/products/logs/backend/alerts_api.py@@ -861,7 +861,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):responses={201: LogsAlertDestinationResponseSerializer},description="Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.",)- @action(detail=True, methods=["POST"], url_path="destinations")+ @action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["logs:write"])def create_destination(self, request: Request, *args: object, **kwargs: object) -> Response:alert = self.get_object()serializer = LogsAlertCreateDestinationSerializer(data=request.data)@@ -884,7 +884,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):responses={204: None},description="Delete a notification destination by deleting its HogFunction group atomically.",)- @action(detail=True, methods=["POST"], url_path="destinations/delete")+ @action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["logs:write"])def delete_destination(self, request: Request, *args: object, **kwargs: object) -> Response:alert = self.get_object()serializer = LogsAlertDeleteDestinationSerializer(data=request.data)@@ -948,7 +948,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"and they carry no forensic value. Optional `?kind=...` narrows to a single kind."),)- @action(detail=True, methods=["GET"], url_path="events")+ @action(detail=True, methods=["GET"], url_path="events", required_scopes=["logs:read"])def events(self, request: Request, *args: object, **kwargs: object) -> Response:alert = self.get_object()queryset = (@@ -979,7 +979,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):responses={200: LogsAlertConfigurationSerializer},description="Reset a broken alert. Clears the consecutive-failure counter and schedules an immediate recheck.",)- @action(detail=True, methods=["POST"], url_path="reset")+ @action(detail=True, methods=["POST"], url_path="reset", required_scopes=["logs:write"])def reset(self, request: Request, *args: object, **kwargs: object) -> Response:alert = self.get_object()previous_failures = alert.consecutive_failures@@ -1030,7 +1030,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):description="Simulate a logs alert on historical data using the full state machine. ""Read-only — no alert check records are created.",)- @action(detail=False, methods=["POST"], url_path="simulate")+ @action(detail=False, methods=["POST"], url_path="simulate", required_scopes=["logs:read"])def simulate(self, request: Request, *args: object, **kwargs: object) -> Response:serializer = LogsAlertSimulateRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 97ea2f17d1f4..1df43452190b 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -1963,3 +1963,141 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):assert eval_events == sim_events, f"cadence={cadence}: eval={eval_events}\nsim={sim_events}"assert any(k == "fire" for _, k in eval_events)assert any(k == "resolve" for _, k in eval_events)+++class TestLogsAlertAPIPersonalAPIKeyScopes(APIBaseTest):+ CONFIG_AUTO_LOGIN = False++ def setUp(self):+ super().setUp()+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ self._ff_patcher.start()+ self.addCleanup(self._ff_patcher.stop)+ self.base_url = f"/api/projects/{self.team.pk}/logs/alerts/"++ def _auth(self, value: str) -> dict:+ return {"HTTP_AUTHORIZATION": f"Bearer {value}"}++ # --- events action (GET detail, requires logs:read) ---++ @parameterized.expand(+ [+ ("logs_read", ["logs:read"]),+ ("logs_write", ["logs:write"]),+ ]+ )+ def test_events_action_allowed(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ # Target a non-existent UUID so the action body doesn't run; a 404 proves the scope+ # gate was passed cleanly (403 = gate rejected the key; a 401/500 would also slip past+ # a bare `!= 403` check, so assert the exact code).+ url = f"{self.base_url}{uuid4()}/events/"+ response = self.client.get(url, **self._auth(key))+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()++ @parameterized.expand(+ [+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_events_action_rejected_without_logs_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}{uuid4()}/events/"+ response = self.client.get(url, **self._auth(key))+ assert response.status_code == 403, response.json()++ # --- simulate action (POST non-detail, requires logs:read) ---++ @parameterized.expand(+ [+ ("logs_read", ["logs:read"]),+ ("logs_write", ["logs:write"]),+ ]+ )+ def test_simulate_action_allowed(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}simulate/"+ # Empty body triggers 400 from serializer validation — proves the scope gate passed+ # (asserting the exact code rules out a 401/500 sneaking past a bare `!= 403`).+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ @parameterized.expand(+ [+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_simulate_action_rejected_without_logs_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}simulate/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == 403, response.json()++ # --- create_destination action (POST detail, requires logs:write) ---++ def test_create_destination_allowed_with_logs_write_scope(self):+ key = self.create_personal_api_key_with_scopes(["logs:write"])+ # Detail action against a non-existent UUID: get_object 404s before the body runs,+ # proving the scope gate passed (a bare `!= 403` would also pass on a 401/500).+ url = f"{self.base_url}{uuid4()}/destinations/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()++ @parameterized.expand(+ [+ ("read_scope_cannot_satisfy_write", ["logs:read"]),+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_create_destination_rejected_without_logs_write_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}{uuid4()}/destinations/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == 403, response.json()++ # --- delete_destination action (POST detail, requires logs:write) ---++ def test_delete_destination_allowed_with_logs_write_scope(self):+ key = self.create_personal_api_key_with_scopes(["logs:write"])+ url = f"{self.base_url}{uuid4()}/destinations/delete/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()++ @parameterized.expand(+ [+ ("read_scope_cannot_satisfy_write", ["logs:read"]),+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_delete_destination_rejected_without_logs_write_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}{uuid4()}/destinations/delete/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == 403, response.json()++ # --- reset action (POST detail, requires logs:write) ---++ def test_reset_allowed_with_logs_write_scope(self):+ key = self.create_personal_api_key_with_scopes(["logs:write"])+ # Detail action against a non-existent UUID: get_object 404s before the body runs,+ # proving the scope gate passed (a bare `!= 403` would also pass on a 401/500).+ url = f"{self.base_url}{uuid4()}/reset/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()++ @parameterized.expand(+ [+ ("read_scope_cannot_satisfy_write", ["logs:read"]),+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_reset_rejected_without_logs_write_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"{self.base_url}{uuid4()}/reset/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == 403, response.json()diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex dd0df9208a41..ee176f2d6b1a 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -384,6 +384,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"add_snapshots","recompute","mark_tolerated",+ "finalize",]scope_object_read_actions = ["list", "retrieve", "snapshots", "counts", "snapshot_history", "tolerated_hashes"]serializer_class = RunSerializerdiff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.pyindex 442654484f90..d23dd9a5eeb3 100644--- a/products/visual_review/backend/tests/test_presentation.py+++ b/products/visual_review/backend/tests/test_presentation.py@@ -503,3 +503,35 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):response = self.client.get(self._history_url("Components-Button--default v2.0"))self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["count"], 0)+++class TestRunFinalizePersonalAPIKeyScopes(VisualReviewTeamScopedTestMixin, APIBaseTest):+ databases = PRODUCT_DATABASES+ CONFIG_AUTO_LOGIN = False++ def setUp(self):+ super().setUp()+ self.vr_project = api.create_repo(team_id=self.team.id, repo_external_id=77777, repo_full_name="org/scope-test")++ def _auth(self, value: str) -> dict:+ return {"HTTP_AUTHORIZATION": f"Bearer {value}"}++ def test_finalize_allowed_with_visual_review_write_scope(self):+ key = self.create_personal_api_key_with_scopes(["visual_review:write"])+ # Target a non-existent UUID; a 404 proves the scope gate was passed.+ url = f"/api/projects/{self.team.id}/visual_review/runs/{uuid4()}/finalize/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code != 403, response.json()++ @parameterized.expand(+ [+ ("read_scope_cannot_satisfy_write", ["visual_review:read"]),+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_finalize_rejected_without_visual_review_write_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"/api/projects/{self.team.id}/visual_review/runs/{uuid4()}/finalize/"+ response = self.client.post(url, {}, format="json", **self._auth(key))+ assert response.status_code == 403, response.json()diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex c608bcfef894..50fc67025fb1 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -1067,7 +1067,7 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gdescription="Re-run screenshot generation for a saved heatmap of type 'screenshot'. Clears existing renders ""and re-renders at every target width; status returns to 'processing'.",)- @action(methods=["POST"], detail=True)+ @action(methods=["POST"], detail=True, required_scopes=["heatmap:write"])def regenerate(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()if obj.type != SavedHeatmap.Type.SCREENSHOT:diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.pyindex 9ab2dd0acebb..96a7bf741b34 100644--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py@@ -200,3 +200,30 @@ class TestHeatmapsAPI(APIBaseTest):r = self.client.post(f"/api/environments/{self.team.id}/saved/{saved.short_id}/regenerate/")self.assertEqual(r.status_code, 400)+++class TestSavedHeatmapRegeneratePersonalAPIKeyScopes(APIBaseTest):+ CONFIG_AUTO_LOGIN = False++ def _auth(self, value: str) -> dict:+ return {"HTTP_AUTHORIZATION": f"Bearer {value}"}++ def test_regenerate_allowed_with_heatmap_write_scope(self):+ key = self.create_personal_api_key_with_scopes(["heatmap:write"])+ # Use a non-existent short_id; a 404 proves the scope gate was passed.+ url = f"/api/environments/{self.team.id}/saved/nonexistent-short-id/regenerate/"+ r = self.client.post(url, **self._auth(key))+ assert r.status_code != 403, r.json()++ @parameterized.expand(+ [+ ("read_scope_cannot_satisfy_write", ["heatmap:read"]),+ ("unrelated_scope", ["insight:read"]),+ ("no_scopes", []),+ ]+ )+ def test_regenerate_rejected_without_heatmap_write_scope(self, _name: str, scopes: list[str]):+ key = self.create_personal_api_key_with_scopes(scopes)+ url = f"/api/environments/{self.team.id}/saved/nonexistent-short-id/regenerate/"+ r = self.client.post(url, **self._auth(key))+ assert r.status_code == 403, r.json()