: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(experiments): enforce warehouse access control at metric authoring (#66677)
Alex Lider63dce7d60973
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex d3caebeae981..485bc4a5f5fe 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -537,6 +537,13 @@ class Database(BaseModel):table_name = table_name.split(".")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"""+ if isinstance(table_name, list):+ table_name = ".".join(str(part) for part in table_name)+ return table_name in self._denied_tables+def get_table_node(self, table_name: str | list[str]) -> TableNode:if isinstance(table_name, str):table_name = table_name.split(".")diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.pyindex 3894db428a07..34af4c833c8f 100644--- a/products/experiments/backend/experiment_saved_metric_service.py+++ b/products/experiments/backend/experiment_saved_metric_service.py@@ -25,6 +25,7 @@ from products.experiments.backend.models.experiment import (ExperimentSavedMetric,saved_metric_has_legacy_query,)+from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_accessclass ExperimentSavedMetricService:@@ -83,6 +84,7 @@ class ExperimentSavedMetricService:) -> ExperimentSavedMetric:"""Create a saved metric with full business-logic validation."""normalized_query = self._normalize_query_for_write(query)+ enforce_warehouse_metric_access([normalized_query], team=self.team, user=self.user)return ExperimentSavedMetric.objects.create(team=self.team,@@ -101,6 +103,7 @@ class ExperimentSavedMetricService:if "query" in update_data:existing_uuid = saved_metric.query.get("uuid") if saved_metric.query else Noneupdate_data["query"] = self._normalize_query_for_write(update_data["query"], existing_uuid=existing_uuid)+ enforce_warehouse_metric_access([update_data["query"]], team=self.team, user=self.user)for attr, value in update_data.items():setattr(saved_metric, attr, value)diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 3806a352706e..28bc02588521 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -57,6 +57,7 @@ from products.experiments.backend.models.experiment import ()from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.experiments.backend.result_serialization import strip_step_sessions+from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_accessfrom products.feature_flags.backend.api.feature_flag import (FeatureFlagSerializer,parse_created_by_ids,@@ -764,6 +765,15 @@ class ExperimentService:if not allow_unknown_events:self.validate_metric_event_names(metrics)self.validate_metric_event_names(metrics_secondary)+ enforce_warehouse_metric_access(+ [+ *(metrics or []),+ *(metrics_secondary or []),+ *self._collect_saved_metric_queries(saved_metrics_ids),+ ],+ team=self.team,+ user=self.user,+ )self.validate_saved_metrics_ids(saved_metrics_ids, self.team.id)is_draft = start_date is None@@ -1081,6 +1091,20 @@ class ExperimentService:seen.add(uuid)return seen+ def _collect_saved_metric_queries(self, saved_metrics_ids: list | None) -> list[dict]:+ """Query definitions of the attached saved metrics, so their tables get the same warehouse+ access check as inline metrics."""+ if not saved_metrics_ids:+ return []+ ids = [sm["id"] for sm in saved_metrics_ids if isinstance(sm, dict) and "id" in sm]+ if not ids:+ return []+ return [+ sm.query+ for sm in ExperimentSavedMetric.objects.filter(id__in=ids, team_id=self.team.id).only("query")+ if sm.query+ ]+@staticmethoddef _regenerate_all_metric_uuids(metrics: list[dict] | None) -> tuple[list[dict] | None, dict[str, str]]:"""Return a deep copy of ``metrics`` with every uuid regenerated.@@ -2030,6 +2054,16 @@ class ExperimentService:if not allow_unknown_events:self.validate_metric_event_names(update_data["metrics_secondary"])+ enforce_warehouse_metric_access(+ [+ *(update_data.get("metrics") or []),+ *(update_data.get("metrics_secondary") or []),+ *self._collect_saved_metric_queries(update_data.get("saved_metrics_ids")),+ ],+ team=self.team,+ user=self.user,+ )+context = serializer_context or self._build_serializer_context()feature_flag = experiment.feature_flagdiff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.pyindex c28d7294d36e..d5992cca0a4c 100644--- a/products/experiments/backend/experiment_summary_data_service.py+++ b/products/experiments/backend/experiment_summary_data_service.py@@ -139,8 +139,9 @@ def is_incomplete_response(result: Any) -> TypeIs[CacheMissResponse | QueryStatuclass ExperimentSummaryDataService:- def __init__(self, team):+ def __init__(self, team, user):self._team = team+ self._user = userasync def fetch_experiment_data(self, experiment_id: int@@ -202,6 +203,8 @@ class ExperimentSummaryDataService:team=experiment.team,workload=Workload.ONLINE,limit_context=LimitContext.QUERY_ASYNC,+ # Runs for the requesting Max user, so warehouse access is enforced against them.+ user=self._user,)result = query_runner.run(execution_mode=execution_mode,diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.pyindex d3c2a13d25a4..27da869b11ff 100644--- a/products/experiments/backend/max_tools.py+++ b/products/experiments/backend/max_tools.py@@ -312,7 +312,7 @@ class ExperimentSummaryTool(MaxTool):async def _fetch_and_format(self, experiment_id: int) -> tuple[str, dict[str, Any]]:"""Fetch experiment data from query runners and format it."""- data_service = ExperimentSummaryDataService(self._team)+ data_service = ExperimentSummaryDataService(self._team, self._user)try:summary_context, _last_refresh, pending = await data_service.fetch_experiment_data(experiment_id)diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.pyindex 1b78579c944e..40d944bdd659 100644--- a/products/experiments/backend/metric_utils.py+++ b/products/experiments/backend/metric_utils.py@@ -179,6 +179,21 @@ def collect_metric_events_and_action_ids(metrics: list[dict[str, Any]]) -> tuplereturn event_names, action_ids+def collect_metric_warehouse_tables(metrics: list[dict[str, Any]]) -> set[str]:+ """Collect ExperimentDataWarehouseNode table names referenced by metric queries."""+ table_names: set[str] = set()+ stack: list[Any] = list(metrics)+ while stack:+ obj = stack.pop()+ if isinstance(obj, dict):+ if obj.get("kind") == "ExperimentDataWarehouseNode" and obj.get("table_name"):+ table_names.add(obj["table_name"])+ stack.extend(obj.values())+ elif isinstance(obj, list):+ stack.extend(obj)+ return table_names++def resolve_action_events(action_ids: set[int], team: Team) -> dict[int, set[str]]:"""Resolve action IDs to their step event names in a single query."""if not action_ids:diff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.pyindex 2b53fad4ebb4..7ac28feb14ba 100644--- a/products/experiments/backend/temporal/canary_logic.py+++ b/products/experiments/backend/temporal/canary_logic.py@@ -306,6 +306,9 @@ def _execute_canary_run(query=ExperimentQuery(experiment_id=experiment.id, metric=metric, precomputation_mode=mode),team=experiment.team,user_facing=False,+ # Userless background recompute. Warehouse access is enforced when the metric is authored, so+ # resolve warehouse tables here instead of failing closed.+ bypass_warehouse_access_control=True,)with tags_context(client_query_id=query_id, trigger="experiment_precompute_canary"):response = runner.calculate()diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 7a18c6f52529..01631485fc14 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -542,9 +542,9 @@ def _calculate_experiment_metric_for_recalculation_sync(team=experiment.team,as_of=query_to_dt,workload=Workload.OFFLINE,- # Scheduled recalc has no request user. Attribute the query to the experiment's creator so- # warehouse HogQL access control is enforced against an accountable user instead of bypassed.- user=experiment.created_by,+ # Userless background recompute. Warehouse access is enforced when the metric is authored,+ # so resolve warehouse tables here instead of failing closed.+ bypass_warehouse_access_control=True,)# Attribute CH load back to this team + product so query_log analysis can tell whose recalc isdiff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex fc406c50978b..4ecd72818808 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -18,8 +18,9 @@ from rest_framework.test import APIRequestFactoryfrom posthog.schema import EventsNode, ExperimentMetric+from posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSource-from posthog.models import Team, User+from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.actions.backend.models.action import Action@@ -37,6 +38,9 @@ from products.experiments.backend.models.team_experiments_config import TeamExpefrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++from ee.models.rbac.access_control import AccessControl# Note that we use allow_unknown_events here since allowing it was the behavior before validating it@@ -5592,3 +5596,96 @@ class TestValidateExcludedVariants:def test_invalid_raises(self, value):with pytest.raises(ValidationError, match="must be a list of strings"):ExperimentService.validate_excluded_variants(value)+++@patch("posthoganalytics.feature_enabled", new=MagicMock(return_value=True))+class TestExperimentServiceWarehouseMetricAccess(APIBaseTest):+ def setUp(self):+ super().setUp()+ 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()++ self.membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ self.membership.level = OrganizationMembership.Level.MEMBER+ self.membership.save()++ credential = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=self.team)+ self.table = DataWarehouseTable.objects.create(+ name="restricted_revenue",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ credential=credential,+ url_pattern="s3://bucket/restricted/*",+ columns={"id": "String"},+ )+ # Deny this member every warehouse object (warehouse_table inherits the warehouse_objects resource).+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")++ def _dw_metric(self) -> dict:+ return {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "ExperimentDataWarehouseNode",+ "table_name": self.table.name,+ "events_join_key": "distinct_id",+ "data_warehouse_join_key": "id",+ "timestamp_field": "ds",+ "math": "total",+ },+ }++ def test_create_experiment_with_restricted_warehouse_metric_is_denied(self):+ service = ExperimentService(team=self.team, user=self.user)+ with pytest.raises(PermissionDenied):+ service.create_experiment(+ name="DW experiment",+ feature_flag_key="dw-create",+ metrics=[self._dw_metric()],+ allow_unknown_events=True,+ )++ def test_update_experiment_with_restricted_warehouse_metric_is_denied(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="dw-update",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ experiment = Experiment.objects.create(team=self.team, created_by=self.user, name="E", feature_flag=flag)+ service = ExperimentService(team=self.team, user=self.user)+ with pytest.raises(PermissionDenied):+ service.update_experiment(experiment, {"metrics": [self._dw_metric()]})++ def test_org_admin_can_author_restricted_warehouse_metric(self):+ self.membership.level = OrganizationMembership.Level.ADMIN+ self.membership.save()+ service = ExperimentService(team=self.team, user=self.user)+ experiment = service.create_experiment(+ name="DW experiment allowed",+ feature_flag_key="dw-allowed",+ metrics=[self._dw_metric()],+ allow_unknown_events=True,+ )+ assert experiment.metrics is not None+ assert len(experiment.metrics) == 1++ def test_attaching_saved_metric_on_restricted_table_is_denied(self):+ # A saved metric on the denied table (authored by someone with access) can't be smuggled in+ # by attaching it via saved_metrics_ids.+ saved_metric = ExperimentSavedMetric.objects.create(+ team=self.team,+ created_by=self.user,+ name="DW saved metric",+ query=self._dw_metric(),+ )+ service = ExperimentService(team=self.team, user=self.user)+ with pytest.raises(PermissionDenied):+ service.create_experiment(+ name="DW via saved metric",+ feature_flag_key="dw-saved",+ saved_metrics_ids=[{"id": saved_metric.id, "metadata": {"type": "primary"}}],+ )diff --git a/products/experiments/backend/test/test_experiment_summary_tool.py b/products/experiments/backend/test/test_experiment_summary_tool.pyindex 947f14a852f2..03a30c53a53d 100644--- a/products/experiments/backend/test/test_experiment_summary_tool.py+++ b/products/experiments/backend/test/test_experiment_summary_tool.py@@ -250,7 +250,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):@freeze_time("2020-01-10T12:00:00Z")async def test_check_data_freshness_no_warning_when_recent(self):- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)# 30 seconds difference - well within the 1 minute thresholdfrontend_refresh = "2020-01-10T11:59:00Z"@@ -261,7 +261,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):@freeze_time("2020-01-10T12:00:00Z")async def test_check_data_freshness_warning_when_stale(self):- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)frontend_refresh = "2020-01-10T10:00:00Z"backend_refresh = datetime(2020, 1, 10, 11, 30, tzinfo=ZoneInfo("UTC"))@@ -272,7 +272,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):@freeze_time("2020-01-10T12:00:00Z")async def test_check_data_freshness_warning_at_threshold_boundary(self):- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)# 61 seconds difference - just over the 1 minute (60 second) thresholdfrontend_refresh = "2020-01-10T11:58:00Z"@@ -284,7 +284,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):@freeze_time("2020-01-10T12:00:00Z")async def test_check_data_freshness_no_warning_at_threshold_boundary(self):- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)# Exactly 60 seconds - at the threshold (not over), should NOT trigger warningfrontend_refresh = "2020-01-10T11:58:00Z"@@ -295,7 +295,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):@freeze_time("2020-01-10T12:00:00Z")async def test_check_data_freshness_handles_none_values(self):- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)self.assertIsNone(data_service.check_data_freshness(None, None))self.assertIsNone(data_service.check_data_freshness("2020-01-10T10:00:00Z", None))@@ -347,7 +347,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):mock_query_runner_class.return_value.run.return_value = mock_query_resultmock_exposure_runner_class.return_value.run.return_value = mock_exposure_result- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)context, last_refresh, pending_calculation = await data_service.fetch_experiment_data(experiment.id)self.assertEqual(context.experiment_id, experiment.id)@@ -386,7 +386,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):]await experiment.asave(update_fields=["metrics"])- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)context, last_refresh, pending_calculation = await data_service.fetch_experiment_data(experiment.id)self.assertFalse(pending_calculation)@@ -464,7 +464,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):mock_query_runner_class.return_value.run.return_value = mock_query_resultmock_exposure_runner_class.return_value.run.return_value = mock_exposure_result- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)context, _, _ = await data_service.fetch_experiment_data(experiment.id)self.assertEqual(len(context.primary_metrics_results), 1)@@ -559,7 +559,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):mock_query_runner_class.return_value.run.return_value = mock_query_resultmock_exposure_runner_class.return_value.run.return_value = mock_exposure_result- data_service = ExperimentSummaryDataService(self.team)+ data_service = ExperimentSummaryDataService(self.team, self.user)context, _, _ = await data_service.fetch_experiment_data(experiment.id)# 1 inline primary + 1 saved primary = 2diff --git a/products/experiments/backend/test/test_metric_utils.py b/products/experiments/backend/test/test_metric_utils.pyindex dccef6bc9887..7e599762ab92 100644--- a/products/experiments/backend/test/test_metric_utils.py+++ b/products/experiments/backend/test/test_metric_utils.py@@ -2,11 +2,14 @@from posthog.test.base import BaseTest+from django.test import SimpleTestCase+from parameterized import parameterizedfrom products.actions.backend.models.action import Actionfrom products.experiments.backend.metric_utils import (collect_metric_events_and_action_ids,+ collect_metric_warehouse_tables,refresh_action_names_in_metric,resolve_action_events,)@@ -387,6 +390,91 @@ class TestCollectMetricEventsAndActionIds(BaseTest):assert action_ids == {7}+class TestCollectMetricWarehouseTables(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "mean",+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": "stripe_charges"},+ },+ {"stripe_charges"},+ ),+ (+ "funnel",+ {+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "series": [+ {"kind": "EventsNode", "event": "signup"},+ {"kind": "ExperimentDataWarehouseNode", "table_name": "orders"},+ ],+ },+ {"orders"},+ ),+ (+ "ratio",+ {+ "kind": "ExperimentMetric",+ "metric_type": "ratio",+ "numerator": {"kind": "ExperimentDataWarehouseNode", "table_name": "revenue"},+ "denominator": {"kind": "EventsNode", "event": "$pageview"},+ },+ {"revenue"},+ ),+ (+ "retention",+ {+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "start_event": {"kind": "ExperimentDataWarehouseNode", "table_name": "trials"},+ "completion_event": {"kind": "ExperimentDataWarehouseNode", "table_name": "subscriptions"},+ },+ {"trials", "subscriptions"},+ ),+ ]+ )+ def test_collects_table_names_by_metric_type(self, _name: str, metric: dict, expected: set[str]):+ assert collect_metric_warehouse_tables([metric]) == expected++ def test_ignores_event_and_action_nodes(self):+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "series": [{"kind": "EventsNode", "event": "x"}, {"kind": "ActionsNode", "id": 1}],+ }+ assert collect_metric_warehouse_tables([metric]) == set()++ def test_ignores_warehouse_node_without_table_name(self):+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": ""},+ }+ assert collect_metric_warehouse_tables([metric]) == set()++ def test_combines_tables_across_metrics(self):+ # SimpleTestCase forbids DB access, so this also locks in that collection touches no DB.+ metrics = [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": "a"},+ },+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": "b"},+ },+ ]+ assert collect_metric_warehouse_tables(metrics) == {"a", "b"}++ def test_empty_metrics_returns_empty_set(self):+ assert collect_metric_warehouse_tables([]) == set()++class TestResolveActionEvents(BaseTest):def test_resolves_actions_to_their_step_events(self):action = Action.objects.create(diff --git a/products/experiments/backend/warehouse_access_control.py b/products/experiments/backend/warehouse_access_control.pynew file mode 100644index 000000000000..755c5e7ed07b--- /dev/null+++ b/products/experiments/backend/warehouse_access_control.py@@ -0,0 +1,37 @@+from typing import Any++from rest_framework.exceptions import PermissionDenied++from posthog.hogql.database.database import Database++from posthog.models.team.team import Team+from posthog.models.user import User++from products.experiments.backend.metric_utils import collect_metric_warehouse_tables+++def enforce_warehouse_metric_access(metrics: list[dict[str, Any]], *, team: Team, user: Any) -> None:+ """Raise PermissionDenied if a metric uses an ExperimentDataWarehouseNode whose warehouse table+ or view the user can't access.++ Background recomputes bypass warehouse access control (they run without a request user), so access+ must be enforced when the metric is created or updated — otherwise an inaccessible table would be+ saved and only fail later, during recalculation.++ The access decision is delegated to the HogQL database build (the same code that enforces+ warehouse access at query time) rather than re-derived here.+ """+ # Synthetic principals (project secret API keys) and anonymous/userless callers bypass warehouse+ # access control at query time, so there's nothing to enforce against here.+ if not isinstance(user, User):+ return++ table_names = collect_metric_warehouse_tables(metrics)+ if not table_names:+ # No warehouse nodes in the metric — skip the database build.+ return++ database = Database.create_for(team=team, user=user)+ blocked = sorted(name for name in table_names if database.is_table_access_denied(name))+ if blocked:+ raise PermissionDenied("You don't have access to data warehouse table(s): " + ", ".join(blocked))