: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: check access to a view's tables before materializing it (#75758)
Alex Lider6bdcce899df3
diff --git a/posthog/rbac/query_access.py b/posthog/rbac/query_access.pynew file mode 100644index 000000000000..827f8e8b674f--- /dev/null+++ b/posthog/rbac/query_access.py@@ -0,0 +1,37 @@+"""Check that a user's access control lets them read everything a HogQL query selects from.++Enforcement lives in the schema: Database.create_for(user) leaves out tables and views the user+is denied, so resolving a query against it fails on anything they can't read - including tables+reached through nested views. Extracting table names and checking them individually would miss+those, so resolution is the only faithful definition of "what this query reads".+"""++from rest_framework import exceptions++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.errors import ExposedHogQLError, ResolutionError+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_ast_for_printing++from posthog.models import User+++def assert_user_can_read_query(query: dict | None, team_id: int, user: User, database: Database | None = None) -> None:+ """Raise PermissionDenied unless `user` can read everything `query` selects from.++ Pass `database` to reuse an already-built user-scoped schema; building one is the dominant+ cost, so callers checking several queries should build once and share it.+ """+ sql = (query or {}).get("query")+ if not isinstance(sql, str) or not sql.strip():+ raise exceptions.ValidationError("Query is missing.")++ context = HogQLContext(team_id=team_id, user=user, enable_select_queries=True, database=database)+ try:+ # Resolution is where access is enforced, so this doesn't need to print.+ prepare_ast_for_printing(node=parse_select(sql), context=context, dialect="clickhouse")+ except (ExposedHogQLError, ResolutionError) as err:+ # Surfaces "You don't have access to table `X`." for a denial; a query that no longer+ # resolves for any reason also can't be safely published, so it's refused the same way.+ raise exceptions.PermissionDenied(str(err))diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex b2ed40a8e77b..267d6dc8ae60 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -16,17 +16,20 @@ from rest_framework.exceptions import PermissionDeniedfrom rest_framework.pagination import PageNumberPaginationfrom temporalio.common import RetryPolicy+from posthog.hogql.database.database import Database+from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.models import Team, Userfrom posthog.ph_client import feature_enabled_or_false+from posthog.rbac.query_access import assert_user_can_read_queryfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selectorfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputsfrom products.data_modeling.backend.facade.api import get_declared_target, resume_nodes, suspension_state-from products.data_modeling.backend.facade.models import DAG, Edge, Node, NodeType+from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeTypefrom products.warehouse_sources.backend.facade.models import sync_frequency_interval_to_sync_frequency@@ -321,6 +324,15 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):node_ids.add(str(node.id))+ # A run materializes every node it touches (the workflow sets is_materialized), and the+ # resulting rows then resolve under each view's own access rules. So this is the same+ # declassification as enabling materialization directly, and needs the same check.+ database = Database.create_for(team_id=self.team_id, user=cast(User, req.user))+ for saved_query in DataWarehouseSavedQuery.objects.filter(+ team_id=self.team_id, node__id__in=node_ids+ ).distinct():+ assert_user_can_read_query(saved_query.query, self.team_id, cast(User, req.user), database=database)+# ExecuteDAGWorkflow skips suspended nodes, so without this the request is a silent no-op# for exactly the nodes that need it most.resume_nodes(Node.objects.filter(team_id=self.team_id, id__in=node_ids), by="manual_run")@@ -452,6 +464,12 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):status=status.HTTP_400_BAD_REQUEST,)+ # Publishes the same rows as a DAG run of this node, so it needs the same check as `run`.+ # A DB constraint guarantees non-table nodes have a saved query, so the None branch never+ # skips the check for a real node; it exists because the FK is typed as nullable.+ if node.saved_query is not None:+ assert_user_can_read_query(node.saved_query.query, self.team_id, cast(User, req.user))+start_node_materialization(node, is_v2=_is_v2_backend_enabled(cast(User, req.user), self.team))return response.Response(status=status.HTTP_200_OK)diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex bdd4c5ac2203..e9b1dae1cba5 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -43,6 +43,7 @@ from posthog.models.activity_logging.activity_log import (from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.rate_limit import MaterializationRateThrottle, RunSavedQueryRateThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin+from posthog.rbac.query_access import assert_user_can_read_queryfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.temporal.common.client import sync_connect@@ -617,6 +618,15 @@ class DataWarehouseSavedQuerySerializer(sync_frequency = validated_data.pop("sync_frequency", None)+ if sync_frequency and sync_frequency != "never":+ # Scheduling a view is the same grant as materializing it directly.+ assert_user_can_read_query(+ instance.query,+ self.context["team_id"],+ cast(User, self.context["request"].user),+ database=self.context.get("database"),+ )+dag_managed_frequency = Falseif sync_frequency and posthoganalytics.feature_enabled("data-modeling-backend-v2",@@ -1229,6 +1239,8 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeif saved_query.managed_viewset is not None:raise serializers.ValidationError("Cannot materialize a query from a managed viewset.")+ assert_user_can_read_query(saved_query.query, self.team_id, cast(User, request.user))+sync_frequency_interval = sync_frequency_to_sync_frequency_interval("24hour")should_unpause = saved_query.sync_frequency_interval is Nonediff --git a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.pyindex 0276de35b633..54274d93b29d 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py@@ -1,4 +1,5 @@import pytest+from unittest.mock import Mock, patchfrom parameterized import parameterizedfrom rest_framework import status@@ -6,8 +7,9 @@ from rest_framework import statusfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node, NodeTypefrom products.data_tools.backend.models.datawarehouse_saved_query_folder import DataWarehouseSavedQueryFolder+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTablefrom products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixintry:@@ -284,3 +286,91 @@ class TestDataWarehouseSavedQueryFolderAccessControl(WarehouseAccessControlTestMids = [f["id"] for f in response.json()]self.assertIn(str(self.folder.id), ids)self.assertNotIn(str(other_folder.id), ids)+++@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))+class TestMaterializationRequiresUnderlyingAccess(WarehouseAccessControlTestMixin):+ """Enabling materialization publishes a view's rows under the view's own access rules, so it has+ to be gated on the requester's access to what the query reads - not just on the view."""++ resource = "warehouse_objects"++ def setUp(self):+ super().setUp()+ self.credential = DataWarehouseCredential.objects.create(+ access_key="key", access_secret="secret", team=self.team+ )+ self.table = DataWarehouseTable.objects.create(+ name="restricted_table",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ credential=self.credential,+ url_pattern="s3://bucket/restricted/*",+ columns={"id": "String"},+ )+ # Authored by someone who could read the table; the restricted user only materializes it.+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="view_over_restricted",+ query={"kind": "HogQLQuery", "query": "select id from restricted_table"},+ created_by=self.user,+ )+ self._create_access_control(self.editor_user, access_level="editor")+ self._create_access_control(+ self.editor_user, resource="warehouse_table", resource_id=str(self.table.id), access_level="none"+ )+ self.client.force_login(self.editor_user)++ def _base(self) -> str:+ return f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.view.id}"++ def test_materialize_denied_when_the_query_reads_a_denied_table(self):+ response = self.client.post(f"{self._base()}/materialize/")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.view.refresh_from_db()+ self.assertFalse(self.view.is_materialized)++ def test_scheduling_denied_when_the_query_reads_a_denied_table(self):+ # Same grant by another name: a sync frequency is what actually schedules the runs.+ response = self.client.patch(f"{self._base()}/", {"sync_frequency": "24hour"}, format="json")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.view.refresh_from_db()+ self.assertIsNone(self.view.sync_frequency_interval)++ def test_running_the_dag_node_is_denied_when_the_query_reads_a_denied_table(self):+ # The run workflow sets is_materialized itself, so running a node publishes the same rows+ # that `materialize` would - a separate door onto the same declassification.+ dag = DAG.objects.create(team=self.team, name="dag")+ node = Node.objects.create(+ team=self.team, dag=dag, name=self.view.name, saved_query=self.view, type=NodeType.VIEW+ )++ response = self.client.post(+ f"/api/environments/{self.team.pk}/data_modeling_nodes/{node.id}/run/",+ {"direction": "downstream"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_materializing_the_node_is_denied_when_the_query_reads_a_denied_table(self):+ # The single-node endpoint dispatches the same materialization workflow as `run`, so it is+ # yet another door onto the same declassification.+ dag = DAG.objects.create(team=self.team, name="dag")+ node = Node.objects.create(+ team=self.team, dag=dag, name=self.view.name, saved_query=self.view, type=NodeType.VIEW+ )++ response = self.client.post(f"/api/environments/{self.team.pk}/data_modeling_nodes/{node.id}/materialize/")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_materialize_allowed_without_a_table_denial(self):+ AccessControl.objects.filter(resource="warehouse_table", resource_id=str(self.table.id)).delete()++ response = self.client.post(f"{self._base()}/materialize/")++ self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN)