Skip to content

: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.

feat(warehouse): resolve table access through its source (#74201)

Alex Lider3ecbbe8fee67
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 95da06a6367c..1f59f971cd8c 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -509,6 +509,43 @@ class TestWarehouseTableAccessControl(BaseTest):
"warehouse_table", set()
)
+ def test_source_denial_reaches_its_tables_but_not_self_managed(self):
+ # The gate resolves each table through RESOURCE_FALLBACK_MAP, so a rule about a source must
+ # deny the tables it syncs while leaving tables no source owns untouched. Pins the gate's
+ # resolution call: a per-table or umbrella test passes even if the gate stops consulting the
+ # source, this one doesn't.
+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src",
+ connection_id="conn",
+ destination_id="dest",
+ source_type="Stripe",
+ prefix="stripe_",
+ )
+ sourced_table = DataWarehouseTable.objects.create(
+ name="stripe_customers",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ credential=self.credential,
+ external_data_source=source,
+ url_pattern="s3://bucket/stripe/*",
+ columns={"id": "String"},
+ )
+ self._create_ac(
+ resource="external_data_source",
+ resource_id=str(source.id),
+ access_level="none",
+ member=self._membership(),
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+
+ assert sourced_table.name in database._denied_tables
+ # allowed_table has no source, so no rule about sources may reach it.
+ assert "allowed_table" not in database._denied_tables
+
def test_warehouse_objects_resource_none_denies_all_tables(self):
self._create_ac(resource="warehouse_objects", access_level="none")
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index 7bc58f781e4d..ecedc37fdd0f 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -10,6 +10,8 @@ from posthog.schema import (
RetentionEntity,
)
+from posthog.rbac.user_access_control import RESOURCE_FALLBACK_MAP
+
if TYPE_CHECKING:
from posthog.models import Team
@@ -129,11 +131,21 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str
# otherwise a user denied an underlying table could be served a cached view result.
scopes.add("warehouse_table")
- return scopes
+ return _with_fallback_parents(scopes)
# Structured insight queries (Trends/Funnels/Lifecycle/...) read warehouse data via a
# DataWarehouseNode in their tree rather than by table name.
- return {"warehouse_table", "warehouse_view"} if _references_data_warehouse(query) else set()
+ return _with_fallback_parents({"warehouse_table", "warehouse_view"}) if _references_data_warehouse(query) else set()
+
+
+def _with_fallback_parents(scopes: set[str]) -> set[str]:
+ """Add the parent of every scope that resolves through one, since the parent's rules decide the
+ child's access.
+
+ Only RESOURCE_FALLBACK_MAP. RESOURCE_INHERITANCE_MAP substitutes the parent's access for the
+ child'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}
def _references_data_warehouse(value) -> bool:
diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.py
index 48f88edbe700..419acf872e56 100644
--- a/posthog/hogql_queries/test/test_access_controlled_resources.py
+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py
@@ -73,27 +73,27 @@ class TestQueriedAccessControlledResources(BaseTest):
(
"information_schema_tables",
"select certification from system.information_schema.tables",
- {"data_catalog", "warehouse_table", "warehouse_view"},
+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},
),
(
"information_schema_relationships",
"select reasoning from system.information_schema.relationships",
- {"data_catalog", "warehouse_table", "warehouse_view"},
+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},
),
(
"information_schema_metrics",
"select name from system.information_schema.metrics",
- {"data_catalog", "warehouse_table", "warehouse_view"},
+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},
),
(
"information_schema_certifications",
"select notes from system.information_schema.certifications",
- {"data_catalog", "warehouse_table", "warehouse_view"},
+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},
),
(
"information_schema_relationship_proposals",
"select reasoning from system.information_schema.relationship_proposals",
- {"data_catalog", "warehouse_table", "warehouse_view"},
+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},
),
# The plain schema tables expose no catalog-gated data, so they don't partition on it.
("information_schema_columns", "select * from system.information_schema.columns", set()),
@@ -118,13 +118,21 @@ class TestQueriedAccessControlledResources(BaseTest):
def test_structured_query_with_data_warehouse_series(self):
query = TrendsQuery(series=[EventsNode(event="$pageview"), self._dw_node()])
- assert queried_access_controlled_resources(query, self.team) == {"warehouse_table", "warehouse_view"}
+ assert queried_access_controlled_resources(query, self.team) == {
+ "external_data_source",
+ "warehouse_table",
+ "warehouse_view",
+ }
def test_nested_data_warehouse_node_is_detected(self):
# The node is two levels deep (actors query -> source insight -> series), so a shallow
# series-only check would miss it; the recursive walk must catch it (else the cache leaks).
query = InsightActorsQuery(source=TrendsQuery(series=[self._dw_node()]))
- assert queried_access_controlled_resources(query, self.team) == {"warehouse_table", "warehouse_view"}
+ assert queried_access_controlled_resources(query, self.team) == {
+ "external_data_source",
+ "warehouse_table",
+ "warehouse_view",
+ }
@parameterized.expand(["targetEntity", "returningEntity"])
def test_retention_query_with_data_warehouse_entity(self, entity_field):
@@ -162,7 +170,7 @@ class TestQueriedAccessControlledResources(BaseTest):
def test_warehouse_table_scope(self):
self._create_warehouse_table("my_warehouse_table")
result = queried_access_controlled_resources(HogQLQuery(query="select * from my_warehouse_table"), self.team)
- assert result == {"warehouse_table"}
+ assert result == {"external_data_source", "warehouse_table"}
def test_external_warehouse_table_matched_by_raw_name(self):
# External tables are queryable under BOTH their raw name and the prefixed
@@ -184,7 +192,7 @@ class TestQueriedAccessControlledResources(BaseTest):
assert get_data_warehouse_table_name(source, table.name) != table.name
result = queried_access_controlled_resources(HogQLQuery(query="select * from stripe_customers"), self.team)
- assert result == {"warehouse_table"}
+ assert result == {"external_data_source", "warehouse_table"}
def test_warehouse_view_scope(self):
DataWarehouseSavedQuery.objects.create(
@@ -193,14 +201,14 @@ class TestQueriedAccessControlledResources(BaseTest):
result = queried_access_controlled_resources(HogQLQuery(query="select * from my_warehouse_view"), self.team)
# warehouse_table is included too: a non-materialized view reads underlying tables, and a cache
# hit skips that resolution, so the user's table denials must partition the key.
- assert result == {"warehouse_view", "warehouse_table"}
+ assert result == {"warehouse_view", "warehouse_table", "external_data_source"}
def test_warehouse_and_system_scopes_combined(self):
self._create_warehouse_table("my_warehouse_table")
result = queried_access_controlled_resources(
HogQLQuery(query="select 1 from my_warehouse_table, system.notebooks"), self.team
)
- assert result == {"warehouse_table", "notebook"}
+ assert result == {"warehouse_table", "notebook", "external_data_source"}
def test_catalog_fetch_loads_only_name_fields(self):
source = ExternalDataSource.objects.create(
@@ -220,7 +228,7 @@ class TestQueriedAccessControlledResources(BaseTest):
# longer covers what get_data_warehouse_table_name reads (rows silently defer-load per
# row) or the default manager's externaldataschema_set prefetch leaked back in.
with self.assertNumQueries(2):
- assert queried_access_controlled_resources(query, self.team) == {"warehouse_table"}
+ assert queried_access_controlled_resources(query, self.team) == {"external_data_source", "warehouse_table"}
def test_warehouse_table_of_another_team_not_matched(self):
from posthog.models import Team
diff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.py
index fc0371a41e19..51fb6c67edcb 100644
--- a/posthog/rbac/test/test_user_access_control.py
+++ b/posthog/rbac/test/test_user_access_control.py
@@ -23,6 +23,7 @@ from posthog.rbac.user_access_control import (
from products.dashboards.backend.models.dashboard import Dashboard
from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
try:
from ee.models.rbac.access_control import AccessControl
@@ -2046,3 +2047,99 @@ class TestBlockedResourceIdsByScope(BaseTest):
organization_member=self.membership,
)
assert self._blocked() == {"10"}
+
+
+class TestUserAccessControlFallbackParent(BaseUserAccessControlTest):
+ """Resolution through RESOURCE_FALLBACK_MAP: a synced table falls back to the source that syncs it."""
+
+ def setUp(self):
+ super().setUp()
+ self.membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ self.source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id="src",
+ connection_id="conn",
+ destination_id="dest",
+ source_type="Stripe",
+ prefix="test",
+ )
+ self.sourced_table = DataWarehouseTable.objects.create(
+ name="customers", format="Parquet", team=self.team, external_data_source=self.source, columns={}
+ )
+ self.self_managed_table = DataWarehouseTable.objects.create(
+ name="uploads", format="Parquet", team=self.team, columns={}
+ )
+
+ def _apply(self, rules, table):
+ # The four places a rule can be written about this table. The ladder exists because these are
+ # different statements: "this source" is not "all sources", and neither is "all tables".
+ targets = {
+ "this_table": ("warehouse_table", str(table.id)),
+ "this_source": ("external_data_source", str(self.source.id)),
+ "all_tables": ("warehouse_objects", None),
+ "all_sources": ("external_data_source", None),
+ }
+ for target, level in rules.items():
+ resource, resource_id = targets[target]
+ self._create_access_control(
+ resource=resource, resource_id=resource_id, access_level=level, organization_member=self.membership
+ )
+ self._clear_uac_caches()
+
+ def _level(self, table):
+ return self.user_access_control.get_user_access_level(table)
+
+ @parameterized.expand(
+ [
+ # A rule about a source reaches the tables it syncs, written either way round.
+ ("source_reaches_its_tables", {"this_source": "none"}, "none"),
+ ("all_sources_reaches_sourced_tables", {"all_sources": "none"}, "none"),
+ # The table's own rule is more specific than its source's, in both directions.
+ ("table_grant_beats_source_deny", {"this_source": "none", "this_table": "editor"}, "editor"),
+ ("table_deny_beats_source_grant", {"this_source": "editor", "this_table": "none"}, "none"),
+ # "All tables" is more specific than "all sources", so a broad table grant isn't capped
+ # by a source denial - which lets an editor on tables sync a schema they only view.
+ ("all_tables_beats_all_sources", {"all_sources": "none", "all_tables": "viewer"}, "viewer"),
+ # ...and one named source is more specific than "all tables".
+ ("one_source_beats_all_tables", {"this_source": "none", "all_tables": "editor"}, "none"),
+ ]
+ )
+ def test_sourced_table_resolution(self, _name, rules, expected):
+ self._apply(rules, self.sourced_table)
+
+ assert self._level(self.sourced_table) == expected
+
+ @parameterized.expand(
+ [
+ # A self-managed table has no source, so no rule about sources may reach it. Without this
+ # skip, restricting sources would silently lock every S3 table and direct connection that
+ # no source has ever touched.
+ ("all_sources_cannot_reach_it", {"all_sources": "none"}, "editor"),
+ ("one_source_cannot_reach_it", {"this_source": "none"}, "editor"),
+ # The rules that do apply to it still govern it - the skip isn't switching access off.
+ ("all_tables_still_governs_it", {"all_tables": "none"}, "none"),
+ ("its_own_rule_still_governs_it", {"this_table": "viewer"}, "viewer"),
+ ]
+ )
+ def test_self_managed_table_skips_the_source(self, _name, rules, expected):
+ self._apply(rules, self.self_managed_table)
+
+ assert self._level(self.self_managed_table) == expected
+
+ def test_source_denial_does_not_leak_across_sources(self):
+ other_source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id="src2",
+ connection_id="conn2",
+ destination_id="dest2",
+ source_type="Stripe",
+ prefix="other",
+ )
+ other_table = DataWarehouseTable.objects.create(
+ name="invoices", format="Parquet", team=self.team, external_data_source=other_source, columns={}
+ )
+ self._apply({"this_source": "none"}, self.sourced_table)
+
+ assert self._level(self.sourced_table) == "none"
+ assert self._level(other_table) == "editor"
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 2372f9cc0551..5dc46a788885 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -3,10 +3,10 @@ from collections import defaultdict
from collections.abc import Sequence
from dataclasses import dataclass
from enum import Enum
-from functools import cached_property
+from functools import cache, cached_property
from typing import TYPE_CHECKING, Any, Literal, Optional, cast, get_args
-from django.db.models import Case, CharField, Exists, F, Model, OuterRef, Q, QuerySet, Value, When
+from django.db.models import Case, CharField, Exists, F, ForeignKey, Model, OuterRef, Q, QuerySet, Value, When
from django.db.models.functions import Cast
from opentelemetry import trace
@@ -123,6 +123,19 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
"vision_action": "replay_scanner",
}
+# Unlike RESOURCE_INHERITANCE_MAP above, where the child has no access of its own and just uses the
+# parent's, this checks the child's own access first and falls back to the parent.
+# For example:
+# this table (object) -> this source (object) -> all tables (resource) -> all sources (resource) -> default
+#
+# The parent's id is read off the child's foreign key to it (DataWarehouseTable.external_data_source),
+# so an entry only works when that foreign key exists. A null one means no parent, and the object
+# skips it rather than inheriting: a self-managed table has no source, so no rule about sources
+# may reach it.
+RESOURCE_FALLBACK_MAP: dict[APIScopeObject, APIScopeObject] = {
+ "warehouse_table": "external_data_source",
+}
+
WAREHOUSE_ACCESS_SCOPES: frozenset[str] = frozenset(
{
"warehouse_objects",
@@ -464,6 +477,35 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return cast(APIScopeObject, name)
+@cache
+def _fallback_parent_field(model: type[Model], parent_resource: APIScopeObject) -> Optional[str]:
+ """Attribute holding the id of `model`'s `parent_resource` foreign key, if it has one.
+
+ Found by introspection rather than a declared field map so the relationship is read off the
+ schema that already defines it. Cached because it depends only on the model class.
+ """
+ for field in model._meta.get_fields():
+ # ForeignKey covers OneToOneField too, and excludes the reverse relations get_fields() also returns.
+ if not isinstance(field, ForeignKey) or field.related_model is None:
+ continue
+ if model_to_resource(cast(Model, field.related_model)) == parent_resource:
+ return field.attname
+ return None
+
+
+def fallback_parent_object_id(obj: Model, parent_resource: APIScopeObject) -> Optional[str]:
+ """Id of the object `obj` falls back to for access, or None when it has no such parent.
+
+ None is what makes a self-managed table skip its source tiers rather than inherit from a
+ source it doesn't have.
+ """
+ field = _fallback_parent_field(type(obj), parent_resource)
+ if field is None:
+ return None
+ parent_id = getattr(obj, field, None)
+ return str(parent_id) if parent_id is not None else None
+
+
class UserAccessControl:
"""
UserAccessControl provides functions for checking unified access to all resources and objects from a Project level downwards.
@@ -1302,28 +1344,52 @@ class UserAccessControl:
).access_level
def _object_access_level_from_rows(
- self, resource: APIScopeObject, object_access_controls: list[_AccessControl], explicit: bool = False
+ self,
+ resource: APIScopeObject,
+ object_access_controls: list[_AccessControl],
+ explicit: bool = False,
+ fallback_parent_id: Optional[str] = None,
) -> Optional[AccessControlLevel]:
- """Row-based object access resolution: explicit (role/member) object rows win, then
+ """Row-based object access resolution, most specific rule first: explicit (role/member) object
+ rows, then the fallback parent's object rows, then resource-level rows, then the parent's
resource-level rows, then default object rows, then the resource default. Shared by
`get_user_access_level` and `bulk_object_access_levels`.
"""
+ parent = RESOURCE_FALLBACK_MAP.get(resource) if fallback_parent_id else None
+
explicit_rows = [
ac for ac in object_access_controls if ac.role_id is not None or ac.organization_member_id is not None
]
if explicit_rows:
return self._highest_access_level_from_rows(resource, explicit_rows)
+ if parent:
+ parent_rows = self._get_access_controls(
+ self._access_controls_filters_for_object(parent, cast(str, fallback_parent_id))
+ )
+ if parent_rows:
+ return self._highest_access_level_from_rows(parent, parent_rows)
+
if self.has_access_levels_for_resource(resource):
access_level_for_resource = self.access_level_for_resource(resource)
if access_level_for_resource:
return access_level_for_resource
+ if parent and self.has_access_levels_for_resource(parent):
+ access_level_for_parent = self.access_level_for_resource(parent)
+ if access_level_for_parent:
+ return access_level_for_parent
+
if object_access_controls:
return self._highest_access_level_from_rows(resource, object_access_controls)
return None if explicit else default_access_level(resource)
+ @staticmethod
+ def _fallback_parent_id(obj: Model, resource: APIScopeObject) -> Optional[str]:
+ parent = RESOURCE_FALLBACK_MAP.get(resource)
+ return fallback_parent_object_id(obj, parent) if parent else None
+
def get_user_access_level(self, obj: Model, explicit=False) -> Optional[AccessControlLevel]:
resource = model_to_resource(obj)
if not resource:
@@ -1337,7 +1403,12 @@ class UserAccessControl:
object_access_controls = self._get_access_controls(
self._access_controls_filters_for_object(resource, str(obj.id)) # type: ignore
)
- return self._object_access_level_from_rows(resource, object_access_controls, explicit=explicit)
+ return self._object_access_level_from_rows(
+ resource,
+ object_access_controls,
+ explicit=explicit,
+ fallback_parent_id=self._fallback_parent_id(obj, resource),
+ )
def bulk_object_access_levels(
self,
@@ -1350,6 +1421,12 @@ class UserAccessControl:
`get_user_access_level`, but object rows come from the bulk preload grouped in memory,
so no per-object queries are issued.
"""
+ # Warehouse tables aren't listed by either caller (search, the file tree). If that changes, load
+ # the parent ids here too, so access is checked against the source and not just the table.
+ parent = RESOURCE_FALLBACK_MAP.get(resource)
+ if parent:
+ raise NotImplementedError(f"bulk_object_access_levels cannot resolve `{resource}` through `{parent}`")
+
if not objects:
return {}