: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(query): share the warehouse cache partition with shared-link viewers (#104170)
Sandy Spicer95006486279c
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.pyindex fa7a482f4cc8..b02458de36da 100644--- a/posthog/hogql_queries/access_controlled_resources.py+++ b/posthog/hogql_queries/access_controlled_resources.py@@ -6,6 +6,7 @@ from posthog.schema import (DataWarehouseNode,EntityType,FunnelsDataWarehouseNode,+ HogQLQuery,LifecycleDataWarehouseNode,RetentionEntity,)@@ -67,14 +68,23 @@ _TRANSITIVE_SYSTEM_TABLE_SCOPES: dict[str, frozenset[str]] = {}-def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str]]:+def queried_access_controlled_resources(+ query, team: "Team", *, bypassed_scopes: frozenset[str] = frozenset(), _seen_views: frozenset[str] = frozenset()+) -> Optional[set[str]]:"""The set of access-control scope names a query reads, e.g. "notebook", "warehouse_table".Empty when the query reads no access-controlled table.None when the query is malformed or unparseable.This drives query-cache partitioning: a denied object the query reads must change the cache key,otherwise a denied user could be served an allowed user's cached rows on a cache hit (the hit- short-circuits the schema strip that would otherwise raise "You don't have access to table")."""+ short-circuits the schema strip that would otherwise raise "You don't have access to table").++ `bypassed_scopes` are the scopes whose access control the principal bypasses. The parent such a+ scope falls back to through `RESOURCE_FALLBACK_MAP` is left out, because the principal never+ reaches the parent's rules; the parent still partitions the cache when a table carries that+ scope directly.++ `_seen_views` carries the saved views already walked, so views that reference each other end."""# Deferred to break the query_runner -> this module -> hogql import cycle.from posthog.hogql.database.database import get_data_warehouse_table_name # noqa: PLC0415@@ -88,7 +98,7 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415if getattr(query, "kind", None) == "AccountsTableQuery":- return _with_fallback_parents({"account"})+ return _with_fallback_parents({"account"}, bypassed_scopes)if getattr(query, "kind", None) == "AccountsQuery":expressions = [@@ -108,7 +118,7 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[straccount_scopes = {"account"}if any(any(str(segment) in _ACCOUNT_COMMUNICATION_LAZY_FIELDS for segment in field.chain) for field in fields):account_scopes.add("ticket")- return _with_fallback_parents(account_scopes)+ return _with_fallback_parents(account_scopes, bypassed_scopes)# Raw HogQL is the only query that references system.* and warehouse tables by nameif getattr(query, "kind", None) == "HogQLQuery":@@ -198,33 +208,56 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strif non_system_names & warehouse_table_names:scopes.add("warehouse_table")- view_names = set(- DataWarehouseSavedQuery.objects.filter(team_id=team.pk)+ views = list(+ DataWarehouseSavedQuery.objects.filter(team_id=team.pk, name__in=non_system_names).exclude(deleted=True)- .values_list("name", flat=True)+ .values_list("name", "query"))- if non_system_names & view_names:+ if views:scopes.add("warehouse_view")# A non-materialized view re-resolves to its underlying warehouse tables at execution.# A cache hit skips that resolution, so fold warehouse_table denials into the key too —# otherwise a user denied an underlying table could be served a cached view result.scopes.add("warehouse_table")+ # A cache hit also skips the access check on the system tables a definition reads. Materialized+ # views are walked too, since they expand to their definition unless the query reads materialized views.+ for view_name, view_query in views:+ if view_name in _seen_views:+ continue+ view_sql = view_query.get("query") if isinstance(view_query, dict) else None+ if not isinstance(view_sql, str):+ return None # a view without a definition cannot expand -> fail closed+ nested = queried_access_controlled_resources(+ HogQLQuery(query=view_sql),+ team,+ bypassed_scopes=bypassed_scopes,+ _seen_views=_seen_views | {view_name},+ )+ if nested is None:+ return None+ scopes |= nested- return _with_fallback_parents(scopes)+ return _with_fallback_parents(scopes, bypassed_scopes)# Structured insight queries (Trends/Funnels/Lifecycle/...) read warehouse data via a# DataWarehouseNode in their tree rather than by table name.- return _with_fallback_parents({"warehouse_table", "warehouse_view"}) if _references_data_warehouse(query) else set()+ return (+ _with_fallback_parents({"warehouse_table", "warehouse_view"}, bypassed_scopes)+ if _references_data_warehouse(query)+ else set()+ )-def _with_fallback_parents(scopes: set[str]) -> set[str]:+def _with_fallback_parents(scopes: set[str], bypassed_scopes: frozenset[str]) -> set[str]:"""Add the parent of every scope that resolves through one, since the parent's rules decide the- child's access.+ child's access. A bypassed child's parent is not added: the principal never reaches its rules.Only RESOURCE_FALLBACK_MAP. RESOURCE_INHERITANCE_MAP substitutes the parent's access for thechild's rather than adding rules of its own, so there is nothing extra to partition on."""- return scopes | {parent for child, parent in RESOURCE_FALLBACK_MAP.items() if child in scopes}+ return scopes | {+ parent for child, parent in RESOURCE_FALLBACK_MAP.items() if child in scopes and child not in bypassed_scopes+ }def _references_data_warehouse(value) -> bool:diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 204ba4b3aeeb..baf2fa199e12 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -3411,13 +3411,25 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):self._user_access_control = UserAccessControl(user=user, team=self.team)return self._user_access_control+ @property+ def _bypassed_access_scopes(self) -> frozenset[str]:+ """Scopes whose access control the principal skips. Service tokens and shared-link viewers bypass+ warehouse access control (see Database.create_for); real users and userless runs bypass nothing."""+ # `user` is typed Optional[User] but shared renders and service tokens pass other principals at runtime.+ user = cast("Optional[User | SyntheticUser | SharedLinkUser]", self.user)+ if user is None or isinstance(user, User):+ return frozenset()+ return WAREHOUSE_ACCESS_SCOPES+def get_cache_payload(self) -> dict:payload = super().get_cache_payload()# Partition only by the access-controlled tables this query reads that the user is restricted# from - so queries on events, persons and other non-access-controlled tables share one cache# entry (incl. userless cache warming).- queried_resources = queried_access_controlled_resources(self.query, self.team)+ queried_resources = queried_access_controlled_resources(+ self.query, self.team, bypassed_scopes=self._bypassed_access_scopes+ )if isinstance(self.user, User) and not self.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL@@ -3490,13 +3502,12 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):# Non-real principals (service tokens, shared-link viewers) are scope-gated on system tables;# partition on the readable scopes so a narrower token can't be served a broader principal's- # cached result. Warehouse scopes are excluded: these principals bypass warehouse access- # control (see Database.create_for), so warehouse tables are readable for them and listing- # them as restricted would collide with users who are genuinely denied those resources.+ # cached result. Bypassed scopes are readable for them, and listing them as restricted would+ # collide with users who are genuinely denied those resources.if not isinstance(user, User):if queried_resources is None:return ["*"]- restricted = queried_resources - user.readable_system_table_access_scopes() - WAREHOUSE_ACCESS_SCOPES+ restricted = queried_resources - user.readable_system_table_access_scopes() - self._bypassed_access_scopesreturn sorted(restricted) or Noneuser_access_control = self.user_access_controldiff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex 34961864fd73..419d2aae9313 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -1,4 +1,5 @@from posthog.test.base import BaseTest+from unittest.mock import patchfrom django.test import SimpleTestCase@@ -30,6 +31,7 @@ from posthog.hogql_queries.access_controlled_resources import (queried_access_controlled_resources,)+from products.access_control.backend.facade.user_access_control import RESOURCE_FALLBACK_MAPfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -268,6 +270,29 @@ class TestQueriedAccessControlledResources(BaseTest):# hit skips that resolution, so the user's table denials must partition the key.assert result == {"warehouse_view", "warehouse_table", "external_data_source"}+ @parameterized.expand(+ [+ (+ "system table behind two views",+ {"notebook_view": "select * from system.notebooks", "outer_view": "select * from notebook_view"},+ "select * from outer_view",+ {"warehouse_view", "warehouse_table", "external_data_source", "notebook"},+ ),+ (+ "views that reference each other",+ {"view_a": "select * from view_b", "view_b": "select * from view_a"},+ "select * from view_a",+ {"warehouse_view", "warehouse_table", "external_data_source"},+ ),+ ]+ )+ def test_view_definitions_are_walked(self, _name, views, sql, expected):+ for name, definition in views.items():+ DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": definition}+ )+ assert queried_access_controlled_resources(HogQLQuery(query=sql), self.team) == expected+def test_warehouse_and_system_scopes_combined(self):self._create_warehouse_table("my_warehouse_table")result = queried_access_controlled_resources(@@ -275,6 +300,17 @@ class TestQueriedAccessControlledResources(BaseTest):)assert result == {"warehouse_table", "notebook", "external_data_source"}+ def test_bypassed_scope_drops_only_its_own_fallback_parent(self):+ # The map has a single entry, so a second one is patched in: a principal that bypasses one child's+ # access control must still partition on the fallback parent of a child it does not bypass.+ self._create_warehouse_table("my_warehouse_table")+ query = HogQLQuery(query="select 1 from my_warehouse_table, system.notebooks")+ with patch.dict(RESOURCE_FALLBACK_MAP, {"notebook": "dashboard"}):+ result = queried_access_controlled_resources(+ query, self.team, bypassed_scopes=frozenset({"warehouse_table"})+ )+ assert result == {"warehouse_table", "notebook", "dashboard"}+def test_catalog_fetch_loads_only_name_fields(self):source = ExternalDataSource.objects.create(team=self.team,diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 82c254f41dcb..f4278b116d06 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -117,8 +117,10 @@ from posthog.slo.types import SloOutcomefrom products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlErrorfrom products.access_control.backend.models.access_control import AccessControlfrom products.customer_analytics.backend.facade.constants import DEFAULT_ACTIVITY_EVENT+from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.product_analytics.backend.facade.queries import TrendsQueryRunnerfrom products.revenue_analytics.backend.views.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT+from products.warehouse_sources.backend.facade.models import DataWarehouseTableMARKETING_ANALYTICS_SOURCES_MAP_SAMPLE = {"01977f7b-7f29-0000-a028-7275d1a767a4": {@@ -1784,6 +1786,43 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):ac_queries = [q["sql"] for q in ctx.captured_queries if "ee_accesscontrol" in q["sql"]]assert ac_queries == [], ac_queries+ @parameterized.expand(+ [+ ("warehouse table", "select * from warehouse_orders", set(), True),+ (+ "system table with the source scope",+ "select * from system.data_warehouse_sources",+ {"external_data_source"},+ False,+ ),+ ("saved view over a system table", "select * from notebook_view", {"notebook"}, False),+ ]+ )+ def test_shared_link_viewer_partitions_only_on_scopes_a_table_carries(+ self, _name, sql, expected_restricted, same_key_as_user+ ):+ # A shared-link viewer bypasses warehouse access control, so on a synced table it shares the unrestricted+ # user's entry, while a system table it cannot read, directly or through a view, keeps it on its own.+ DataWarehouseTable.objects.create(+ team=self.team,+ name="warehouse_orders",+ format="Parquet",+ url_pattern="https://bucket.s3/data/*",+ columns={},+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="notebook_view",+ query={"kind": "HogQLQuery", "query": "select * from system.notebooks"},+ )+ query = {"kind": "HogQLQuery", "query": sql}+ shared_runner = HogQLQueryRunner(query=query, team=self.team, user=_shared_link_user(self.team))+ user_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)++ restricted = set(shared_runner.get_cache_payload().get("restricted_resources") or [])+ assert restricted == expected_restricted+ assert (shared_runner.get_cache_key() == user_runner.get_cache_key()) == same_key_as_user+def test_hogql_fingerprint_partitions_only_on_queried_tables(self):# Two denied resources, but the query only reads notebooks - so only that scope partitions.self._ac(resource="notebook", access_level="none")