: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): gate AI delivery report snapshot on query access (#62142)
Vasco de Krijgerc36918feb3bc
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 0edc0e0b9b65..294a146b7579 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -1,7 +1,7 @@import uuidimport asynciofrom collections.abc import Callable-from typing import Any, Optional+from typing import Any, ClassVar, Optionalfrom django.conf import settingsfrom django.core.cache import cache@@ -735,6 +735,16 @@ class SubscriptionSerializer(serializers.ModelSerializer):return instance+def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool:+ """An AI subscription is one backed by a non-empty prompt (team-scoped)."""+ return (+ Subscription.objects.filter(pk=subscription_id, team_id=team_id)+ .exclude(prompt__isnull=True)+ .exclude(prompt="")+ .exists()+ )++@extend_schema_view(list=extend_schema(parameters=[@@ -829,12 +839,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mreturn True# Existing subscription (update / test-delivery): resolve its kind by pk, team-scoped.pk = view.kwargs.get("pk")- return bool(pk) and (- Subscription.objects.filter(pk=pk, team_id=self.team_id)- .exclude(prompt__isnull=True)- .exclude(prompt="")- .exists()- )+ return bool(pk) and _subscription_is_ai_prompt(pk, self.team_id)def safely_get_queryset(self, queryset) -> QuerySet:request_params = self.request.GET.dict()@@ -1006,6 +1011,11 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mclass SubscriptionDeliverySerializer(serializers.ModelSerializer):+ # Delivery fields that embed the query-derived AI report, mapped to the value each returns when+ # scrubbed for a caller without query access (content_snapshot is a non-null object, change_summary+ # nullable text). Single source of truth — keep in sync when adding AI-derived delivery fields.+ AI_REPORT_SCRUBBED: ClassVar[dict[str, dict | None]] = {"content_snapshot": {}, "change_summary": None}+class Meta:model = SubscriptionDeliveryfields = [@@ -1055,6 +1065,15 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):"change_summary": {"help_text": "AI-generated summary included in this delivery, when one was produced."},}+ def to_representation(self, instance):+ data = super().to_representation(instance)+ # The viewset sets this flag when an AI prompt delivery is read by a caller without query+ # access; scrub the query-derived report so subscription:read (or a self-granted query:read+ # scope) can't read analytics the user isn't allowed to run themselves.+ if self.context.get("hide_ai_report"):+ data.update(self.AI_REPORT_SCRUBBED)+ return data+class SubscriptionDeliveryCursorPagination(CursorPagination):page_size = 50@@ -1091,6 +1110,21 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelpagination_class = SubscriptionDeliveryCursorPaginationordering = "-created_at"+ def get_serializer_context(self) -> dict:+ context = super().get_serializer_context()+ context["hide_ai_report"] = self._should_hide_ai_report()+ return context++ def _should_hide_ai_report(self) -> bool:+ # An AI prompt subscription's delivered report is query-derived, so reading it requires query+ # access — mirroring the create/test-delivery gate. Non-AI deliveries are unaffected.+ subscription_id = self.kwargs.get("parent_lookup_subscription_id")+ if not subscription_id:+ return True # nested route always supplies this; fail closed (scrub) if it ever doesn't+ if not _subscription_is_ai_prompt(subscription_id, self.team_id):+ return False+ return not self.user_access_control.check_access_level_for_resource("query", "viewer")+def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:subscription_id = self.kwargs.get("parent_lookup_subscription_id")if subscription_id:diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 1bedd8b8039e..2ba4cb555649 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -1771,6 +1771,88 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):params.update(kwargs)return SubscriptionDelivery.objects.create(**params)+ def _create_ai_subscription(self) -> Subscription:+ return Subscription.objects.create(+ team=self.team,+ created_by=self.user,+ prompt="Weekly growth recap",+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ interval=1,+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=UTC),+ title="AI Sub",+ )++ def _restrict_query_access(self) -> None:+ # Demote the owner (owners bypass access controls) to a member with an explicit query "none"+ # row so they fall below the read level required to see AI-generated report content.+ 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"])+ AccessControl.objects.create(+ team=self.team,+ resource="query",+ resource_id=None,+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()++ @parameterized.expand(+ [+ # The delivered report is query-derived only for AI prompt subscriptions, so its content+ # is hidden from a query-restricted member there — but insight deliveries (no prompt) and+ # members who keep query access still see the full snapshot.+ ("ai_restricted", True, True, True),+ ("ai_with_access", True, False, False),+ ("insight_restricted", False, True, False),+ ]+ )+ def test_ai_delivery_report_hidden_without_query_access(self, _name, is_ai, restrict, expect_hidden):+ subscription = self._create_ai_subscription() if is_ai else self.subscription+ delivery = SubscriptionDelivery.objects.create(+ subscription=subscription,+ team=self.team,+ temporal_workflow_id="wf-report",+ idempotency_key="report-key",+ 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]]}]},+ change_summary="Signups up 20% week over week",+ recipient_results=[{"recipient": "[email protected]", "status": "success"}],+ )+ if restrict:+ self._restrict_query_access()++ response = self.client.get(+ f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/{delivery.id}/"+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ data = response.json()+ if expect_hidden:+ assert data["content_snapshot"] == {}+ assert data["change_summary"] is None+ # The list endpoint shares the same get_serializer_context path, so it scrubs too.+ list_response = self.client.get(+ f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/"+ )+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()+ row = next(r for r in list_response.json()["results"] if r["id"] == str(delivery.id))+ assert row["content_snapshot"] == {}+ assert row["change_summary"] is None+ else:+ assert data["content_snapshot"]["insights"][0]["name"] == "Secret"+ assert data["change_summary"] == "Signups up 20% week over week"+ # Delivery metadata stays visible regardless — only the query-derived report is scrubbed.+ assert data["status"] == "completed"+ assert data["recipient_results"] == [{"recipient": "[email protected]", "status": "success"}]+def test_can_list_deliveries(self):d1 = self._create_delivery(idempotency_key="key-1")d2 = self._create_delivery(idempotency_key="key-2")