: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(sharing): gate the incoming query when a patch adds an insight to a shared dashboard (#97662)
Alex Lider598fbbb909ac
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 5c266c8fd867..123108b05ab9 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -2340,20 +2340,31 @@ class TestSaveTimeAccessBlock(APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.content- def test_adding_insight_to_shared_dashboard_blocked(self):+ @parameterized.expand([("stored_query",), ("query_in_same_patch",)])+ def test_adding_insight_to_shared_dashboard_blocked(self, coverage: str):self._deny_editor()- self.insight.query = self._DENIED_QUERY- self.insight.save()dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)+ payload: dict = {"dashboards": [dashboard.id]}+ if coverage == "stored_query":+ self.insight.query = self._DENIED_QUERY+ self.insight.save()+ else:+ # The insight isn't shared yet, so only the dashboard gate runs. It must see the+ # incoming query, not the stored one that is about to be overwritten.+ payload["query"] = self._DENIED_QUERY- response = self.client.patch(- f"/api/projects/{self.team.id}/insights/{self.insight.id}/", {"dashboards": [dashboard.id]}- )+ response = self.client.patch(f"/api/projects/{self.team.id}/insights/{self.insight.id}/", payload)assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert "publicly shared" in str(response.json())assert not DashboardTile.objects.filter(dashboard=dashboard, insight=self.insight).exists()+ if coverage == "query_in_same_patch":+ self.insight.refresh_from_db()+ assert self.insight.query == {+ "kind": "DataTableNode",+ "source": {"kind": "HogQLQuery", "query": "SELECT 1 AS one"},+ }def test_adding_insight_to_unshared_dashboard_allowed(self):self._deny_editor()diff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.pyindex 856b9bdb27e6..1971376b9294 100644--- a/products/dashboards/backend/facade/api.py+++ b/products/dashboards/backend/facade/api.py@@ -244,12 +244,16 @@ def update_insight_dashboard_membership(*,insight: "Insight",dashboard_ids: Sequence[int],+ query: Any,user: User,user_permissions: UserPermissions,user_access_control: UserAccessControl | None,) -> MembershipChange | None:"""Move an insight on and off dashboards until it sits on exactly `dashboard_ids`.+ `query` is the query the insight will run once the caller's write lands, not the stored one:+ a PATCH that changes the query and the dashboards together must gate on the incoming query.+Returns None when it already does. Adding restores the insight's previously removed tilerather than creating a second one; removing soft-deletes the tile so the same restore worksnext time. Refusals raise `CannotAddToDashboard`, `CannotRemoveFromDashboard` or@@ -282,7 +286,7 @@ def update_insight_dashboard_membership(raise DashboardNotFound# The dashboard's public link must not expose a query the editor can't run.- check_can_add_insight_to_shared_dashboard(user, dashboard, insight.query, user_access_control)+ check_can_add_insight_to_shared_dashboard(user, dashboard, query, user_access_control)tile, _ = DashboardTile.objects_including_soft_deleted.get_or_create(insight=insight, dashboard=dashboard)if tile.deleted:diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 7c2093128e84..cdb182fb0e0e 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -874,7 +874,8 @@ class InsightSerializer(InsightBasicSerializer):else:dashboard_ids = validated_data.pop("dashboards", None)if dashboard_ids is not None:- self._update_insight_dashboards(dashboard_ids, instance)+ # The membership write runs before the query is saved, so gate on the incoming one.+ self._update_insight_dashboards(dashboard_ids, instance, validated_data.get("query", instance.query))updated_insight = super().update(instance, validated_data)# Delete linked alerts only when the insight can no longer carry any alert. A switch between@@ -947,7 +948,7 @@ class InsightSerializer(InsightBasicSerializer):return []- def _update_insight_dashboards(self, dashboard_ids: list[int], instance: Insight) -> None:+ def _update_insight_dashboards(self, dashboard_ids: list[int], instance: Insight, query: Any) -> None:# Counts the field being accepted as write input — before the no-op early return, so# integrations that round-trip an unchanged dashboards list still register as writers._record_deprecated_dashboards_field_used(self.context, usage="write")@@ -956,6 +957,7 @@ class InsightSerializer(InsightBasicSerializer):change = update_insight_dashboard_membership(insight=instance,dashboard_ids=dashboard_ids,+ query=query,user=self.context["request"].user,user_permissions=self.user_permissions,user_access_control=self.user_access_control,