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: HogQL object-level access control (#49264)

Alex Lider051af1390f15
diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.py
index 33b60837eef6..4d8d67694521 100644
--- a/posthog/hogql/ast.py
+++ b/posthog/hogql/ast.py
@@ -1022,6 +1022,11 @@ class Lambda(Expr):
@dataclass(kw_only=True, slots=True)
class Constant(Expr):
value: Any
+ # When True, the SQL printer routes this constant through
+ # ``HogQLContext.add_sensitive_value`` so the placeholder key gets the
+ # ``_sensitive`` suffix and ``substitute_params_for_display`` redacts the
+ # value to ``[HIDDEN]``
+ is_sensitive: bool | None = None
# Internal ClickHouse-printer hint, not part of the logical AST. Set True only by the physical pass, only for its
# fixed scrubbing sentinels (the nullIf ''/'null' literals, the quote-trim regex, the 'true'/'false' the property
# group stores booleans as), to render them inline instead of as a bound parameter — matching the inline string the
diff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.py
index e5b514133059..1054ce44e7e8 100644
--- a/posthog/hogql/database/postgres_table.py
+++ b/posthog/hogql/database/postgres_table.py
@@ -1,3 +1,4 @@
+from functools import cache
from typing import Optional
from django.conf import settings
@@ -11,6 +12,16 @@ from posthog.person_db_router import PERSONS_DB_MODELS
from posthog.scopes import APIScopeObject
+@cache
+def _pk_column_for_pg_table(postgres_table_name: str) -> Optional[str]:
+ """Look up the primary key column from the actual DB schema. Cached per process.
+ Returns None for tables with composite primary key."""
+ from django.db import connection
+
+ with connection.cursor() as cursor:
+ return connection.introspection.get_primary_key_column(cursor, postgres_table_name)
+
+
def build_function_call(postgres_table_name: str, context: Optional[HogQLContext] = None):
raw_params: dict[str, str] = {}
@@ -65,11 +76,25 @@ class PostgresTable(FunctionCallTable):
requires_args: bool = False
postgres_table_name: str
access_scope: Optional[APIScopeObject] = None
+ # Column that object-level access control filters ids against.
+ # Defaults to the primary key, which is correct when the table's rows ARE the access-controlled object
+ # (e.g. system.dashboards). Child tables that only expose a parent object's data set this
+ # to the foreign key pointing at that parent (e.g. system.dashboard_tiles -> "dashboard_id"),
+ # so denying the parent also hides its child rows.
+ access_control_id_field: Optional[str] = None
predicates: list[Expr] = []
def get_predicates(self) -> list[Expr]:
return self.predicates
+ @property
+ def primary_key(self) -> Optional[str]:
+ return _pk_column_for_pg_table(self.postgres_table_name)
+
+ @property
+ def access_control_id(self) -> Optional[str]:
+ return self.access_control_id_field or self.primary_key
+
def to_printed_hogql(self):
return escape_hogql_identifier(self.name)
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 3f7e3a8214db..5648097c20cf 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -228,6 +228,8 @@ dashboard_tiles: PostgresTable = PostgresTable(
name="dashboard_tiles",
postgres_table_name="posthog_dashboardtile",
access_scope="dashboard",
+ # Child of dashboard: object-level access control applies to the parent dashboard, not the tile's own id.
+ access_control_id_field="dashboard_id",
fields={
"id": IntegerDatabaseField(name="id"),
"team_id": IntegerDatabaseField(name="team_id"),
@@ -362,6 +364,8 @@ source_schemas: PostgresTable = PostgresTable(
name="source_schemas",
postgres_table_name="posthog_externaldataschema",
access_scope="external_data_source",
+ # Child of external_data_source: object-level access control applies to the parent source, not the schema's own id.
+ access_control_id_field="source_id",
fields={
"id": StringDatabaseField(name="id"),
"team_id": IntegerDatabaseField(name="team_id"),
@@ -385,6 +389,8 @@ source_sync_jobs: PostgresTable = PostgresTable(
name="source_sync_jobs",
postgres_table_name="posthog_externaldatajob",
access_scope="external_data_source",
+ # Child of external_data_source: object-level access control applies to the parent source, not the job's own id.
+ access_control_id_field="pipeline_id",
fields={
"id": StringDatabaseField(name="id"),
"team_id": IntegerDatabaseField(name="team_id"),
@@ -404,6 +410,8 @@ endpoint_versions: PostgresTable = PostgresTable(
name="data_modeling_endpoint_versions",
postgres_table_name="endpoints_endpointversion",
access_scope="endpoint",
+ # Child of endpoint: object-level access control applies to the parent endpoint, not the version's own id.
+ access_control_id_field="endpoint_id",
fields={
"id": StringDatabaseField(name="id"),
"team_id": IntegerDatabaseField(name="team_id"),
@@ -1037,6 +1045,8 @@ trace_review_scores: PostgresTable = PostgresTable(
name="trace_review_scores",
postgres_table_name="llm_analytics_tracereviewscore",
access_scope="llm_analytics",
+ # Child of trace_review: object-level access control applies to the parent review, not the score's own id.
+ access_control_id_field="review_id",
fields={
"id": UUIDDatabaseField(name="id"),
"team_id": IntegerDatabaseField(name="team_id"),
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index 70cb648f3cbf..c562b7041f3c 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -3,6 +3,8 @@ from typing import Literal
from posthog.test.base import BaseTest
+from django.apps import apps
+from django.db.models import ForeignKey, Model
from django.test import SimpleTestCase
from django.urls import get_resolver
@@ -29,13 +31,55 @@ from posthog.rbac.user_access_control import RESOURCE_INHERITANCE_MAP
from ee.api.rbac.access_control import AccessControlViewSetMixin
+ALL_POSTGRES_SYSTEM_TABLES: list[tuple[str, PostgresTable]] = [
+ (name, node.table) for name, node in SystemTables().children.items() if isinstance(node.table, PostgresTable)
+]
_SCOPED_SYSTEM_TABLES: dict[str, PostgresTable] = {
- name: node.table
- for name, node in SystemTables().children.items()
- if isinstance(node.table, PostgresTable) and node.table.access_scope is not None
+ name: table for name, table in ALL_POSTGRES_SYSTEM_TABLES if table.access_scope is not None
}
+@lru_cache(maxsize=1)
+def _object_grant_registry() -> dict[type[Model], str]:
+ """Map every model that is object-restrictable to the resource (`scope_object`) its
+ per-object grants are stored under. Derived from `AccessControlViewSetMixin` viewsets —
+ the authoritative source of which resources can hold object-level grants. Loading the
+ full URLconf forces all viewsets (including product ones) to be imported first."""
+ _ = get_resolver().url_patterns
+
+ def all_subclasses(cls: type) -> set[type]:
+ subs: set[type] = set()
+ for sub in cls.__subclasses__():
+ subs.add(sub)
+ subs |= all_subclasses(sub)
+ return subs
+
+ registry: dict[type[Model], str] = {}
+ for viewset in all_subclasses(AccessControlViewSetMixin):
+ scope = getattr(viewset, "scope_object", None)
+ if not isinstance(scope, str) or scope == "INTERNAL":
+ continue
+ queryset = getattr(viewset, "queryset", None)
+ model = queryset.model if queryset is not None else None
+ if model is None:
+ meta = getattr(getattr(viewset, "serializer_class", None), "Meta", None)
+ model = getattr(meta, "model", None)
+ if model is not None:
+ registry[model] = scope
+ return registry
+
+
+@lru_cache(maxsize=1)
+def _model_by_pg_table() -> dict[str, type[Model]]:
+ # Skip proxy models — they share their base's db_table and would shadow the concrete model.
+ mapping: dict[str, type[Model]] = {}
+ for model in apps.get_models():
+ if model._meta.proxy:
+ continue
+ mapping.setdefault(model._meta.db_table, model)
+ return mapping
+
+
@lru_cache(maxsize=1)
def _object_grant_scopes() -> frozenset[str]:
"""Resources under which object-level access control grants can actually be stored,
@@ -345,6 +389,84 @@ class TestPostgresTable(BaseTest):
)
+class TestPostgresTablePrimaryKey(BaseTest):
+ """Validate primary_key auto-detection and access_scope constraints."""
+
+ @parameterized.expand(_SCOPED_SYSTEM_TABLES.items())
+ def test_tables_with_access_scope_have_single_column_pk(self, table_name, table):
+ """Object-level access control requires a single-column PK to filter by."""
+ assert table.primary_key is not None, (
+ f"system.{table_name} has access_scope='{table.access_scope}' "
+ f"but no single-column primary key (composite PK). "
+ f"Object-level access control requires a single-column PK."
+ )
+
+
+class TestObjectAccessControlIdField(SimpleTestCase):
+ """Every scoped system table must filter object-level denials against the correct column.
+
+ A table whose rows ARE the access-controlled object filters its primary key (the default).
+ A child table that only exposes a parent object's data must set `access_control_id_field`
+ to the foreign key pointing at that parent — otherwise a member denied the parent could
+ still read the child rows through HogQL. The set of object-restrictable resources is
+ derived from `AccessControlViewSetMixin` viewsets, so new restrictable models or child
+ tables fail this test until their `access_control_id_field` is declared correctly."""
+
+ @parameterized.expand(ALL_POSTGRES_SYSTEM_TABLES)
+ def test_access_control_id_field_targets_the_restricted_object(self, table_name, table) -> None:
+ if table.access_scope is None:
+ self.assertIsNone(
+ table.access_control_id_field,
+ f"system.{table_name} has no access_scope, so access_control_id_field is meaningless — remove it.",
+ )
+ return
+
+ model = _model_by_pg_table().get(table.postgres_table_name)
+ self.assertIsNotNone(model, f"could not resolve a Django model for system.{table_name}")
+
+ scope = table.access_scope
+ registry = _object_grant_registry()
+ # Models whose per-object grants are stored under this table's scope.
+ target_models = {m for m, s in registry.items() if s == scope}
+
+ # This table's rows ARE the access-controlled object → filter the primary key (default).
+ if model in target_models:
+ self.assertIsNone(
+ table.access_control_id_field,
+ f"system.{table_name} is itself access-controlled under '{scope}'; it must filter its "
+ f"primary key — leave access_control_id_field unset.",
+ )
+ return
+
+ # The scope has no object-restrictable models → no per-object grants ever exist → the
+ # guard short-circuits on an empty deny set. No id override is meaningful.
+ if not target_models:
+ self.assertIsNone(
+ table.access_control_id_field,
+ f"system.{table_name} scope '{scope}' has no object-level grants; remove access_control_id_field.",
+ )
+ return
+
+ # Child table: it must filter the FK pointing at one of the restricted parent models.
+ fk_columns = sorted(
+ field.attname
+ for field in model._meta.get_fields() # type: ignore[union-attr]
+ if isinstance(field, ForeignKey) and field.related_model in target_models
+ )
+ self.assertTrue(
+ fk_columns,
+ f"system.{table_name} is scoped to the object-restrictable resource '{scope}' but is neither "
+ f"one of its objects ({sorted(m.__name__ for m in target_models)}) nor has a foreign key to one. "
+ f"It may leak access-controlled rows — add the right FK or reconsider its access_scope.",
+ )
+ self.assertIn(
+ table.access_control_id_field,
+ fk_columns,
+ f"system.{table_name} is a child of '{scope}'; set access_control_id_field to the FK pointing at "
+ f"its parent (one of {fk_columns}), got {table.access_control_id_field!r}.",
+ )
+
+
class TestSystemTableAccessScope(SimpleTestCase):
"""A system table's `access_scope` must be the concrete resource under which object-level
access control grants are stored — never a pure umbrella parent.
diff --git a/posthog/hogql/printer/access_control.py b/posthog/hogql/printer/access_control.py
new file mode 100644
index 000000000000..fa82b3774a40
--- /dev/null
+++ b/posthog/hogql/printer/access_control.py
@@ -0,0 +1,43 @@
+from typing import Optional
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.postgres_table import PostgresTable
+
+
+def build_access_control_guard(
+ table: PostgresTable,
+ table_type: ast.TableOrSelectType,
+ context: HogQLContext,
+) -> Optional[ast.Expr]:
+ """
+ Build the WHERE clause AST node that filters out access-controlled resource IDs
+ for the current user. Returns None if no filtering is needed.
+
+ Deny set lives on UserAccessControl.blocked_resource_ids_by_scope — single source
+ of truth, shared with the cache-key fingerprint in query_runner.py.
+ """
+ resource = table.access_scope
+ if not resource:
+ return None
+
+ id_field = table.access_control_id
+ if id_field is None:
+ return None
+
+ if not context.database or not context.database.user_access_control:
+ return None
+
+ blocked_ids = context.database.user_access_control.blocked_resource_ids_by_scope.get(resource, set())
+ if not blocked_ids:
+ return None
+
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=ast.Call(
+ name="toString",
+ args=[ast.Field(chain=[id_field], type=ast.FieldType(name=id_field, table_type=table_type))],
+ ),
+ right=ast.Constant(value=sorted(blocked_ids), is_sensitive=True),
+ type=ast.BooleanType(),
+ )
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 6c474d591a6c..ac7986713211 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -518,6 +518,16 @@ class BasePrinter(Visitor[str]):
scope = ast.SelectQueryType(tables={"t": node_type})
return [resolve_types(clone_expr(pred), self.context, self.DIALECT_NAME, [scope]) for pred in predicates]
+ def _ensure_access_control_where_clause(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ) -> ast.Expr | None:
+ """Object-level access-control guard for this table, or None.
+ Override it per dialect: ClickHouse enforces, Postgres/DuckDB/HogQL no-op.
+ """
+ raise NotImplementedError("BasePrinter._ensure_access_control_where_clause not overridden")
+
def _print_table_ref(self, table_type: ast.TableType | ast.LazyTableType, node: ast.JoinExpr) -> str:
"""Print a table reference. Fail-fast by default: each dialect must override.
@@ -539,8 +549,8 @@ class BasePrinter(Visitor[str]):
def visit_join_expr(self, node: ast.JoinExpr) -> JoinExprResponse:
# Constraints to add to the SELECT's WHERE clause (for most join types)
extra_where: ast.Expr | None = None
- # For LEFT JOINs, team_id goes in ON instead of WHERE to preserve NULL rows
- team_id_for_on_clause: ast.Expr | None = None
+ # For LEFT JOINs, guards (team_id + access control) go in ON instead of WHERE to preserve NULL rows
+ on_clause_guard: ast.Expr | None = None
join_strings = []
if node.join_type is not None:
@@ -566,23 +576,31 @@ class BasePrinter(Visitor[str]):
self._collect_table_top_level_settings(table_type.table)
- # :IMPORTANT: Ensures team_id filtering on every table. For LEFT JOINs, we add it to the
- # ON clause (not WHERE) to preserve LEFT JOIN semantics - otherwise NULL rows get filtered out.
+ # :IMPORTANT: Ensures team_id and resource_id filtering on every table.
+ # For LEFT JOINs, we add guards to ON (not WHERE) to preserve NULL rows.
team_id_expr = self._ensure_team_id_where_clause(table_type, node.type)
+ access_control_expr = self._ensure_access_control_where_clause(table_type, node.type)
+
+ combined_guard: ast.Expr | None = None
+ if team_id_expr and access_control_expr:
+ combined_guard = ast.And(exprs=[team_id_expr, access_control_expr], type=ast.BooleanType())
+ else:
+ combined_guard = team_id_expr or access_control_expr
+
is_left_join = node.join_type is not None and "LEFT" in node.join_type
- if is_left_join and team_id_expr is not None and node.constraint is not None:
- team_id_for_on_clause = team_id_expr
+ if is_left_join and combined_guard is not None and node.constraint is not None:
+ on_clause_guard = combined_guard
else:
- extra_where = team_id_expr
+ extra_where = combined_guard
# Apply table-level predicates (e.g., date filters on PostgresTable).
predicate_exprs = self._get_table_predicates(table_type, node.type)
for pred in predicate_exprs:
if is_left_join and node.constraint is not None:
- if team_id_for_on_clause is None:
- team_id_for_on_clause = pred
+ if on_clause_guard is None:
+ on_clause_guard = pred
else:
- team_id_for_on_clause = ast.And(exprs=[team_id_for_on_clause, pred])
+ on_clause_guard = ast.And(exprs=[on_clause_guard, pred])
else:
if extra_where is None:
extra_where = pred
@@ -668,8 +686,8 @@ class BasePrinter(Visitor[str]):
# Allowlist gate against `setattr`-bypass — the printer interpolates `constraint_type` verbatim.
if node.constraint.constraint_type not in ast.VALID_JOIN_CONSTRAINT_TYPES:
raise QueryError(f"Invalid join constraint type: {node.constraint.constraint_type!r}")
- if team_id_for_on_clause is not None:
- combined_constraint = ast.And(exprs=[team_id_for_on_clause, node.constraint.expr])
+ if on_clause_guard is not None:
+ combined_constraint = ast.And(exprs=[on_clause_guard, node.constraint.expr])
join_strings.append(f"{node.constraint.constraint_type} {self.visit(combined_constraint)}")
else:
join_strings.append(f"{node.constraint.constraint_type} {self.visit(node.constraint)}")
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 249550182440..8f301753164a 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -435,6 +435,8 @@ class ClickHousePrinter(BasePrinter):
return value
else:
# Strings, lists, tuples, and any other random datatype printed in ClickHouse.
+ if node.is_sensitive:
+ return self.context.add_sensitive_value(node.value)
return self.context.add_value(node.value)
def visit_interpolate_expr(self, node: ast.InterpolateExpr):
@@ -817,6 +819,32 @@ class ClickHousePrinter(BasePrinter):
):
return team_id_guard_for_table(node_type, self.context)
+ def _ensure_access_control_where_clause(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ):
+ """Add access control guard for system tables"""
+ from posthog.hogql.database.postgres_table import PostgresTable
+ from posthog.hogql.printer.access_control import build_access_control_guard
+
+ if node_type is None:
+ return None
+ if not isinstance(table_type.table, PostgresTable):
+ return None
+ if not self.context.database or not self.context.database.user_access_control:
+ return None
+
+ # Only apply access control to tables registered under the system namespace
+ system_node = self.context.database.tables.children.get("system")
+ if not system_node or table_type.table.name not in system_node.children:
+ return None
+
+ if not table_type.table.primary_key:
+ return None
+
+ return build_access_control_guard(table_type.table, node_type, self.context)
+
def _print_table_ref(self, table_type: ast.TableType | ast.LazyTableType, node: ast.JoinExpr) -> str:
sql = table_type.table.to_printed_clickhouse(self.context)
table = table_type.table
diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.py
index dd31c4ca4d7b..8961f315f88f 100644
--- a/posthog/hogql/printer/hogql.py
+++ b/posthog/hogql/printer/hogql.py
@@ -51,6 +51,14 @@ class HogQLPrinter(BasePrinter):
):
return
+ def _ensure_access_control_where_clause(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ) -> ast.Expr | None:
+ # HogQL output never produces a real query, so no access-control guard is injected.
+ return None
+
def _print_table_ref(self, table_type: ast.TableType | ast.LazyTableType, node: ast.JoinExpr) -> str:
return table_type.table.to_printed_hogql()
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index fb6f7eff620d..e25b9a4b0ecd 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -394,6 +394,14 @@ class PostgresPrinter(BasePrinter):
# Team ID filtering is not required for Postgres queries
pass
+ def _ensure_access_control_where_clause(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ):
+ # Access control is not implemented for Postgres dialect yet
+ return None
+
def _print_identifier(self, name: str) -> str:
if len(name) > 63 and "__" in name:
name = self._truncate_identifier(name)
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 0631e219939e..f3c835ab491a 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -1,10 +1,12 @@
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
+from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.system import SystemTables
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
+from posthog.hogql.printer.access_control import build_access_control_guard
from posthog.models import OrganizationMembership
@@ -91,6 +93,152 @@ class TestAccessControlSystemTables(BaseTest):
assert "cohorts" in system_node.children
+class TestAccessControlGuard(BaseTest):
+ """Test object-level access control guard generation."""
+
+ def _get_dashboards_table(self, database: Database):
+ from posthog.hogql.database.postgres_table import PostgresTable
+
+ system_node = database.tables.children.get("system")
+ assert system_node is not None
+ dashboards_node = system_node.children.get("dashboards")
+ assert dashboards_node is not None
+ table = dashboards_node.get()
+ assert isinstance(table, PostgresTable)
+ return table
+
+ def test_build_access_control_guard_returns_none_for_admin(self):
+ """Org admins should not have an access control guard."""
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.ADMIN
+ membership.save()
+
+ context = HogQLContext(team_id=self.team.pk, team=self.team, user=self.user)
+ database = Database.create_for(team=self.team, user=self.user)
+ context.database = database
+
+ table = self._get_dashboards_table(database)
+ table_type = ast.TableType(table=table)
+
+ guard = build_access_control_guard(table, table_type, context)
+ assert guard is None
+
+ def test_build_access_control_guard_returns_none_without_user(self):
+ """Without user context, no guard should be generated."""
+ from posthog.hogql.database.schema.system import dashboards
+
+ context = HogQLContext(team_id=self.team.pk, team=self.team, user=None)
+ database = Database.create_for(team=self.team, user=None)
+ context.database = database
+
+ table_type = ast.TableType(table=dashboards)
+
+ guard = build_access_control_guard(dashboards, table_type, context)
+ assert guard is None
+
+ def test_blocked_ids_bind_as_single_sensitive_placeholder(self):
+ """
+ The deny list compiles to one ``%(..._sensitive)s`` placeholder bound to a list,
+ not N per-ID placeholders. Mirrors ``JSONDropKeys`` in property-level AC.
+ """
+ from posthog.hogql.parser import parse_select
+
+ from posthog.clickhouse.client.escape import substitute_params_for_display
+ from posthog.constants import AvailableFeature
+
+ from ee.models import AccessControl
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ for resource_id in ("dash-1", "dash-2", "dash-3"):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id=resource_id,
+ access_level="none",
+ )
+
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ user=self.user,
+ enable_select_queries=True,
+ )
+ prepared = prepare_ast_for_printing(
+ parse_select("SELECT id, name FROM system.dashboards"),
+ context=context,
+ dialect="clickhouse",
+ )
+ assert prepared is not None
+ sql = print_prepared_ast(prepared, context=context, dialect="clickhouse")
+
+ sensitive_keys = [k for k in context.values if k.endswith("_sensitive")]
+ deny_keys = [k for k in sensitive_keys if isinstance(context.values[k], list)]
+ assert len(deny_keys) == 1, f"expected exactly one sensitive list placeholder, got {sensitive_keys!r}"
+ deny_key = deny_keys[0]
+ assert context.values[deny_key] == ["dash-1", "dash-2", "dash-3"]
+ assert f"notIn(toString(system__dashboards.id), %({deny_key})s)" in sql
+ # No raw IDs leaked into the SQL template
+ for raw in ("'dash-1'", "'dash-2'", "'dash-3'"):
+ assert raw not in sql
+
+ # And the display renderer scrubs them.
+ rendered = substitute_params_for_display(sql, context.values)
+ for raw in ("dash-1", "dash-2", "dash-3"):
+ assert raw not in rendered
+ assert "[HIDDEN]" in rendered
+
+ def test_child_table_guard_filters_parent_fk_not_own_pk(self):
+ # system.dashboard_tiles inherits the "dashboard" scope and sets access_control_id_field="dashboard_id".
+ # Denying a dashboard must filter the tile rows on their dashboard_id FK, not the tile's own id -
+ # otherwise a denied dashboard's tiles leak (the deny set holds dashboard ids, never tile ids).
+ from posthog.hogql.parser import parse_select
+
+ from posthog.constants import AvailableFeature
+
+ from ee.models import AccessControl
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id="dash-99", access_level="none")
+
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ user=self.user,
+ enable_select_queries=True,
+ )
+ prepared = prepare_ast_for_printing(
+ parse_select("SELECT id FROM system.dashboard_tiles"),
+ context=context,
+ dialect="clickhouse",
+ )
+ assert prepared is not None
+ sql = print_prepared_ast(prepared, context=context, dialect="clickhouse")
+
+ deny_keys = [k for k in context.values if k.endswith("_sensitive") and isinstance(context.values[k], list)]
+ assert len(deny_keys) == 1
+ deny_key = deny_keys[0]
+ assert context.values[deny_key] == ["dash-99"]
+ # The guard targets the parent FK, never the child's own primary key.
+ assert f"notIn(toString(system__dashboard_tiles.dashboard_id), %({deny_key})s)" in sql
+ assert "notIn(toString(system__dashboard_tiles.id)" not in sql
+
+
class TestDeniedTableError(BaseTest):
"""Test that denied tables show a helpful error message."""
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 718658c3fa53..64f203394cf4 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -96,10 +96,10 @@ class TestQueryRunner(BaseTest):
super().tearDown()
cache.clear()
- def setup_test_query_runner_class(self):
+ def setup_test_query_runner_class(self, base: type[QueryRunner] = QueryRunner):
"""Setup required methods and attributes of the abstract base class."""
- class TestQueryRunner(QueryRunner):
+ class TestQueryRunner(base): # type: ignore[misc, valid-type]
query: TheTestQuery
cached_response: TheTestCachedBasicQueryResponse
@@ -340,6 +340,12 @@ class TestQueryRunner(BaseTest):
cache_key = runner.get_cache_key()
assert cache_key == "cache_42_473689ec17cc982383519776503e498bd0e44f16e6b6f0073412599254a69aba"
+ def test_cache_payload_omits_object_restrictions_when_unrestricted(self):
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
+
+ assert "restricted_objects" not in runner.get_cache_payload()
+
@mock.patch("django.db.transaction.on_commit")
def test_cache_response(self, mock_on_commit):
TestQueryRunner = self.setup_test_query_runner_class()
diff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.py
index b50b2a1142c7..c81abcc9fa20 100644
--- a/posthog/rbac/test/test_user_access_control.py
+++ b/posthog/rbac/test/test_user_access_control.py
@@ -1937,3 +1937,103 @@ class TestAccessControlMissingEE(BaseTest):
qs = FileSystem.objects.filter(team=self.team)
result = self.uac.filter_and_annotate_file_system_queryset(qs)
assert list(result) == list(qs)
+
+
+class TestBlockedResourceIdsByScope(BaseTest):
+ """
+ Tests the deny-set precedence used by HogQL system tables.
+
+ These exercise UserAccessControl.blocked_resource_ids_by_scope directly,
+ which is also the single source of truth for the HogQL printer guard and
+ the cache-key fingerprint in query_runner.py.
+ """
+
+ def setUp(self):
+ super().setUp()
+ from posthog.constants import AvailableFeature
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ self.membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ self.membership.level = OrganizationMembership.Level.MEMBER
+ self.membership.save()
+
+ self.uac = UserAccessControl(self.user, self.team)
+
+ def _blocked(self, resource="dashboard") -> set[str]:
+ return self.uac.blocked_resource_ids_by_scope.get(resource, set())
+
+ def test_empty_for_org_admin(self):
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+ self.uac = UserAccessControl(self.user, self.team)
+ assert self._blocked() == set()
+
+ def test_no_object_overrides_means_no_blocked_ids(self):
+ assert self._blocked() == set()
+
+ def test_object_default_none_blocks_object(self):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="none",
+ )
+ assert "42" in self._blocked()
+
+ def test_object_default_editor_allows_object(self):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="editor",
+ )
+ assert "42" not in self._blocked()
+
+ def test_object_default_none_with_member_editor_override_allows(self):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="none",
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="editor",
+ organization_member=self.membership,
+ )
+ assert "42" not in self._blocked()
+
+ def test_object_default_editor_with_member_none_blocks(self):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="editor",
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="42",
+ access_level="none",
+ organization_member=self.membership,
+ )
+ assert "42" in self._blocked()
+
+ def test_multiple_objects_mixed_access(self):
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id="10", access_level="none")
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id="20", access_level="editor")
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id="30", access_level="none")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="dashboard",
+ resource_id="30",
+ access_level="editor",
+ organization_member=self.membership,
+ )
+ assert self._blocked() == {"10"}
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 44c9d8db293e..612ca2d1fc4d 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -1009,8 +1009,8 @@ class UserAccessControl:
"none"), built from the single preload via the canonical object resolver.
Consumed by HogQL object-level access control (schema filtering / printer guard) and by
- the query cache fingerprint. Empty for org admins (they bypass object AC) and when there
- is no team / EE. FF-agnostic: callers decide whether to enforce it.
+ the query cache fingerprint. Empty for org admins (they bypass object AC) and when there is
+ no team / EE / entitlement.
"""
if not EE_AVAILABLE or not self._team or self.is_organization_admin:
return {}