: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): check table access for filters saved on a delivered dashboard (#116782)
Alex Lider5821632cf5e9
diff --git a/posthog/api/sharing_publish_gate.py b/posthog/api/sharing_publish_gate.pyindex 9ffecd0c5f67..d3e824b4fdb9 100644--- a/posthog/api/sharing_publish_gate.py+++ b/posthog/api/sharing_publish_gate.py@@ -15,9 +15,11 @@ from rest_framework import serializersfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.errors import TableAccessDeniedError+from posthog.hogql.escape_sql import backquote_escape_chars_mapfrom posthog.hogql.modifiers import create_default_modifiers_for_userfrom posthog.hogql.printer import prepare_ast_for_printing+from posthog.api.property_filter_access_gate import table_blocking_property_filtersfrom posthog.constants import AvailableFeaturefrom posthog.hogql_queries.query_runner import get_query_runner_or_nonefrom posthog.models import Team, User@@ -64,7 +66,63 @@ def blocked_access_for_publisher(user: User, team: Team, config: SharingConfigurthe same resolution the read path uses. Non-access compile errors don't gate.Empty list = safe to publish."""- return blocked_access_for_user(user, team, _queries_exposed_by(config))+ blocked = blocked_access_for_user(user, team, _queries_exposed_by(config))+ # A dashboard's own filters and tile overrides run inside every tile, and they could have+ # been saved before the dashboard was shared, when the save-time check did not apply.+ if config.dashboard is not None:+ leaves = dashboard_filter_leaves(config.dashboard.filters)+ for overrides in config.dashboard.tiles.values_list("filters_overrides", flat=True):+ leaves += dashboard_filter_leaves(overrides)+ if (table := table_blocking_property_filters(user, team, leaves)) and table not in blocked:+ blocked = sorted([*blocked, table])+ return blocked+++def dashboard_filter_leaves(filters: Any) -> list[dict[str, Any]]:+ """The property filters of a dashboard filter set, plus its breakdowns as HogQL filters, in+ the shape `table_blocking_property_filters` checks. A leaf without a string type is skipped,+ since the check cannot classify it."""+ if not isinstance(filters, dict):+ return []+ properties = filters.get("properties")+ leaves = [+ leaf+ for leaf in (properties if isinstance(properties, list) else [])+ if isinstance(leaf, dict) and isinstance(leaf.get("type"), str)+ ]+ breakdown_filter = filters.get("breakdown_filter")+ if not isinstance(breakdown_filter, dict):+ return leaves+ breakdowns = breakdown_filter.get("breakdowns")+ pairs = [+ (breakdown.get("type"), breakdown.get("property"))+ for breakdown in (breakdowns if isinstance(breakdowns, list) else [])+ if isinstance(breakdown, dict)+ ]+ pairs.append((breakdown_filter.get("breakdown_type"), breakdown_filter.get("breakdown")))+ for breakdown_type, value in pairs:+ # A funnel breakdown is a list of values, each read like a single breakdown.+ for key in value if isinstance(value, list) else [value]:+ if isinstance(breakdown_type, str) and isinstance(key, str):+ if expr := _breakdown_as_hogql(breakdown_type, key):+ leaves.append({"type": "hogql", "key": expr})+ return leaves+++def _breakdown_as_hogql(breakdown_type: str, key: str) -> str | None:+ """The expression a breakdown reads, as the trends breakdown builds it, for the breakdown+ types that can reach a warehouse table. None for the types that cannot."""+ if breakdown_type in ("hogql", "event_metadata"):+ return key+ if breakdown_type == "data_warehouse":+ chain = key.split(".")+ elif breakdown_type == "data_warehouse_person_property":+ chain = ["person", *key.split(".")]+ else:+ return None+ # Every part is quoted, so a part that reads as a keyword, such as `null`, stays a field name,+ # and a part the printer would refuse does not raise here.+ return ".".join("`" + "".join(backquote_escape_chars_map.get(c, c) for c in part) + "`" for part in chain)def blocked_access_for_user(user: User, team: Team, queries: list[dict[str, Any]]) -> list[str]:diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 94a3e9091538..6723da189c1b 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -1,6 +1,7 @@import jsonfrom datetime import timedeltafrom functools import wraps+from typing import Anyfrom urllib.parse import quoteimport time_machine@@ -24,6 +25,7 @@ from posthog.api.sharing import (check_can_access_sharing_configuration,shared_url_as_png,)+from posthog.api.sharing_publish_gate import dashboard_filter_leavesfrom posthog.auth import SharingPasswordProtectedAuthenticationfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, decode_jwt@@ -34,6 +36,7 @@ from posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import Userfrom posthog.test.authentication_checks import covers_authenticationfrom posthog.test.insight_queries import browser_filtered_pageview_query+from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_memberfrom products.access_control.backend.models.access_control import AccessControlfrom products.alerts.backend.models.alert import AlertConfiguration@@ -43,6 +46,7 @@ from products.dashboards.backend.models.dashboard_tile import ButtonTile, Dashbofrom 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+from products.exports.backend.models.subscription import Subscriptionfrom products.notebooks.backend.models import Notebookfrom products.product_analytics.backend.facade.models import Insight@@ -2221,6 +2225,52 @@ class TestSharingPublishGate(APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentassert response.json()["enabled"] is True+ @parameterized.expand(+ [+ (+ "warehouse_person_chain",+ "data_warehouse_person_property",+ "allowed_join.denied_join.id",+ "`person`.`allowed_join`.`denied_join`.`id`",+ ),+ ("warehouse_chain", "data_warehouse", "stripe.charges.amount", "`stripe`.`charges`.`amount`"),+ ("keyword_chain", "data_warehouse_person_property", "null.id", "`person`.`null`.`id`"),+ ("percent_chain", "data_warehouse", "discount%", "`discount%`"),+ ("escaped_chain", "data_warehouse", "odd`name.amount", "`odd``name`.`amount`"),+ ("event_metadata", "event_metadata", "(SELECT 1 FROM t)", "(SELECT 1 FROM t)"),+ ("person_property", "person", "email", None),+ ]+ )+ def test_breakdown_reads_the_chain_trends_resolves(+ self, _name: str, breakdown_type: str, key: str, expected: str | None+ ):+ leaves = dashboard_filter_leaves({"breakdown_filter": {"breakdown_type": breakdown_type, "breakdown": key}})++ assert leaves == ([{"type": "hogql", "key": expected}] if expected else [])++ @parameterized.expand([("dashboard_filters",), ("tile_overrides",)])+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True)+ def test_denied_dashboard_filters_saved_before_sharing_block_enabling(self, target: str, _flag):+ # Saved while unshared, so the save-time check did not run. Enabling the share must catch them.+ denied_filter = deny_warehouse_table_to_member(self.organization, self.team, self.user)+ filters = {"properties": [denied_filter]}+ dashboard = Dashboard.objects.create(+ team=self.team, created_by=self.user, filters=filters if target == "dashboard_filters" else {}+ )+ DashboardTile.objects.create(+ dashboard=dashboard,+ insight=Insight.objects.create(team=self.team, created_by=self.user),+ filters_overrides=filters if target == "tile_overrides" else {},+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/sharing", {"enabled": True}+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "denied_warehouse_table" in str(response.json())+ assert not SharingConfiguration.objects.filter(team=self.team, enabled=True).exists()+def test_system_table_denial_blocks_publishing(self):AccessControl.objects.create(team=self.team, resource="dashboard", access_level="none")self.insight.query = {@@ -2612,3 +2662,87 @@ class TestSaveTimeAccessBlock(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert "publicly shared" in str(response.json())++ @parameterized.expand(+ [+ ("dashboard_filters", "shared", status.HTTP_400_BAD_REQUEST),+ ("tile_overrides", "shared", status.HTTP_400_BAD_REQUEST),+ ("dashboard_filters", "subscription", status.HTTP_400_BAD_REQUEST),+ ("grouped_dashboard_filters", "shared", status.HTTP_400_BAD_REQUEST),+ ("grouped_tile_overrides", "shared", status.HTTP_400_BAD_REQUEST),+ ("null_dashboard_filters", "shared", status.HTTP_200_OK),+ ("breakdown_dashboard_filters", "shared", status.HTTP_400_BAD_REQUEST),+ ("metadata_breakdown_dashboard_filters", "shared", status.HTTP_400_BAD_REQUEST),+ ("list_breakdown_dashboard_filters", "shared", status.HTTP_400_BAD_REQUEST),+ ("untyped_dashboard_filters", "shared", status.HTTP_200_OK),+ ("untyped_breakdown_dashboard_filters", "shared", status.HTTP_200_OK),+ ("dashboard_filters", "none", status.HTTP_200_OK),+ ]+ )+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True)+ def test_filters_through_denied_table_on_delivered_dashboard(+ self, target: str, exposure: str, expected: int, _flag+ ):+ denied_filter = deny_warehouse_table_to_member(self.organization, self.team, self.user)+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)+ tile = DashboardTile.objects.create(dashboard=dashboard, insight=self.insight)+ if exposure == "shared":+ SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)+ elif exposure == "subscription":+ Subscription.objects.create(+ team=self.team,+ dashboard=dashboard,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ created_by=self.user,+ )+ filters = {"properties": [denied_filter]}+ sent_filters: dict[str, Any] = filters+ if target.startswith("grouped"):+ sent_filters = {"properties": [{"type": "AND", "values": [denied_filter]}]}+ elif target.startswith("null"):+ sent_filters = {"properties": None}+ elif target.startswith("breakdown"):+ sent_filters = {+ "breakdown_filter": {"breakdown_type": "data_warehouse_person_property", "breakdown": "denied_join.id"}+ }+ elif target.startswith("metadata_breakdown"):+ sent_filters = {+ "breakdown_filter": {+ "breakdown_type": "event_metadata",+ "breakdown": "(SELECT any(id) FROM denied_warehouse_table)",+ }+ }+ elif target.startswith("list_breakdown"):+ sent_filters = {+ "breakdown_filter": {+ "breakdown_type": "hogql",+ "breakdown": ["distinct_id", "(SELECT count() FROM denied_warehouse_table)"],+ }+ }+ elif target.startswith("untyped_breakdown"):+ sent_filters = {"breakdown_filter": {"breakdown_type": [], "breakdown": "denied_join.id"}}+ elif target.startswith("untyped"):+ sent_filters = {"properties": [{"type": [], "key": "x", "value": "y"}]}+ payload = (+ {"filters": sent_filters}+ if target.endswith("dashboard_filters")+ else {"tiles": [{"id": tile.id, "filters_overrides": sent_filters}]}+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}", {**payload, "name": "Renamed"}+ )++ assert response.status_code == expected, response.content+ dashboard.refresh_from_db()+ tile.refresh_from_db()+ if expected == status.HTTP_400_BAD_REQUEST:+ assert "denied_warehouse_table" in str(response.json())+ assert dashboard.name != "Renamed"+ assert dashboard.filters == {}+ assert not tile.filters_overrides+ else:+ assert dashboard.filters == sent_filtersdiff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 9eb3b23ca49c..77f0f7beed00 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -52,9 +52,14 @@ from posthog.schema import InsightVizNodefrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param+from posthog.api.property_filter_access_gate import table_blocking_property_filtersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer-from posthog.api.sharing_publish_gate import check_can_add_insight_to_shared_dashboard+from posthog.api.sharing_publish_gate import (+ check_can_add_insight_to_shared_dashboard,+ dashboard_filter_leaves,+ is_publicly_shared,+)from posthog.api.streaming import sse_streaming_responsefrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import action@@ -169,6 +174,7 @@ from products.dashboards.backend.widget_registry import (validate_widget_config,)from products.dashboards.backend.widget_specs.configs import CONVERSATIONS_RECENT_TICKETS_WIDGET_TYPE+from products.exports.backend.facade.api import dashboard_ids_with_subscriptionsfrom products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_templatefrom products.notifications.backend.facade.api import (NotificationData,@@ -2063,6 +2069,9 @@ class DashboardSerializer(DashboardMetadataSerializer):raise exceptions.PermissionDenied("Only the dashboard owner and project admins have the restriction rights required to change the dashboard's restriction level.")+ self._check_delivered_dashboard_filters_access(+ cast(User, self.context["request"].user), instance, self.initial_data+ )validated_data.pop("use_template", None) # Remove attribute if presentgrid_spacing = validated_data.pop("grid_spacing", None)@@ -2209,6 +2218,37 @@ class DashboardSerializer(DashboardMetadataSerializer):"deleted",}+ @staticmethod+ def _check_delivered_dashboard_filters_access(user: User, dashboard: Dashboard, request_data: Any) -> None:+ """Dashboard filters and tile overrides apply to every tile at render time, on the public+ link and in a subscription delivery, so a filter the editor cannot run must not reach a+ dashboard delivered either way. The check reads the whole request once, before any write,+ so a rejected request changes nothing."""+ filter_sets = [request_data.get("filters")]+ tiles = request_data.get("tiles")+ if isinstance(tiles, list):+ filter_sets += [tile.get("filters_overrides") for tile in tiles if isinstance(tile, dict)]+ # Normalized as the save normalizes them, so a filter nested in a property group is checked+ # as the leaf that gets stored.+ properties = [+ leaf+ for filters in filter_sets+ if isinstance(filters, dict)+ for leaf in dashboard_filter_leaves(DashboardSerializer._validated_filters(filters))+ ]+ if not properties:+ return+ if is_publicly_shared(dashboard):+ exposure = "publicly shared"+ elif dashboard_ids_with_subscriptions([dashboard.id]):+ exposure = "delivered by a subscription"+ else:+ return+ if table := table_blocking_property_filters(user, dashboard.team, properties):+ raise serializers.ValidationError(+ f"Can't save these filters: you don't have access to `{table}`, and this dashboard is {exposure}."+ )+@staticmethoddef _extract_display_defaults(tile_data: dict, existing_layouts: dict | None = None) -> dict:defaults = {k: tile_data[k] for k in DashboardSerializer.TILE_DISPLAY_FIELDS if k in tile_data}diff --git a/tach.toml b/tach.tomlindex 1bf91aa7246d..72ef4417d8b1 100644--- a/tach.toml+++ b/tach.toml@@ -306,6 +306,9 @@ depends_on = ["products.surveys", "products.access_control",# The canvas_app widget resolves its canvas through the canvas facade as the viewer."products.canvas",+ # Facade-only: the dashboard filter access check asks the exports facade whether a+ # subscription delivers the dashboard.+ "products.exports",]layer = "modules"