: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(engineering-analytics): bypass warehouse access control in reads (#66507)
Julian Bez5b65b98969ef
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex c78873925325..0e2c4dadd8f4 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -394,6 +394,13 @@ class UserAccessControl:AccessControl.objects.select_related("team").filter(self._filter_options({"team_id": self._team.id})))+ @property+ def user(self) -> User:+ """The principal this access control was built for. Callers that run HogQL on a user's behalf+ need it: warehouse/system table ACL is honored only when a real user reaches the database build+ (a userless build fails closed), so forwarding just the access control isn't enough."""+ return self._user+@propertydef rbac_supported(self) -> bool:if not self._organization:diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 2e31c7073b38..a33e6910e24d 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -40,9 +40,12 @@ class CuratedGitHubSource:modules then ask the returned instance for the curated subqueries and run HogQL through it."""- def __init__(self, *, team: Team, tables: GitHubTables) -> None:+ def __init__(+ self, *, team: Team, tables: GitHubTables, user_access_control: "UserAccessControl | None" = None+ ) -> None:self._team = teamself._tables = tables+ self._user_access_control = user_access_control@propertydef team(self) -> Team:@@ -56,6 +59,7 @@ class CuratedGitHubSource:return cls(team=team,tables=resolve_github_tables(team=team, source_id=source_id, user_access_control=user_access_control),+ user_access_control=user_access_control,)def pr_source(self) -> str:@@ -164,10 +168,31 @@ class CuratedGitHubSource:query_type: str,placeholders: dict[str, ast.Expr] | None = None,) -> HogQLQueryResponse:- """Parse + execute a curated HogQL query for this team."""+ """Parse + execute a curated HogQL query for this team.++ Mirrors the two paths the data warehouse team intends for ``hogql-warehouse-access-control``+ (#61686). Request-driven reads (the common case — the views thread the requesting user through)+ forward that user so HogQL honors the per-table warehouse ACL: access is enforced twice over —+ the resolver (``for_team``) already filtered the source to what this user may read, and now the+ table-level ACL is honored too, so a user denied a backing ``DataWarehouseTable`` is blocked+ rather than let through. The facade also documents a userless path (``user_access_control=None``)+ for system / Temporal / CLI contexts; that build has no user to honor the ACL with and would fail+ closed (strip every warehouse table), so those reads bypass it — the warehouse team's sanctioned+ escape hatch for userless callers.+ """+ uac = self._user_access_controlwith tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=self._team.pk):return execute_hogql_query(query=parse_select(sql, placeholders=placeholders),team=self._team,query_type=query_type,+ # Forward the real user, not just the access control: a userless build drops the access+ # control and fails closed (see _compute_system_table_access_decision), so the user is what+ # lets HogQL honor the per-table warehouse ACL.+ user=uac.user if uac is not None else None,+ user_access_control=uac,+ # No user means a system / Temporal / CLI caller (the facade's documented userless path).+ # There is no principal to honor the ACL with, so bypass it rather than fail closed and+ # strip the tables — bypass is set ONLY in this genuinely userless case.+ bypass_warehouse_access_control=uac is None,)diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex 19e14235dfb9..2e773a9f08a3 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -32,7 +32,7 @@ _SELECT = """SELECTr.workflow_name, r.id AS run_id, r.run_attempt, j.labels,countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(j.duration_seconds, j.duration_seconds IS NOT NULL) AS elapsed,+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,countIf(j.duration_seconds IS NULL) AS unfinishedFROM __JOBS_SOURCE__ AS jINNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt@@ -113,7 +113,7 @@ _LIST_SELECT = """SELECTr.repo_owner, r.repo_name, r.pr_number, j.labels,countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(j.duration_seconds, j.duration_seconds IS NOT NULL) AS elapsed,+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,countIf(j.duration_seconds IS NULL) AS unfinishedFROM __JOBS_SOURCE__ AS jINNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt@@ -155,7 +155,7 @@ _WINDOW_COST_SELECT = """SELECTr.workflow_name, j.labels,countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(j.duration_seconds, j.duration_seconds IS NOT NULL) AS elapsed,+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,countIf(j.duration_seconds IS NULL) AS unfinishedFROM __JOBS_SOURCE__ AS jINNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt@@ -211,7 +211,7 @@ _RUNNER_COST_SELECT = """SELECTj.labels,countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(j.duration_seconds, j.duration_seconds IS NOT NULL) AS elapsed,+ sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,countIf(j.duration_seconds IS NULL) AS unfinishedFROM __JOBS_SOURCE__ AS jINNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt@@ -283,7 +283,9 @@ def _expand_jobs() -> list[tuple[list[str], float | None]]:"""Re-expand a (labels, finished, elapsed_total, unfinished) group into per-job (labels, elapsed)tuples for aggregate_pr_cost. Elapsed is split evenly across finished jobs — cost is linear in- elapsed, so the summed cost/minutes/counts are identical to costing each real job."""+ elapsed, so the summed cost/minutes/counts are identical to costing each real job. The SQL sums+ ``greatest(duration_seconds, 0)`` so a single clock-skewed negative duration can't cancel its+ group-mates' elapsed before the split — matching aggregate_pr_cost's per-job ``max(0, elapsed)``."""per = (elapsed_total / finished) if finished else 0.0return [(labels, per)] * finished + [(labels, None)] * unfinisheddiff --git a/products/engineering_analytics/backend/tests/test_access_control.py b/products/engineering_analytics/backend/tests/test_access_control.pyindex e6bd2828ef8d..d6eab4d8f760 100644--- a/products/engineering_analytics/backend/tests/test_access_control.py+++ b/products/engineering_analytics/backend/tests/test_access_control.py@@ -13,19 +13,41 @@ the bug under test, independent of object-storage availability for the real ware"""from types import SimpleNamespace+from typing import Anyimport pytestfrom unittest import mockfrom rest_framework import status+from posthog.hogql.database.database import Database++from posthog.rbac.user_access_control import UserAccessControl+from products.data_warehouse.backend.tests.api._access_control_base import WarehouseAccessControlTestMixin-from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.sources import (+ PULL_REQUESTS_SCHEMA,+ WORKFLOW_JOBS_SCHEMA,+ WORKFLOW_RUNS_SCHEMA,+ resolve_github_tables,+)+from products.engineering_analytics.backend.tests.test_views import (+ GITHUB_SOURCE_PREFIX,+ connect_github_source_without_data,+ create_github_source,+ create_warehouse_table_row,+ link_schema,+)from products.warehouse_sources.backend.facade.models import ExternalDataSource# Every curated query runs HogQL through this method; stub it to empty so a resolved source# returns 200 with no rows, leaving the resolver's access-control decision as the only variable._RUN_QUERY = "products.engineering_analytics.backend.logic.queries._curated.CuratedGitHubSource.run"+# The curated runner hands its assembled query to this; capture the principal it forwards.+_EXECUTE_HOGQL = "products.engineering_analytics.backend.logic.queries._curated.execute_hogql_query"+# Schema build reads this to decide whether per-table warehouse ACL is enforced.+_FLAG = "posthog.hogql.database.database.feature_enabled_or_false"@pytest.mark.ee@@ -96,3 +118,96 @@ class TestEngineeringAnalyticsAccessControl(WarehouseAccessControlTestMixin):assert response.status_code == status.HTTP_200_OKassert str(self.source_b.id) in {source["id"] for source in response.json()}+++class TestEngineeringAnalyticsWarehouseAcl(WarehouseAccessControlTestMixin):+ """Per-table warehouse ACL on the real curated read path, once hogql-warehouse-access-control is on.++ #61686 makes a userless HogQL build fail closed -- every warehouse table is stripped from the schema+ -- which is why the curated GitHub reads (historically run with no user) 500'd when the flag rolled+ out. The fix forwards the request user into execution. These build the HogQL schema exactly as the+ runner does (capturing whatever principal ``run`` forwards, so the guard follows the fix rather than+ hard-coding it) and assert a member with default access keeps the GitHub tables, while a member+ denied the backing table loses it. Schema-build only: no object storage or warehouse rows needed.+ """++ resource = "warehouse_table"++ def setUp(self) -> None:+ super().setUp()+ self.source = create_github_source(self.team)+ self.tables = {}+ for schema in (PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA):+ table = create_warehouse_table_row(+ self.team, name=f"{GITHUB_SOURCE_PREFIX}github_{schema}", source=self.source+ )+ link_schema(self.team, self.source, name=schema, table=table)+ self.tables[schema] = table++ def _schema_as_runner_builds_it(self, user_access_control: UserAccessControl | None) -> tuple[Database, dict]:+ # Capture the principal the real curated runner forwards for this access control, then rebuild the+ # schema with it under the flag -- so this follows whatever run() passes (user / access control /+ # bypass), not a hard-coded shape. Returns the schema and the captured kwargs.+ captured: dict = {}++ def _capture(*_args: Any, **kwargs: Any) -> SimpleNamespace:+ captured.update(kwargs)+ return SimpleNamespace(results=[])++ with mock.patch(_EXECUTE_HOGQL, side_effect=_capture):+ CuratedGitHubSource.for_team(self.team, user_access_control=user_access_control).run(+ "SELECT 1", query_type="engineering_analytics.test"+ )++ def _flag_enabled(key: str, *_args: Any, **_kwargs: Any) -> bool:+ return key == "hogql-warehouse-access-control"++ with mock.patch(_FLAG, side_effect=_flag_enabled):+ database = Database.create_for(+ team=self.team,+ user=captured.get("user"),+ user_access_control=captured.get("user_access_control"),+ bypass_warehouse_access_control=captured.get("bypass_warehouse_access_control", False),+ )+ return database, captured++ def test_member_with_default_access_keeps_github_tables(self) -> None:+ # A normal member (no explicit restriction) defaults to editor on the warehouse tables, so the+ # forwarded user keeps all three GitHub tables in the schema -- the read works under the flag.+ uac = UserAccessControl(self.editor_user, self.team)+ tables = resolve_github_tables(team=self.team, user_access_control=uac)+ database, _ = self._schema_as_runner_builds_it(uac)++ assert database.has_table(tables.pull_requests)+ assert database.has_table(tables.workflow_runs)+ assert tables.workflow_jobs is not None and database.has_table(tables.workflow_jobs)++ def test_member_denied_backing_table_cannot_query_it(self) -> None:+ # Deny one member the workflow_runs table specifically. Forwarding the user now honors that: the+ # denied table is stripped (so reads of it are blocked, not silently returned), while an+ # un-denied sibling stays queryable -- the security win the bypass gave up.+ self._create_access_control(+ self.no_access_user,+ resource="warehouse_table",+ resource_id=str(self.tables[WORKFLOW_RUNS_SCHEMA].id),+ access_level="none",+ )+ uac = UserAccessControl(self.no_access_user, self.team)+ tables = resolve_github_tables(team=self.team, user_access_control=uac)+ database, _ = self._schema_as_runner_builds_it(uac)++ assert not database.has_table(tables.workflow_runs)+ assert database.has_table(tables.pull_requests)++ def test_userless_system_read_bypasses_acl_and_keeps_tables(self) -> None:+ # The facade documents a userless path (user_access_control=None) for system / Temporal / CLI+ # callers. There is no principal to honor the table ACL with, so the runner bypasses it rather+ # than fail closed and strip the tables under the flag.+ tables = resolve_github_tables(team=self.team)+ database, captured = self._schema_as_runner_builds_it(None)++ assert captured.get("bypass_warehouse_access_control") is True+ assert database.has_table(tables.pull_requests)+ assert database.has_table(tables.workflow_runs)+ assert tables.workflow_jobs is not None and database.has_table(tables.workflow_jobs)diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex 0102ce7a7997..d32bcdf61c64 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -647,6 +647,37 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):assert cost.costed_jobs == job_countassert cost.estimated_cost_usd == pytest.approx(2.40)+ def test_pr_cost_clamps_clock_skewed_negative_durations(self) -> None:+ # Two jobs share one run/label group: a normal +120s job and a clock-skewed -120s one+ # (completed_at < started_at). The grouped sum must clamp the negative per-job (greatest(.,0))+ # so it doesn't cancel its group-mate's elapsed before the even-split expansion. Without the+ # clamp the group sums to 0s and the PR reads $0.00; with it, the skewed job contributes 0 and+ # the normal job's 120s survives = 2 billable min, depot 4-core (2x) at $0.004/min = $0.016.+ self._create_table(+ "github_pull_requests",+ _PULL_REQUESTS_COLUMNS,+ [_pr_row(72, "alice", "open", 0, _ago(1), head_sha="sha72")],+ )+ self._create_table(+ "github_workflow_runs",+ _WORKFLOW_RUNS_COLUMNS,+ [_run_row(9800, "CI", "sha72", "completed", "success", _ago(1), _ago(1), pr_number=72)],+ )+ self._create_table(+ "github_workflow_jobs",+ WORKFLOW_JOBS_COLUMNS,+ [+ _job_row(98000, 9800, "ok", "success", started="2026-01-01 00:00:00", completed="2026-01-01 00:02:00"),+ _job_row(+ 98001, 9800, "skew", "success", started="2026-01-01 00:02:00", completed="2026-01-01 00:00:00"+ ),+ ],+ )+ cost = api.get_pr_cost(team=self.team, pr_number=72, repo="PostHog/posthog")+ assert cost.costed_jobs == 2+ assert cost.billable_minutes == pytest.approx(2.0)+ assert cost.estimated_cost_usd == pytest.approx(0.016)+def test_pull_request_list_author_filter(self) -> None:# The author filter scopes the list to one author's PRs (drives the author page).self._create_table(