: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(subscriptions): enforce object access control on subscription targets (#81674)
Vasco de Krijger4c0ceeb7d825
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex a14c2bec22fa..df27be27911f 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -5,8 +5,9 @@ from typing import Any, ClassVar, Optionalfrom django.conf import settingsfrom django.core.cache import cache-from django.db.models import QuerySet+from django.db.models import Manager, Q, QuerySetfrom django.http import HttpRequest, JsonResponse+from django.shortcuts import get_object_or_404import jwtimport posthoganalytics@@ -32,12 +33,15 @@ from posthog.constants import (SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY,SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY,)+from posthog.dataclasses import frozenfrom posthog.event_usage import get_request_analytics_properties, groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integrationfrom posthog.rate_limit import SubscriptionTestDeliveryThrottle+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.resource_limits import LimitKey, check_count_limit, get_organization_limit+from posthog.scopes import APIScopeObjectfrom posthog.slo.context import SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connect@@ -96,6 +100,58 @@ def _invalidate_summary_quota_cache(organization_id) -> None:cache.delete(_summary_quota_cache_key(organization_id))+@frozen+class _TargetLookups:+ insight: str+ dashboard: str+ exported_insights: str+ no_selection: str+ insights: Manager+ dashboards: Manager+ tiles: Manager+++_SUBSCRIPTION_TARGETS = _TargetLookups(+ insight="insight_id__in",+ dashboard="dashboard_id__in",+ exported_insights="dashboard_export_insights__id__in",+ no_selection="dashboard_export_insights__isnull",+ insights=Insight.objects,+ dashboards=Dashboard.objects,+ tiles=DashboardTile.objects,+)++# A delivery keeps the results it rendered, so a soft-deleted target still restricts it.+_DELIVERY_TARGETS = _TargetLookups(+ insight="subscription__insight_id__in",+ dashboard="subscription__dashboard_id__in",+ exported_insights="subscription__dashboard_export_insights__id__in",+ no_selection="subscription__dashboard_export_insights__isnull",+ insights=Insight.objects_including_soft_deleted,+ dashboards=Dashboard.objects_including_soft_deleted,+ tiles=DashboardTile.objects_including_soft_deleted,+)+++def _require_viewer_access(user_access_control: UserAccessControl, obj: Insight | Dashboard, field: str) -> None:+ if not user_access_control.check_access_level_for_object(obj, "viewer"):+ raise ValidationError(+ {field: [f"Viewer access to this {field} is required. Ask an admin to grant you access."]}+ )+++def _viewable_queryset(+ user_access_control: UserAccessControl, queryset: QuerySet, resource: APIScopeObject+) -> QuerySet:+ viewable = user_access_control.filter_queryset_by_access_level(+ queryset, include_all_if_admin=True, resource=resource+ )+ if user_access_control.is_organization_admin or user_access_control.has_resource_access(resource):+ return viewable+ allowed_ids = user_access_control.allowlisted_resource_ids_by_scope.get(resource, frozenset())+ return viewable.filter(Q(id__in=allowed_ids) | Q(created_by=user_access_control.user))++def _ai_create_gate_reason(organization, distinct_id: str) -> Optional[str]:if not settings.DEBUG and not is_cloud():return "AI subscriptions are only available in PostHog Cloud."@@ -418,6 +474,13 @@ class SubscriptionSerializer(serializers.ModelSerializer):if attrs.get("insight") and attrs["insight"].team.id != self.context["team_id"]:raise ValidationError({"insight": ["This insight does not belong to your team."]})+ user_access_control = self.context["view"].user_access_control+ turning_off = attrs.get("deleted") is True or attrs.get("enabled") is False+ for field in ("dashboard", "insight"):+ target = attrs.get(field) or getattr(existing, field, None)+ if target is not None and not (target.deleted and turning_off):+ _require_viewer_access(user_access_control, target, field)+if existing is None:# Create: a subscription must export an insight, a dashboard, or an AI prompt.if not attrs.get("dashboard") and not attrs.get("insight") and not attrs.get("prompt"):@@ -676,12 +739,24 @@ class SubscriptionSerializer(serializers.ModelSerializer):{"dashboard_export_insights": [f"Cannot select more than {MAX_INSIGHTS} insights."]})- # Ensure all selected insights belong to the team- if Insight.objects.filter(id__in=selected_ids, team_id=self.context["team_id"]).count() != len(- selected_ids- ):+ team_insights = Insight.objects.filter(id__in=selected_ids, team_id=self.context["team_id"])+ user_access_control = self.context["view"].user_access_control+ viewable_ids = set(+ _viewable_queryset(user_access_control, team_insights, "insight").values_list("id", flat=True)+ )+ unusable_ids = selected_ids - viewable_ids+ if unusable_ids:+ if team_insights.count() != len(selected_ids):+ raise ValidationError(+ {"dashboard_export_insights": ["Some insights are not in your team, or no longer exist."]}+ )raise ValidationError(- {"dashboard_export_insights": ["Some insights do not belong to your team or do no longer exist."]}+ {+ "dashboard_export_insights": [+ "Viewer access to every selected insight is required. "+ "Ask an admin for access, or remove the restricted insights."+ ]+ })# Ensure all selected insights belong to the dashboard (and are not deleted)@@ -696,6 +771,31 @@ class SubscriptionSerializer(serializers.ModelSerializer):raise ValidationError({"dashboard_export_insights": [f"{len(invalid_ids)} invalid insight(s) selected."]})+ return++ if self._keeps_its_own_selection():+ return++ self._require_viewer_access_to_every_live_tile(dashboard)++ def _keeps_its_own_selection(self) -> bool:+ return self.instance is not None and self.instance.dashboard_export_insights.exists()++ def _require_viewer_access_to_every_live_tile(self, dashboard: Dashboard) -> None:+ live_tile_insights = Insight.objects.filter(+ team_id=self.context["team_id"],+ id__in=dashboard.tiles.filter(insight__isnull=False, insight__deleted=False).values("insight_id"),+ )+ user_access_control = self.context["view"].user_access_control+ if _blocked_target_ids(user_access_control, live_tile_insights, "insight").exists():+ raise ValidationError(+ {+ "dashboard": [+ "Viewer access to every insight on this dashboard is required. "+ "Ask an admin for access, or select only the insights you can view."+ ]+ }+ )def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Subscription:request = self.context["request"]@@ -911,6 +1011,53 @@ class SubscriptionSerializer(serializers.ModelSerializer):return instance+def _blocked_target_ids(+ user_access_control: UserAccessControl, queryset: QuerySet, resource: APIScopeObject+) -> QuerySet:+ if user_access_control.has_resource_access(resource):+ denied_ids = user_access_control.blocked_resource_ids_by_scope.get(resource, frozenset())+ queryset = queryset.filter(id__in=denied_ids)+ return queryset.exclude(id__in=_viewable_queryset(user_access_control, queryset, resource).values("id")).values(+ "id"+ )+++def _viewable_subscription_filter(user_access_control: UserAccessControl, team_id: int) -> Q:+ return _target_filter(user_access_control, team_id, _SUBSCRIPTION_TARGETS)+++def _viewable_delivery_filter(user_access_control: UserAccessControl, team_id: int) -> Q:+ return _target_filter(user_access_control, team_id, _DELIVERY_TARGETS)+++def _target_filter(user_access_control: UserAccessControl, team_id: int, targets: _TargetLookups) -> Q:+ if not user_access_control.access_controls_supported or user_access_control.is_organization_admin:+ return Q()+ rules = (user_access_control.blocked_resource_ids_by_scope, user_access_control.allowlisted_resource_ids_by_scope)+ has_object_rules = any(scope.get("insight") or scope.get("dashboard") for scope in rules)+ denies_a_target_resource = not user_access_control.has_resource_access(+ "insight"+ ) or not user_access_control.has_resource_access("dashboard")+ if not has_object_rules and not denies_a_target_resource:+ return Q()++ team_dashboards = targets.dashboards.filter(team_id=team_id)+ blocked_insights = _blocked_target_ids(user_access_control, targets.insights.filter(team_id=team_id), "insight")+ blocked_dashboards = _blocked_target_ids(user_access_control, team_dashboards, "dashboard")+ dashboards_with_blocked_tiles = targets.tiles.filter(+ dashboard__in=team_dashboards, insight_id__in=blocked_insights+ ).values("dashboard_id")++ targets_a_blocked_insight = Q(**{targets.insight: blocked_insights})+ targets_a_blocked_dashboard = Q(**{targets.dashboard: blocked_dashboards})+ exports_a_blocked_insight = Q(**{targets.exported_insights: blocked_insights})+ renders_a_blocked_tile = Q(**{targets.no_selection: True}) & Q(**{targets.dashboard: dashboards_with_blocked_tiles})++ return ~(+ targets_a_blocked_insight | targets_a_blocked_dashboard | exports_a_blocked_insight | renders_a_blocked_tile+ )++def _parse_int_param(value: str, param: str) -> int:try:return int(value.strip())@@ -1129,8 +1276,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mif not self.user_access_control.check_access_level_for_object(dashboard, "viewer"):raise exceptions.PermissionDenied("You do not have access to this dashboard.")tile_insight_ids = DashboardTile.objects.filter(- dashboard_id=dashboard_id,- dashboard__team_id=self.team_id,+ dashboard=dashboard,insight_id__isnull=False,insight__deleted=False,).values_list("insight_id", flat=True)@@ -1140,8 +1286,23 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Melif key == "deleted":queryset = queryset.filter(deleted=str_to_bool(request_params["deleted"]))+ if self.action == "list":+ return queryset.filter(_viewable_subscription_filter(self.user_access_control, self.team_id))return queryset+ def safely_get_object(self, queryset: QuerySet) -> Subscription:+ subscription = get_object_or_404(queryset, pk=self.kwargs[self.lookup_field])+ can_view_subscription = (+ Subscription.objects.filter(pk=subscription.pk, team_id=self.team_id)+ .filter(_viewable_subscription_filter(self.user_access_control, self.team_id))+ .exists()+ )+ if not can_view_subscription:+ raise exceptions.PermissionDenied(+ "You do not have viewer access to this subscription. Ask an organization admin to update your access."+ )+ return subscription+@extend_schema(extensions={"x-product": "subscriptions"},request=None,@@ -1477,7 +1638,7 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModel{"status": [f"Must be one of: {', '.join(sorted(valid))}."]},)queryset = queryset.filter(status=status_param)- return queryset+ return queryset.filter(_viewable_delivery_filter(self.user_access_control, self.team_id))def unsubscribe(request: HttpRequest):diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 49f8ac91bd5f..8603ee125c65 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -24,6 +24,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.slo.context import slo_operationfrom products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.subscription import (SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER,Subscription,@@ -42,6 +43,7 @@ from ee.api.test.base import APILicensedTestfrom ee.models.rbac.access_control import AccessControlfrom ee.tasks.subscriptions.slack_subscriptions import get_slack_integration_for_teamfrom ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS+from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscriptionclass TestSubscriptionTemporal(APILicensedTest):@@ -662,7 +664,7 @@ class TestSubscriptionTemporal(APILicensedTest):)assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["attr"] == "dashboard_export_insights"- assert "do not belong to your team" in response.json()["detail"]+ assert "not in your team" in response.json()["detail"]def test_can_create_slack_subscription_with_valid_integration(self):integration = Integration.objects.create(team=self.team, kind="slack", config={})@@ -3104,3 +3106,354 @@ class TestAISubscriptionAPI(APILicensedTest):response = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload)assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()assert "ai_prompt_config" in str(response.json()), response.json()+++class TestSubscriptionObjectAccessControl(APILicensedTest):+ def setUp(self):+ super().setUp()+ self._sync_connect_patcher = patch("ee.api.subscription.sync_connect")+ self.mock_temporal_client = MagicMock(start_workflow=AsyncMock())+ self._sync_connect_patcher.start().return_value = self.mock_temporal_client+ self.addCleanup(self._sync_connect_patcher.stop)+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save(update_fields=["level"])++ self.open_insight = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})+ self.restricted_insight = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})+ self.restricted_dashboard = Dashboard.objects.create(team=self.team, name="Private numbers")+ DashboardTile.objects.create(dashboard=self.restricted_dashboard, insight=self.open_insight)+ self._rule("insight", obj=self.restricted_insight)+ self._rule("dashboard", obj=self.restricted_dashboard)++ def _payload(self, **overrides):+ payload = {+ "target_type": "email",+ "target_value": "[email protected]",+ "frequency": "daily",+ "interval": 1,+ "start_date": "2022-01-01T00:00:00Z",+ "title": "Exfil",+ }+ payload.update(overrides)+ return payload++ def _subscription_for(self, **kwargs) -> Subscription:+ return create_subscription(team=self.team, created_by=self.user, **kwargs)++ def _delivery_for(self, subscription: Subscription, **overrides) -> SubscriptionDelivery:+ return SubscriptionDelivery.objects.create(+ subscription=subscription,+ team=self.team,+ temporal_workflow_id=f"wf-{subscription.id}",+ idempotency_key=f"key-{subscription.id}",+ trigger_type="scheduled",+ target_type="email",+ target_value="[email protected]",+ status=SubscriptionDelivery.Status.COMPLETED,+ content_snapshot={"insights": [{"id": 1, "name": "Secret", "query_results": [[1, 2, 3]]}]},+ **overrides,+ )++ def _rule(self, resource: str, *, obj=None, level: str = "none", for_member: bool = True, team=None) -> None:+ AccessControl.objects.create(+ team=team or self.team,+ resource=resource,+ resource_id=str(obj.id) if obj is not None else None,+ organization_member=self.organization_membership if for_member else None,+ access_level=level,+ )+ cache.clear()++ def _dashboard_with_tiles(self, *insights: Insight) -> Dashboard:+ dashboard = Dashboard.objects.create(team=self.team, name="Team dashboard")+ for insight in insights:+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)+ return dashboard++ def _sub_on_an_open_insight(self) -> Subscription:+ return self._subscription_for(insight=self.open_insight)++ def _sub_on_a_restricted_insight(self) -> Subscription:+ return self._subscription_for(insight=self.restricted_insight)++ def _sub_on_a_restricted_dashboard(self) -> Subscription:+ return self._subscription_for(dashboard=self.restricted_dashboard)++ def _sub_on_an_ai_prompt(self) -> Subscription:+ return self._subscription_for(prompt="How did signups do last week?")++ def _sub_exporting_an_insight_restricted_afterwards(self) -> Subscription:+ exported = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})+ subscription = self._subscription_for(dashboard=self._dashboard_with_tiles(exported))+ subscription.dashboard_export_insights.set([exported])+ self._rule("insight", obj=exported)+ return subscription++ def _sub_rendering_every_tile(self) -> Subscription:+ return self._subscription_for(dashboard=self._dashboard_with_tiles(self.open_insight, self.restricted_insight))++ def _sub_selecting_only_the_open_tile(self) -> Subscription:+ subscription = self._subscription_for(+ dashboard=self._dashboard_with_tiles(self.open_insight, self.restricted_insight)+ )+ subscription.dashboard_export_insights.set([self.open_insight])+ return subscription++ def _sub_whose_restricted_tile_was_removed(self) -> Subscription:+ dashboard = self._dashboard_with_tiles(self.open_insight)+ restricted_tile = DashboardTile.objects.create(dashboard=dashboard, insight=self.restricted_insight)+ subscription = self._subscription_for(dashboard=dashboard)+ restricted_tile.deleted = True+ restricted_tile.save(update_fields=["deleted"])+ return subscription++ def _sub_under_a_resource_wide_deny(self) -> Subscription:+ self._rule("insight")+ return self._subscription_for(insight=self.open_insight)++ def _sub_under_a_lone_resource_wide_deny(self) -> Subscription:+ AccessControl.objects.filter(team=self.team).delete()+ return self._sub_under_a_resource_wide_deny()++ def _sub_under_a_resource_wide_deny_with_a_grant(self) -> Subscription:+ self._rule("insight")+ self._rule("insight", obj=self.open_insight, level="viewer")+ return self._subscription_for(insight=self.open_insight)++ def _sub_read_by_an_org_admin(self) -> Subscription:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save(update_fields=["level"])+ private_insight = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})+ self._rule("insight", obj=private_insight, for_member=False)+ return self._subscription_for(insight=private_insight)++ def _sub_in_a_team_without_rules(self) -> Subscription:+ AccessControl.objects.filter(team=self.team).delete()+ cache.clear()+ return self._subscription_for(insight=self.open_insight)++ def _sub_on_a_soft_deleted_restricted_insight(self) -> Subscription:+ subscription = self._subscription_for(insight=self.restricted_insight)+ self.restricted_insight.deleted = True+ self.restricted_insight.save(update_fields=["deleted"])+ return subscription++ def _assert_visibility(self, subscription: Subscription, *, sees_subscription: bool, sees_deliveries: bool) -> None:+ listed = self.client.get(f"/api/projects/{self.team.id}/subscriptions")+ assert listed.status_code == status.HTTP_200_OK+ assert [row["id"] for row in listed.json()["results"]] == ([subscription.id] if sees_subscription else [])++ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}")+ expected = status.HTTP_200_OK if sees_subscription else status.HTTP_403_FORBIDDEN+ assert retrieved.status_code == expected, retrieved.json()++ deliveries = self.client.get(f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/")+ assert deliveries.status_code == status.HTTP_200_OK+ assert len(deliveries.json()["results"]) == (1 if sees_deliveries else 0)++ @parameterized.expand(+ [+ ("an open insight", "_sub_on_an_open_insight", True, True),+ ("an AI prompt, so no target at all", "_sub_on_an_ai_prompt", True, True),+ ("a restricted insight", "_sub_on_a_restricted_insight", False, False),+ ("a restricted dashboard", "_sub_on_a_restricted_dashboard", False, False),+ (+ "an exported insight restricted after saving",+ "_sub_exporting_an_insight_restricted_afterwards",+ False,+ False,+ ),+ ("no selection and a restricted tile", "_sub_rendering_every_tile", False, False),+ ("a selection that leaves the restricted tile out", "_sub_selecting_only_the_open_tile", True, True),+ ("a restricted tile that was removed", "_sub_whose_restricted_tile_was_removed", True, False),+ ("a deny on the whole insight resource", "_sub_under_a_resource_wide_deny", False, False),+ ("that deny as the only rule in the team", "_sub_under_a_lone_resource_wide_deny", False, False),+ ("that deny with the insight granted back", "_sub_under_a_resource_wide_deny_with_a_grant", True, True),+ ("an org admin reading a private insight", "_sub_read_by_an_org_admin", True, True),+ ("a team with no access rules", "_sub_in_a_team_without_rules", True, True),+ ("a restricted insight that was soft-deleted", "_sub_on_a_soft_deleted_restricted_insight", True, False),+ ]+ )+ def test_target_access_decides_what_the_caller_sees(self, _name, builder, sees_subscription, sees_deliveries):+ subscription = getattr(self, builder)()+ self._delivery_for(subscription)++ self._assert_visibility(subscription, sees_subscription=sees_subscription, sees_deliveries=sees_deliveries)++ def _create_on_a_restricted_insight(self):+ return self.client.post(+ f"/api/projects/{self.team.id}/subscriptions", self._payload(insight=self.restricted_insight.id)+ )++ def _create_on_a_restricted_dashboard(self):+ return self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._payload(dashboard=self.restricted_dashboard.id, dashboard_export_insights=[self.open_insight.id]),+ )++ def _create_selecting_a_restricted_insight(self):+ dashboard = self._dashboard_with_tiles(self.open_insight, self.restricted_insight)+ return self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._payload(+ dashboard=dashboard.id,+ dashboard_export_insights=[self.open_insight.id, self.restricted_insight.id],+ ),+ )++ def _patch_adding_a_restricted_insight(self):+ subscription = self._sub_selecting_only_the_open_tile()+ return self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}",+ {"dashboard_export_insights": [self.open_insight.id, self.restricted_insight.id]},+ )++ def _create_selecting_an_insight_from_another_team(self):+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ foreign_insight = Insight.objects.create(team=other_team, filters={"events": [{"id": "$pageview"}]})+ dashboard = self._dashboard_with_tiles(self.restricted_insight)+ return self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._payload(+ dashboard=dashboard.id,+ dashboard_export_insights=[foreign_insight.id, self.restricted_insight.id],+ ),+ )++ @parameterized.expand(+ [+ ("the insight target", "_create_on_a_restricted_insight", "insight", "Viewer access"),+ ("the dashboard target", "_create_on_a_restricted_dashboard", "dashboard", "Viewer access"),+ (+ "an insight in the export selection",+ "_create_selecting_a_restricted_insight",+ "dashboard_export_insights",+ "Viewer access",+ ),+ (+ "an insight a PATCH adds to the selection",+ "_patch_adding_a_restricted_insight",+ "dashboard_export_insights",+ "Viewer access",+ ),+ (+ "an insight from another team, which outranks the access error",+ "_create_selecting_an_insight_from_another_team",+ "dashboard_export_insights",+ "not in your team",+ ),+ ]+ )+ def test_write_is_rejected_when_the_caller_cannot_view_a_target(self, _name, request_builder, attr, message):+ response = getattr(self, request_builder)()++ body = response.json()+ assert response.status_code == status.HTTP_400_BAD_REQUEST, body+ assert body["attr"] == attr, body+ assert message in body["detail"], body+ self.mock_temporal_client.start_workflow.assert_not_called()++ def test_create_allows_an_open_insight(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions", self._payload(insight=self.open_insight.id)+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ ("patch", "patch", "", {"target_value": "[email protected]"}),+ ("test_delivery", "post", "/test-delivery", None),+ ]+ )+ def test_restricted_subscription_cannot_be_written_by_id(self, _name, method, url_suffix, body):+ subscription = self._sub_on_a_restricted_insight()++ url = f"/api/projects/{self.team.id}/subscriptions/{subscription.id}{url_suffix}"+ response = getattr(self.client, method)(url, body)++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()++ def test_insight_filter_does_not_confirm_a_restricted_subscription(self):+ hidden = self._sub_on_a_restricted_insight()++ filtered = self.client.get(f"/api/projects/{self.team.id}/subscriptions?insight={self.restricted_insight.id}")++ assert filtered.status_code == status.HTTP_200_OK+ assert filtered.json()["results"] == []+ assert Subscription.objects.filter(pk=hidden.pk).exists()++ def test_tile_rule_holds_for_a_dashboard_read_through_an_environment(self):+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")+ self._rule("insight", obj=self.restricted_insight, team=environment)+ dashboard = Dashboard.objects.create(team=environment, name="Team dashboard")+ DashboardTile.objects.create(dashboard=dashboard, insight=self.open_insight)+ DashboardTile.objects.create(dashboard=dashboard, insight=self.restricted_insight)+ subscription = create_subscription(team=environment, created_by=self.user, dashboard=dashboard)++ listed = self.client.get(f"/api/environments/{environment.id}/subscriptions")++ assert listed.status_code == status.HTTP_200_OK+ assert subscription.id not in [row["id"] for row in listed.json()["results"]]++ def test_multi_insight_dashboard_subscription_is_returned_exactly_once(self):+ second_insight = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})+ subscription = self._subscription_for(dashboard=self._dashboard_with_tiles(self.open_insight, second_insight))+ subscription.dashboard_export_insights.set([self.open_insight, second_insight])+ self._delivery_for(subscription)++ self._assert_visibility(subscription, sees_subscription=True, sees_deliveries=True)++ @parameterized.expand(+ [+ ("a rename", {"title": "Renamed"}, status.HTTP_400_BAD_REQUEST),+ ("a new recipient", {"target_value": "[email protected]"}, status.HTTP_400_BAD_REQUEST),+ ("turning it off", {"deleted": True}, status.HTTP_200_OK),+ ]+ )+ def test_write_to_a_soft_deleted_restricted_target_may_only_turn_it_off(self, _name, body, expected):+ subscription = self._subscription_for(insight=self.restricted_insight)+ self.restricted_insight.deleted = True+ self.restricted_insight.save(update_fields=["deleted"])++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", body)++ assert response.status_code == expected, response.json()++ @parameterized.expand([("an open insight", False), ("a restricted insight", True)])+ def test_subscription_on_a_soft_deleted_target_can_still_be_turned_off(self, _name, restricted):+ target = self.restricted_insight if restricted else self.open_insight+ subscription = self._subscription_for(insight=target)+ target.deleted = True+ target.save(update_fields=["deleted"])++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", {"deleted": True})++ assert response.status_code == status.HTTP_200_OK, response.json()++ @parameterized.expand([("a rename", {"title": "Renamed"}), ("turning it off", {"deleted": True})])+ def test_patch_that_omits_the_selection_is_accepted(self, _name, body):+ subscription = self._sub_selecting_only_the_open_tile()++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", body)++ assert response.status_code == status.HTTP_200_OK, response.json()++ def test_repointing_an_empty_selection_at_a_restricted_tile_is_rejected(self):+ subscription = self._subscription_for(dashboard=self._dashboard_with_tiles(self.open_insight))+ target_dashboard = self._dashboard_with_tiles(self.open_insight, self.restricted_insight)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}",+ {"dashboard": target_dashboard.id, "target_value": "[email protected]"},+ )++ body = response.json()+ assert response.status_code == status.HTTP_400_BAD_REQUEST, body+ assert body["attr"] == "dashboard", body+ assert "Viewer access to every insight on this dashboard" in body["detail"], body+ self.mock_temporal_client.start_workflow.assert_not_called()diff --git a/products/subscriptions/frontend/scenes/SubscriptionScene.tsx b/products/subscriptions/frontend/scenes/SubscriptionScene.tsxindex 165257099471..7150017be171 100644--- a/products/subscriptions/frontend/scenes/SubscriptionScene.tsx+++ b/products/subscriptions/frontend/scenes/SubscriptionScene.tsx@@ -3,6 +3,7 @@ import { router } from 'kea-router'import { LemonButton } from '@posthog/lemon-ui'+import { AccessDenied } from 'lib/components/AccessDenied'import { NotFound } from 'lib/components/NotFound'import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'@@ -83,6 +84,7 @@ function SubscriptionDetailActions({ sub }: { sub: SubscriptionApi }): JSX.Elemeexport function SubscriptionScene(): JSX.Element {const {subscription,+ subscriptionAccessDenied,subscriptionLoading,deliveriesPage,deliveriesPageLoading,@@ -94,11 +96,13 @@ export function SubscriptionScene(): JSX.Element {const { loadDeliveriesPage, deliverSubscription, setDeliveryStatusFilter, submitDeliveryFeedback } =useActions(subscriptionSceneLogic)- const showNotFound = !subscriptionLoading && !subscription+ const showNotFound = !subscriptionLoading && !subscription && !subscriptionAccessDeniedreturn (<SceneContent>- {showNotFound ? (+ {subscriptionAccessDenied ? (+ <AccessDenied object="subscription" />+ ) : showNotFound ? (<NotFound object="subscription" />) : (<div className="py-8 flex-1 min-h-0 flex flex-col gap-6 max-w-full">diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.tsindex 988e41db730b..03b465917dc2 100644--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts@@ -129,6 +129,26 @@ describe('subscriptionSceneLogic', () => {logic.unmount()})+ it.each([+ [403, true],+ [404, false],+ ])('marks only a %s subscription load failure as access denied', async (status, subscriptionAccessDenied) => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/1/`]: () => [status, { detail: 'Request failed' }],+ },+ })+ initKeaTests()+ const logic = subscriptionSceneLogic({ id: '1' })+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadSubscriptionFailure'])+ .toMatchValues({ subscriptionAccessDenied })++ logic.unmount()+ })+// The failure path matters too: the header button's double-submit guard would stick// if deliveringSubscriptionId reset only on success.it.each([diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsxindex a36c46a9c05f..93e79b0b4b46 100644--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx@@ -61,6 +61,7 @@ export interface subscriptionSceneLogicValues {deliveryStatusFilter: SubscriptionsDeliveriesListStatus | nullrecentlyThankedDeliveries: Record<string, true>subscription: SubscriptionApi | null+ subscriptionAccessDenied: booleansubscriptionLoading: boolean}@@ -183,6 +184,13 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([deliverSubscriptionFailure: () => null,},],+ subscriptionAccessDenied: [+ false,+ {+ loadSubscription: () => false,+ loadSubscriptionFailure: (_, { errorObject }) => errorObject?.status === 403,+ },+ ],deliveryStatusFilter: [null as SubscriptionsDeliveriesListStatus | null,{