: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(dashboards): require viewer access on source when duplicating (#65115)
Yasen1eba64915ffd
diff --git a/posthog/api/test/dashboards/test_dashboard_duplication.py b/posthog/api/test/dashboards/test_dashboard_duplication.pyindex 3f87468a77f3..e7ce9c5d524d 100644--- a/posthog/api/test/dashboards/test_dashboard_duplication.py+++ b/posthog/api/test/dashboards/test_dashboard_duplication.py@@ -1,6 +1,18 @@+import pytestfrom posthog.test.base import APIBaseTest, QueryMatchingTest+from parameterized import parameterized+from rest_framework import status+from posthog.api.test.dashboards import DashboardAPI+from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ passclass TestDashboardDuplication(APIBaseTest, QueryMatchingTest):@@ -126,3 +138,68 @@ class TestDashboardDuplication(APIBaseTest, QueryMatchingTest):if child_id is not None:child_ids.append(child_id)return child_ids+++class TestDashboardDuplicationAccessControl(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()++ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)+ self.dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "secret"})+ self.insight_id, _ = self.dashboard_api.create_insight(+ {"dashboards": [self.dashboard_id], "name": "confidential"}+ )++ self.member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)++ def _set_access(self, resource: str, resource_id: int, access_level: str) -> None:+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=str(resource_id),+ access_level=access_level,+ organization_member=self.membership,+ )++ def _duplicate(self) -> int:+ return self.client.post(+ f"/api/projects/{self.team.id}/dashboards/",+ {"name": "copy", "use_dashboard": self.dashboard_id, "duplicate_tiles": True},+ ).status_code++ @parameterized.expand(+ [+ ("none", status.HTTP_403_FORBIDDEN),+ ("viewer", status.HTTP_201_CREATED),+ ]+ )+ def test_duplication_requires_viewer_access_to_source_dashboard(+ self, access_level: str, expected_status: int+ ) -> None:+ self._set_access("dashboard", self.dashboard_id, access_level)+ self.client.force_login(self.member)++ assert self._duplicate() == expected_status++ def test_denied_source_dashboard_also_blocks_direct_retrieve(self) -> None:+ # Baseline: the duplication block is a back door around this denied retrieve.+ self._set_access("dashboard", self.dashboard_id, "none")+ self.client.force_login(self.member)++ retrieve_status = self.client.get(f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}/").status_code+ assert retrieve_status == status.HTTP_403_FORBIDDEN++ def test_duplication_requires_viewer_access_to_each_insight(self) -> None:+ # Dashboard is viewable, but an individual insight is explicitly restricted.+ self._set_access("dashboard", self.dashboard_id, "viewer")+ self._set_access("insight", self.insight_id, "none")+ self.client.force_login(self.member)++ assert self._duplicate() == status.HTTP_403_FORBIDDENdiff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.pyindex c00c5440532c..3e1d9c42df44 100644--- a/posthog/api/test/test_resource_transfer.py+++ b/posthog/api/test/test_resource_transfer.py@@ -802,7 +802,10 @@ class TestResourceTransferTenantIsolation(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTbody_text = str(response.json())- assert str(self.foreign_team.pk) not in body_text+ # The error must not name the foreign team. Check for a "team <id>" reference rather than a bare+ # substring: team and insight pks come from independent sequences and can coincide, so a bare+ # `str(pk) in body` false-positives against the (legitimately echoed) substitution insight id.+ assert f"team {self.foreign_team.pk}".lower() not in body_text.lower()class TestResourceTransferProjectAccessControl(APIBaseTest):diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 230396254a54..7d7270293b20 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1170,6 +1170,7 @@ class DashboardSerializer(DashboardMetadataSerializer):validated_data = self._update_creation_mode(validated_data, use_template, use_dashboard)tags = validated_data.pop("tags", None) # tags are created separately below as global tag relationshipsexisting_dashboard: Dashboard | None = None+ user_access_control = UserAccessControl(user=cast(User, request.user), team=team)if use_dashboard:try:existing_dashboard = Dashboard.objects.get(@@ -1178,6 +1179,11 @@ class DashboardSerializer(DashboardMetadataSerializer):except Dashboard.DoesNotExist:raise serializers.ValidationError({"use_dashboard": "Invalid value provided"})+ # Duplicating a dashboard reads and copies all of its content (filters, variables, tiles, insights),+ # so the caller must have at least viewer access to the source — mirrors the copy_tile/move_tile checks.+ if not user_access_control.check_access_level_for_object(existing_dashboard, "viewer"):+ raise exceptions.PermissionDenied("You don't have permission to view the source dashboard.")+request_filters = request.data.get("filters")if request_filters:if not isinstance(request_filters, dict):@@ -1210,7 +1216,7 @@ class DashboardSerializer(DashboardMetadataSerializer):use_template,dashboard,cast(User, request.user),- user_access_control=UserAccessControl(user=cast(User, request.user), team=team),+ user_access_control=user_access_control,)except AttributeError as error:logger.error(@@ -1232,7 +1238,7 @@ class DashboardSerializer(DashboardMetadataSerializer):for existing_tile in existing_tiles:# Widget tiles move with their widget row; other tiles re-link shared insight/text/button rows.if duplicate_tiles or existing_tile.widget_id is not None:- self._deep_duplicate_tiles(dashboard, existing_tile)+ self._deep_duplicate_tiles(dashboard, existing_tile, user_access_control)else:existing_tile.copy_to_dashboard(dashboard)@@ -1255,8 +1261,17 @@ class DashboardSerializer(DashboardMetadataSerializer):return dashboard- def _deep_duplicate_tiles(self, dashboard: Dashboard, existing_tile: DashboardTile) -> None:+ def _deep_duplicate_tiles(+ self, dashboard: Dashboard, existing_tile: DashboardTile, user_access_control: UserAccessControl+ ) -> None:if existing_tile.insight:+ # Deep duplication serializes and recreates the source insight, so the caller must have viewer+ # access to that specific insight — an insight can be restricted independently of its dashboard.+ if not user_access_control.check_access_level_for_object(existing_tile.insight, "viewer"):+ raise exceptions.PermissionDenied(+ "You don't have permission to view one of the source dashboard's insights."+ )+new_data = {**InsightSerializer(existing_tile.insight, context=self.context).data,"id": None, # to create a new Insight@@ -1449,11 +1464,13 @@ class DashboardSerializer(DashboardMetadataSerializer):)duplicate_tiles = initial_data.pop("duplicate_tiles", [])- for tile_data in duplicate_tiles:- # nosemgrep: idor-lookup-without-team (scoped via parent viewset get_queryset)- existing_tile = DashboardTile.objects.get(dashboard=instance, id=tile_data["id"])- existing_tile.layouts = tile_data.get("layouts", {})- self._deep_duplicate_tiles(instance, existing_tile)+ if duplicate_tiles:+ user_access_control = UserAccessControl(user=user, team=instance.team)+ for tile_data in duplicate_tiles:+ # nosemgrep: idor-lookup-without-team (scoped via parent viewset get_queryset)+ existing_tile = DashboardTile.objects.get(dashboard=instance, id=tile_data["id"])+ existing_tile.layouts = tile_data.get("layouts", {})+ self._deep_duplicate_tiles(instance, existing_tile, user_access_control)if "request" in self.context:if being_deleted: