: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): keep authorship out of shared dashboard payloads (#79070)
Phillc9b0942a4b46
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 899235d4479d..79bb0cd65560 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -24,7 +24,7 @@ from rest_framework.request import Requestfrom posthog.schema import SharingConfigurationSettings-from posthog.api.data_color_theme import DataColorTheme, DataColorThemeSerializer+from posthog.api.data_color_theme import DataColorTheme, PublicDataColorThemeSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.services.query import process_query_dictfrom posthog.api.shared import TeamPublicSerializer@@ -265,13 +265,14 @@ def export_asset_for_opengraph(resource: SharingConfiguration) -> ExportedAssetdef get_themes_for_team(team: Team):global_and_team_themes = DataColorTheme.objects.filter(Q(team_id=team.pk) | Q(team_id=None))- themes = DataColorThemeSerializer(global_and_team_themes, many=True).data+ # The shared payload is served to anonymous viewers, so use the serializer without `created_by`.+ themes = PublicDataColorThemeSerializer(global_and_team_themes, many=True).datareturn themesdef get_global_themes():global_themes = DataColorTheme.objects.filter(Q(team_id=None))- themes = DataColorThemeSerializer(global_themes, many=True).data+ themes = PublicDataColorThemeSerializer(global_themes, many=True).datareturn themes@@ -1125,7 +1126,10 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSerecord_dashboard_view(resource.dashboard, context["dashboard_access_method"])with task_chain_context():- dashboard_data = DashboardSerializer(resource.dashboard, context=context).data+ # Viewers of a shared dashboard never get the tile details panel, so the people+ # who created and last modified the dashboard and its tiles stay out of the payload+ dashboard_context = {**context, "hide_extra_details": True}+ dashboard_data = DashboardSerializer(resource.dashboard, context=dashboard_context).data# We don't want the dashboard to be accidentally loaded via the shared endpointexported_data.update({"dashboard": dashboard_data})exported_data.update({"themes": get_themes_for_team(resource.team)})diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex e57af21a03a0..d685e1463e77 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -25,14 +25,16 @@ from posthog.api.sharing import ()from posthog.constants import AvailableFeaturefrom posthog.models import ActivityLog, OrganizationMembership+from posthog.models.data_color_theme import DataColorThemefrom posthog.models.filters.filter import Filterfrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import User+from products.alerts.backend.models.alert import AlertConfigurationfrom products.dashboards.backend.access import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Textfrom products.dashboards.backend.models.dashboard_widget import DashboardWidgetfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.exports.backend.models.exported_asset import ExportedAsset, get_render_access_token@@ -1707,6 +1709,52 @@ class TestSharedCohortInlining(APIBaseTest):assert widget_data["config"]["limit"] == 10assert "created_by" not in widget_data+ @mock_exporter_template+ def test_shared_dashboard_omits_authorship_of_dashboard_and_tiles(self):+ dashboard = Dashboard.objects.create(team=self.team, name="dash", created_by=self.user)+ insight = Insight.objects.create(+ team=self.team,+ name="Pageviews",+ query={"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},+ created_by=self.user,+ last_modified_by=self.user,+ )+ AlertConfiguration.objects.create(+ team=self.team, insight=insight, name="High pageviews", enabled=True, created_by=self.user+ )+ DashboardTile.objects.create(dashboard=dashboard, team_id=self.team.id, insight=insight)+ text = Text.objects.create(team=self.team, body="Read me", created_by=self.user, last_modified_by=self.user)+ DashboardTile.objects.create(dashboard=dashboard, team_id=self.team.id, text=text)+ button = ButtonTile.objects.create(+ team=self.team,+ url="https://example.com",+ text="Open docs",+ created_by=self.user,+ last_modified_by=self.user,+ )+ DashboardTile.objects.create(dashboard=dashboard, team_id=self.team.id, button_tile=button)+ DataColorTheme.objects.create(team=self.team, name="Brand", colors=["#000000"], created_by=self.user)++ config = SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)+ response = self.client.get(f"/shared/{config.access_token}")+ assert response.status_code == 200++ body = response.content.decode()+ assert self.user.email not in body++ exported = self._parse_exported_data(body)+ exported_dashboard = exported["dashboard"]+ assert "created_by" not in exported_dashboard+ for tile in exported_dashboard["tiles"]:+ for tile_content in (tile.get("insight"), tile.get("text"), tile.get("button_tile")):+ if tile_content is not None:+ assert "created_by" not in tile_content+ assert "last_modified_by" not in tile_content+ if tile.get("insight") is not None:+ assert tile["insight"]["alerts"] == []+ for theme in exported["themes"]:+ assert "created_by" not in theme+class TestSharingResourceEditChecks(APIBaseTest):def test_every_shareable_resource_has_an_edit_check(self):diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 3ef4274ac30a..11a3959ebd05 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -723,6 +723,15 @@ class CanEditDashboard(BasePermission):return view.user_permissions.dashboard(dashboard).can_edit+def _hide_extra_details(context: dict[str, Any], representation: dict[str, Any]) -> None:+ """Drop authorship details, which carry the name and email of a teammate, when the caller+ can't see them anyway — a shared dashboard, or `hideExtraDetails` on the sharing config."""+ if not context.get("hide_extra_details", False):+ return+ for field in ("created_by", "last_modified_by", "created_at", "last_modified_at"):+ representation.pop(field, None)++class TextSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)last_modified_by = UserBasicSerializer(read_only=True)@@ -740,6 +749,11 @@ class TextSerializer(serializers.ModelSerializer):fields = "__all__"read_only_fields = ["id", "created_by", "last_modified_by", "last_modified_at"]+ def to_representation(self, instance: Text) -> dict[str, Any]:+ representation = super().to_representation(instance)+ _hide_extra_details(self.context, representation)+ return representation+class ButtonTileSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)@@ -760,6 +774,11 @@ class ButtonTileSerializer(serializers.ModelSerializer):fields = "__all__"read_only_fields = ["id", "created_by", "last_modified_by", "last_modified_at"]+ def to_representation(self, instance: ButtonTile) -> dict[str, Any]:+ representation = super().to_representation(instance)+ _hide_extra_details(self.context, representation)+ return representation+def validate_url(self, value: str) -> str:if value.startswith("/"):if not re.match(r"^/[a-zA-Z0-9._~:/?#\[\]@!$&'()*+,;=%-]*$", value):@@ -896,6 +915,11 @@ class DashboardTileErrorSerializer(DashboardTileSerializer):"user_access_level": user_access_level,}+ # InsightBasicSerializer ignores `hide_extra_details`, so strip authorship here too, otherwise+ # a tile that errors on a shared dashboard leaks its insight's creator name and email.+ if isinstance(representation.get("insight"), dict):+ _hide_extra_details(self.context, representation["insight"])+return representation@@ -1111,6 +1135,7 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):ret = super().to_representation(instance)if ret.get("quick_filter_ids") is None:ret["quick_filter_ids"] = []+ _hide_extra_details(self.context, ret)return retdef _filter_out_non_existing_quick_filter_ids(self, quick_filter_ids: list[str], team_id: int) -> list[str]:diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex d5f9bf380e6e..c35215ee06fd 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -1135,6 +1135,11 @@ class InsightSerializer(InsightBasicSerializer):if insight.alertable_query_kind is None:return []+ # Alert configs carry their creator's and subscribers' names and emails, which anonymous+ # viewers of a shared dashboard must never receive, so omit them when hiding authorship.+ if self.context.get("hide_extra_details", False):+ return []+# Use prefetched alerts dataalerts = getattr(insight, "_prefetched_alerts", [])from products.alerts.backend.api.alert import AlertSerializer