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.

fix(hogql): use TableAccessDeniedError in joins and elsewhere (#69791)

Alex Lidere42d53984531
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 062c215ff99b..11c6b6268b68 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -564,8 +564,9 @@ class Database(BaseModel):
return self.tables.has_child(table_name)
def is_table_access_denied(self, table_name: str | list[str]) -> bool:
- """True if access control denied this table when the HogQL database was built,
- so callers can surface an access denied error instead of unknown table"""
+ """True if access control denied this table when the HogQL database was built.
+ Resolution raises the corresponding TableAccessDeniedError from get_table; this is for
+ callers that need the boolean without resolving (e.g. gating writes that reference tables)."""
if isinstance(table_name, list):
table_name = ".".join(str(part) for part in table_name)
return table_name in self._denied_tables
@@ -585,7 +586,7 @@ class Database(BaseModel):
except ResolutionError as e:
if isinstance(table_name, list):
table_name = ".".join(table_name)
- if table_name in self._denied_tables:
+ if self.is_table_access_denied(table_name):
raise TableAccessDeniedError(table_name) from e
suggestions = self._suggest_table_names(table_name)
suffix = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
@@ -702,7 +703,9 @@ class Database(BaseModel):
join_table = field.join_table
if isinstance(join_table, str):
- return join_table in allowed_table_names
+ # A denied target is absent from the schema, but its join is kept on purpose so
+ # resolving the field raises TableAccessDeniedError instead of "Field not found".
+ return join_table in allowed_table_names or self.is_table_access_denied(join_table)
if self._is_helper_function_table(join_table):
return True
@@ -1999,14 +2002,24 @@ class Database(BaseModel):
with timings.measure("data_warehouse_joins", emit_span=True):
for join in sources.data_warehouse_joins:
+ # A denied table is absent from the schema just like a deleted one, but the two must
+ # not behave the same: dropping the join would surface the denial as "Field not
+ # found", indistinguishable from a typo. Keep it, and target the table by name so
+ # resolution goes through Database.get_table and raises TableAccessDeniedError.
+ joining_table_denied = database.is_table_access_denied(join.joining_table_name)
+
# Skip if either table is not present. This can happen if the table was deleted after the join was created.
# User will be prompted on UI to resolve missing tables underlying the JOIN
- if not database.has_table(join.source_table_name) or not database.has_table(join.joining_table_name):
+ if not database.has_table(join.source_table_name) or (
+ not database.has_table(join.joining_table_name) and not joining_table_denied
+ ):
continue
try:
source_table = database.get_table(join.source_table_name)
- joining_table = database.get_table(join.joining_table_name)
+ joining_table: Table | str = (
+ join.joining_table_name if joining_table_denied else database.get_table(join.joining_table_name)
+ )
from_field = get_join_field_chain(join.source_table_key)
if from_field is None:
diff --git a/posthog/hogql/errors.py b/posthog/hogql/errors.py
index 9f4113995869..c635d140bf22 100644
--- a/posthog/hogql/errors.py
+++ b/posthog/hogql/errors.py
@@ -62,6 +62,10 @@ class QueryError(ExposedHogQLError):
class TableAccessDeniedError(QueryError):
"""The user has no access to the table (raised by Database.get_table)."""
+ # Surfaces as the error code on API responses (see posthog/api/query.py), so clients can tell a
+ # denial from any other query error without matching on the message.
+ code_name = "table_access_denied"
+
table_name: str
def __init__(self, table_name: str):
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 75a25aec27ff..95da06a6367c 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -11,6 +11,7 @@ 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.errors import QueryError, TableAccessDeniedError
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
from posthog.hogql.printer.access_control import build_access_control_guard
@@ -326,8 +327,6 @@ class TestDeniedTableError(BaseTest):
def test_denied_table_shows_access_error(self):
"""When a table is denied, error should say 'no access' not 'unknown'."""
- from posthog.hogql.errors import QueryError
-
from posthog.constants import AvailableFeature
from ee.models import AccessControl
@@ -354,17 +353,18 @@ class TestDeniedTableError(BaseTest):
# Verify the table is in denied list
assert "system.dashboards" in database._denied_tables
- # Try to get the table and verify error message
- with self.assertRaises(QueryError) as cm:
+ # The other denial sites assert the type; this one pins what it reports to callers. The code
+ # is what API clients should match on; the message is still a de-facto contract while
+ # accountOpportunitiesLogic.ts matches on it.
+ with self.assertRaises(TableAccessDeniedError) as cm:
database.get_table("system.dashboards")
- assert "don't have access" in str(cm.exception)
- assert "Unknown" not in str(cm.exception)
+ assert cm.exception.table_name == "system.dashboards"
+ assert cm.exception.code_name == "table_access_denied"
+ assert str(cm.exception) == "You don't have access to table `system.dashboards`."
def test_unknown_table_still_shows_unknown_error(self):
"""Tables that don't exist should still show 'unknown' error."""
- from posthog.hogql.errors import QueryError
-
database = Database.create_for(team=self.team, user=self.user)
with self.assertRaises(QueryError) as cm:
@@ -406,8 +406,6 @@ class TestAccessControlIntegration(BaseTest):
def test_query_without_user_fails_on_scoped_table(self):
"""Querying a scoped system table without user should fail with access error."""
- from posthog.hogql.errors import QueryError
-
context = HogQLContext(
team_id=self.team.pk,
team=self.team,
@@ -415,9 +413,8 @@ class TestAccessControlIntegration(BaseTest):
enable_select_queries=True,
)
- with self.assertRaises(QueryError) as cm:
+ with self.assertRaises(TableAccessDeniedError):
self._compile_select("SELECT id, name FROM system.dashboards", context)
- assert "don't have access" in str(cm.exception)
def test_query_without_user_works_for_unscoped_tables(self):
"""Unscoped system tables should still be queryable without user context."""
@@ -584,7 +581,6 @@ class TestWarehouseTableAccessControl(BaseTest):
# Guards the fail-closed fix: query runners print the response HogQL userless right after the
# user-scoped execute. Without the bypass, that print fails closed on a warehouse table; the param
# must reach the database so warehouse-backed insights don't 500 on the print.
- from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import to_printed_hogql
@@ -595,8 +591,6 @@ class TestWarehouseTableAccessControl(BaseTest):
assert "allowed_table" in printed
def test_denied_table_lookup_raises_access_error(self):
- from posthog.hogql.errors import QueryError
-
self._create_ac(
resource="warehouse_table",
resource_id=str(self.denied_table.id),
@@ -606,10 +600,8 @@ class TestWarehouseTableAccessControl(BaseTest):
database = Database.create_for(team=self.team, user=self.user)
- with self.assertRaises(QueryError) as cm:
+ with self.assertRaises(TableAccessDeniedError):
database.get_table("denied_table")
- assert "don't have access" in str(cm.exception)
- assert "Unknown" not in str(cm.exception)
class TestWarehouseTableAccessControlFlagOff(BaseTest):
@@ -688,7 +680,6 @@ class TestWarehouseAccessControlEndToEnd(BaseTest):
)
def test_execute_hogql_query_raises_on_denied_warehouse_table(self):
- from posthog.hogql.errors import QueryError
from posthog.hogql.query import execute_hogql_query
from ee.models.rbac.access_control import AccessControl
@@ -706,21 +697,53 @@ class TestWarehouseAccessControlEndToEnd(BaseTest):
database = Database.create_for(team=self.team, user=self.user)
assert "denied_warehouse_table" in database._denied_tables
- with self.assertRaises(QueryError) as cm:
+ with self.assertRaises(TableAccessDeniedError) as cm:
execute_hogql_query(
query="SELECT id FROM denied_warehouse_table",
team=self.team,
user=self.user,
)
- assert "don't have access" in str(cm.exception)
- assert "denied_warehouse_table" in str(cm.exception)
+ assert cm.exception.table_name == "denied_warehouse_table"
+
+ def test_execute_hogql_query_raises_on_denied_warehouse_table_reached_through_a_join(self):
+ """A denied table reached through a join must raise the access error too. It is absent from
+ the schema exactly like a deleted one, so without special handling the join is dropped and
+ the denial surfaces as "Field not found", indistinguishable from a typo."""
+ from posthog.hogql.query import execute_hogql_query
+
+ from products.data_tools.backend.models.join import DataWarehouseJoin
+
+ from ee.models.rbac.access_control import AccessControl
+
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name="persons",
+ source_table_key="properties.email",
+ joining_table_name="denied_warehouse_table",
+ joining_table_key="id",
+ field_name="denied_join",
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_table",
+ resource_id=str(self.denied_table.id),
+ access_level="none",
+ organization_member=self.membership,
+ )
+
+ with self.assertRaises(TableAccessDeniedError) as cm:
+ execute_hogql_query(
+ query="SELECT person.denied_join.id FROM events",
+ team=self.team,
+ user=self.user,
+ )
+ assert cm.exception.table_name == "denied_warehouse_table"
def test_execute_hogql_query_bypass_warehouse_access_control_skips_denial(self):
"""bypass_warehouse_access_control opt-in should let the query past the access control gate
(downstream may still fail because there's no real S3 data, but the
gate must not block it)."""
from posthog.hogql.context import HogQLContext
- from posthog.hogql.errors import QueryError
from posthog.hogql.query import execute_hogql_query
from ee.models.rbac.access_control import AccessControl
@@ -743,9 +766,8 @@ class TestWarehouseAccessControlEndToEnd(BaseTest):
user=self.user,
context=context,
)
- except QueryError as e:
- # Access control deny would say "don't have access"
- assert "don't have access" not in str(e), f"bypass was not honored: {e}"
+ except TableAccessDeniedError as e:
+ raise AssertionError(f"bypass was not honored: {e}")
except Exception:
# Downstream errors (missing S3, etc.) are expected and irrelevant
# to whether ACL was bypassed.
@@ -942,12 +964,8 @@ class TestWarehouseViewAccessControl(BaseTest):
assert not database.has_table("denied_view")
assert backing_table.name == "denied_view"
- from posthog.hogql.errors import QueryError
-
- with self.assertRaises(QueryError) as cm:
+ with self.assertRaises(TableAccessDeniedError):
database.get_table("denied_view")
- assert "don't have access" in str(cm.exception)
- assert "Unknown" not in str(cm.exception)
def test_allowed_materialized_view_still_resolves(self):
# The backing table is excluded, but the view node still exposes the name (and reads the