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: bypass access control for materialization transforms (#66390)

Alex Lider60cfabb0db31
diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.py
index 621e99ac0414..95bd02027688 100644
--- a/products/endpoints/backend/materialization_transforms.py
+++ b/products/endpoints/backend/materialization_transforms.py
@@ -18,6 +18,7 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL
from posthog.hogql_queries.query_runner import get_query_runner
+from posthog.models import User
from posthog.models.team import Team
ENDPOINT_BREAKDOWN_LIMIT = 10_000
@@ -60,22 +61,37 @@ def _add_series_index_to_select(query: ast.SelectQuery, index: int) -> None:
query.group_by = [*list(query.group_by), ast.Field(chain=["__series_index"])]
-def _print_materialized_hogql(query: ast.Expr, team: Team, modifiers: HogQLQueryModifiers | None = None) -> str:
+def _print_materialized_hogql(
+ query: ast.Expr,
+ team: Team,
+ modifiers: HogQLQueryModifiers | None = None,
+ *,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
+) -> str:
"""Like to_printed_hogql, but without the implicit top-level row cap — a materialized table must hold every row."""
return prepare_and_print_ast(
clone_expr(query),
dialect="hogql",
context=HogQLContext(
team_id=team.pk,
+ user=user,
enable_select_queries=True,
limit_top_select=False,
modifiers=create_default_modifiers_for_team(team, modifiers),
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
),
pretty=True,
)[0]
-def convert_insight_query_to_hogql(query: dict[str, Any], team: Team) -> dict[str, Any]:
+def convert_insight_query_to_hogql(
+ query: dict[str, Any],
+ team: Team,
+ *,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
+) -> dict[str, Any]:
query_kind = query.get("kind")
if query_kind == "HogQLQuery":
@@ -86,6 +102,7 @@ def convert_insight_query_to_hogql(query: dict[str, Any], team: Team) -> dict[st
team=team,
timings=HogQLTimings(),
modifiers=HogQLQueryModifiers(),
+ user=user,
)
combined_query_ast = query_runner.to_query()
@@ -95,7 +112,13 @@ def convert_insight_query_to_hogql(query: dict[str, Any], team: Team) -> dict[st
if query_kind in SERIES_INDEX_QUERY_TYPES:
inject_series_index(combined_query_ast)
- hogql_string = _print_materialized_hogql(combined_query_ast, team, query_runner.modifiers)
+ hogql_string = _print_materialized_hogql(
+ combined_query_ast,
+ team,
+ query_runner.modifiers,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
result = HogQLQuery(query=hogql_string, modifiers=query_runner.modifiers).model_dump()
if "variables" in query:
@@ -1193,6 +1216,9 @@ def transform_query_for_materialization(
variable_infos: MaterializableVariable | list[MaterializableVariable],
team: Team,
bucket_overrides: dict[str, str] | None = None,
+ *,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> dict[str, Any]:
"""
Transform query by:
@@ -1232,7 +1258,12 @@ def transform_query_for_materialization(
transformer = MaterializationTransformer(variable_infos)
transformed_ast = transformer.visit(parsed_ast)
- transformed_query_str = _print_materialized_hogql(transformed_ast, team)
+ transformed_query_str = _print_materialized_hogql(
+ transformed_ast,
+ team,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
return {
**hogql_query,
@@ -1540,11 +1571,23 @@ def replace_breakdown_sentinels_in_query(hogql_query: dict) -> dict:
return {**hogql_query, "query": query_text}
-def build_endpoint_hogql(insight_query: dict, team: Team, bucket_overrides: dict[str, str] | None = None) -> dict:
+def build_endpoint_hogql(
+ insight_query: dict,
+ team: Team,
+ bucket_overrides: dict[str, str] | None = None,
+ *,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
+) -> dict:
"""Run the full endpoint conversion pipeline: prepare → convert insight to HogQL → apply variable
materialization plan → strip breakdown sentinels. Pure function; no DB side effects."""
mat_query = prepare_insight_query_for_endpoint(insight_query)
- hogql_query = convert_insight_query_to_hogql(mat_query, team)
+ hogql_query = convert_insight_query_to_hogql(
+ mat_query,
+ team,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
if insight_query.get("variables"):
can_materialize, _reason, variable_infos = analyze_variables_for_materialization(
@@ -1552,7 +1595,12 @@ def build_endpoint_hogql(insight_query: dict, team: Team, bucket_overrides: dict
)
if can_materialize and variable_infos:
hogql_query = transform_query_for_materialization(
- hogql_query, variable_infos, team, bucket_overrides=bucket_overrides
+ hogql_query,
+ variable_infos,
+ team,
+ bucket_overrides=bucket_overrides,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
)
return replace_breakdown_sentinels_in_query(hogql_query)
diff --git a/products/endpoints/backend/services/materialization.py b/products/endpoints/backend/services/materialization.py
index 26530e27d640..46e950d71c43 100644
--- a/products/endpoints/backend/services/materialization.py
+++ b/products/endpoints/backend/services/materialization.py
@@ -64,7 +64,13 @@ def prepare_executable_query(saved_query: DataWarehouseSavedQuery) -> None:
f"Saved query {saved_query.id} ({saved_query.name}) has no linked EndpointVersion"
)
- saved_query.query = build_endpoint_hogql(version.query, saved_query.team, bucket_overrides=version.bucket_overrides)
+ saved_query.query = build_endpoint_hogql(
+ version.query,
+ saved_query.team,
+ bucket_overrides=version.bucket_overrides,
+ # Temporal rebuilds are userless and operate on an already-owned endpoint saved query.
+ bypass_warehouse_access_control=True,
+ )
saved_query.save(update_fields=["query", "updated_at"])
@@ -248,7 +254,12 @@ class EndpointMaterializationService:
bucket_overrides: dict[str, str] | None,
) -> None:
"""Point the saved query at the version's materializable HogQL and sync cadence."""
- saved_query.query = build_endpoint_hogql(version.query, self.team, bucket_overrides=bucket_overrides)
+ saved_query.query = build_endpoint_hogql(
+ version.query,
+ self.team,
+ bucket_overrides=bucket_overrides,
+ user=self.user,
+ )
saved_query.external_tables = saved_query.s3_tables
saved_query.is_materialized = True
saved_query.sync_frequency_interval = sync_frequency_to_sync_frequency_interval(
@@ -312,7 +323,7 @@ class EndpointMaterializationService:
if not can_mat:
return MaterializationPreview.cant_materialize(reason)
- hogql_query = convert_insight_query_to_hogql(version.query, self.team)
+ hogql_query = convert_insight_query_to_hogql(version.query, self.team, user=self.user)
range_pairs: list[dict] = []
aggregates: list[dict] = []
@@ -329,7 +340,11 @@ class EndpointMaterializationService:
if variable_infos:
transformed = transform_query_for_materialization(
- hogql_query, variable_infos, self.team, bucket_overrides=bucket_overrides
+ hogql_query,
+ variable_infos,
+ self.team,
+ bucket_overrides=bucket_overrides,
+ user=self.user,
)
transformed_query_str = transformed.get("query")
diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.py
index d3e2b78bf2ba..d1db7abd4724 100644
--- a/products/endpoints/backend/tests/test_variable_materialization.py
+++ b/products/endpoints/backend/tests/test_variable_materialization.py
@@ -2,12 +2,19 @@ from typing import Any
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest import mock
from parameterized import parameterized
+from posthog.schema import DataWarehouseNode, TrendsQuery
+
from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_select
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+
from products.endpoints.backend.materialization_transforms import (
DownstreamCTEShape,
MaterializableVariable,
@@ -17,8 +24,12 @@ from products.endpoints.backend.materialization_transforms import (
_downstream_ctes,
_topological_order,
analyze_variables_for_materialization,
+ build_endpoint_hogql,
transform_query_for_materialization,
)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+from ee.models.rbac.access_control import AccessControl
pytestmark = [pytest.mark.django_db]
@@ -26,6 +37,81 @@ pytestmark = [pytest.mark.django_db]
class TestVariableAnalysis(APIBaseTest):
"""Test variable analysis for materialization eligibility."""
+ def test_materialization_transform_compiles_warehouse_table_without_user_context(self):
+ table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name="web_vitals_mv",
+ columns={"page": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True}},
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern="s3://test-bucket/web-vitals/*.parquet",
+ )
+ query = {
+ "kind": "HogQLQuery",
+ "query": "SELECT count() FROM web_vitals_mv WHERE page = {variables.page}",
+ "variables": {
+ "page-variable": {
+ "variableId": "page-variable",
+ "code_name": "page",
+ "value": "/pricing",
+ }
+ },
+ }
+
+ with mock.patch("posthog.hogql.database.database.feature_enabled_or_false", return_value=True):
+ materialized_query = build_endpoint_hogql(query, self.team, bypass_warehouse_access_control=True)
+
+ assert materialized_query["variables"] == {}
+ assert "{variables" not in materialized_query["query"]
+ assert table.name in materialized_query["query"]
+ assert "page" in materialized_query["query"]
+
+ def test_materialization_transform_respects_user_warehouse_access_control(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name="denied_web_vitals_mv",
+ columns={
+ "id": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},
+ "timestamp": {"hogql": "DateTimeDatabaseField", "clickhouse": "DateTime", "valid": True},
+ },
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern="s3://test-bucket/denied-web-vitals/*.parquet",
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_table",
+ resource_id=str(table.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ query = TrendsQuery(
+ series=[
+ DataWarehouseNode(
+ id=table.name,
+ table_name=table.name,
+ id_field="id",
+ distinct_id_field="id",
+ timestamp_field="timestamp",
+ )
+ ]
+ ).model_dump()
+
+ with mock.patch("posthog.hogql.database.database.feature_enabled_or_false", return_value=True):
+ with pytest.raises(QueryError, match=f"You don't have access to table `{table.name}`"):
+ build_endpoint_hogql(query, self.team, user=self.user)
+
+ materialized_query = build_endpoint_hogql(query, self.team, bypass_warehouse_access_control=True)
+
+ assert table.name in materialized_query["query"]
+
def test_simple_variable_detection(self):
query = {
"kind": "HogQLQuery",