: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: bypass warehouse access control in cohorts recalculation (#72923)
Alex Liderb48d6ee737f4
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 1381e59ba14f..68e23ae34bf1 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -31,7 +31,10 @@ from rest_framework_csv import renderers as csvrenderersfrom posthog.schema import ActorsQuery, HogQLQuery, ProductKeyfrom posthog.hogql.compiler.bytecode import create_bytecode-from posthog.hogql.constants import CSV_EXPORT_LIMIT+from posthog.hogql.constants import CSV_EXPORT_LIMIT, LimitContext+from posthog.hogql.context import HogQLContext+from posthog.hogql.errors import TableAccessDeniedError+from posthog.hogql.printer import prepare_ast_for_printingfrom posthog.hogql.property import PERSON_METADATA_FIELDS, property_to_exprfrom posthog.api.forbid_destroy_model import ForbidDestroyModel@@ -53,7 +56,8 @@ from posthog.helpers.trigram_search import (normalize_search_term,)from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner-from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery+from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runnerfrom posthog.metrics import LABEL_TEAM_IDfrom posthog.models import Userfrom posthog.models.activity_logging.activity_log import (@@ -72,6 +76,7 @@ from posthog.models.property.property import Propertyfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTfrom posthog.personhog_client.caller_tag import personhog_caller_tag+from posthog.ph_client import feature_enabled_or_falsefrom posthog.queries.actor_base_query import get_serialized_peoplefrom posthog.queries.base import determine_parsed_date_for_property_matchingfrom posthog.renderers import SafeJSONRenderer@@ -1021,18 +1026,24 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializreturn str_to_bool(self.initial_data["is_static"])return bool(getattr(self.instance, "is_static", False))- def _effective_filters_after_update(self, attrs: dict) -> dict | None:- # PATCH may send legacy groups without filters, derive the post-update properties for validation- instance = cast(Cohort, self.instance)- filters = attrs.get("filters", instance.filters)+ def _effective_filters_after_update(self, attrs: dict, team: Optional[Team] = None) -> dict | None:+ # Derive the properties that survive the save, mirroring Cohort.properties precedence:+ # filters win over the legacy groups field, so clearing filters re-activates preserved+ # groups. Pass team on the create path, where there's no instance to read it from.+ instance = cast(Optional[Cohort], self.instance)+ filters = attrs.get("filters", instance.filters if instance else None)if filters:return filters- groups = attrs.get("groups", instance.groups)+ groups = attrs.get("groups", instance.groups if instance else None)if not groups:return None- cohort = Cohort(team=instance.team, filters=None, groups=deepcopy(groups))+ effective_team = team or (instance.team if instance else None)+ if effective_team is None:+ return None++ cohort = Cohort(team=effective_team, filters=None, groups=deepcopy(groups))return {"properties": cohort.properties.to_dict()}def validate_filters(self, raw: dict):@@ -1065,12 +1076,77 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializself._validate_feature_flag_constraints(raw, cohort_will_be_static) # keep your side-rulesreturn raw+ def _team_for_warehouse_access_check(self) -> Optional[Team]:+ # Resolve the team from whichever context shape the caller provided so the check can't be+ # skipped: experiments pass "team", feature flag copy passes "team_id", the viewset passes+ # the get_team lambda. Prefer an already-materialized object over the lambda, which can+ # issue a query on cold cache.+ team = self.context.get("team")+ if team is None and self.context.get("get_team"):+ team = self.context["get_team"]()+ if team is None and self.context.get("team_id"):+ team = Team.objects.filter(pk=self.context["team_id"]).first()+ return team++ def _validate_warehouse_access(self, attrs: dict) -> None:+ """Background execution runs the cohort without warehouse access control (the definition+ is team-owned), so access is enforced here instead: the member saving the definition must+ be able to read every warehouse table it resolves through. Covers every way a definition+ can change - `filters`, the legacy `groups` field, and query-based cohorts' `query`."""+ instance = cast(Optional[Cohort], self.instance)+ # Flipping a static cohort to dynamic activates its preserved definition.+ reactivating_static = instance is not None and instance.is_static and attrs.get("is_static") is False+ if not reactivating_static and not any(field in attrs for field in ("filters", "groups", "query")):+ return+ team = self._team_for_warehouse_access_check()+ request = self.context.get("request")+ user = getattr(request, "user", None)+ if team is None or user is None or not getattr(user, "is_authenticated", False):+ return+ # Gate on the same flag the enforcement in Database.create_for uses.+ if not feature_enabled_or_false(+ "hogql-warehouse-access-control",+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ send_feature_flag_events=False,+ ):+ return++ # Check what survives the save, not just the fields in the payload.+ effective = self._effective_filters_after_update(attrs, team=team)+ properties = effective.get("properties") if effective else None+ # A payload query is what's being saved; a flip re-activates the instance's preserved query.+ query = attrs["query"] if "query" in attrs else (instance.query if reactivating_static and instance else None)++ try:+ if properties:+ HogQLCohortQuery(+ filter=Filter(data={"properties": properties}, team=team), team=team+ ).get_query_executor(user=user).generate_clickhouse_sql()+ if query:+ context = HogQLContext(team_id=team.pk, team=team, user=user, enable_select_queries=True)+ runner = get_query_runner(query, team=team, limit_context=LimitContext.COHORT_CALCULATION)+ prepare_ast_for_printing(runner.to_query(), context=context, dialect="clickhouse")+ except TableAccessDeniedError as e:+ raise ValidationError(+ f"Can't save this cohort: you don't have access to table `{e.table_name}`, which its definition uses."+ )+ except Exception:+ # Only access denials gate saving; other compile problems surface elsewhere.+ return+def validate(self, attrs: dict) -> dict:# Field-level validate_filters only runs when the PATCH body includes `filters`. This# object-level guard covers the static-to-dynamic flip when it does not, re-checking the# instance's preserved behavioral filters against the feature-flag rule.attrs = super().validate(attrs)+ self._validate_warehouse_access(attrs)+if self.context["request"].method != "PATCH" or self.instance is None:return attrsdiff --git a/posthog/api/test/test_cohort_warehouse_access_control.py b/posthog/api/test/test_cohort_warehouse_access_control.pynew file mode 100644index 000000000000..70a94612ac27--- /dev/null+++ b/posthog/api/test/test_cohort_warehouse_access_control.py@@ -0,0 +1,164 @@+import pytest+from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import Mock, patch++from posthog.hogql.errors import TableAccessDeniedError++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, Team++from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import hogql_cohort_subquery_sql+from products.data_tools.backend.models.join import DataWarehouseJoin+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++from ee.models.rbac.access_control import AccessControl++# A behavioral filter whose hogql event filter reads the warehouse table directly (cohort+# filters reject the data_warehouse_* property types at the pydantic layer). Reaching the same+# table through the persons join instead is not covered here: a denied join target is dropped+# from the schema rather than raising TableAccessDeniedError, so nothing signals the denial -+# see #69791, which routes those through the typed error too.+WAREHOUSE_FILTERS = {+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "behavioral",+ "key": "$pageview",+ "value": "performed_event",+ "event_type": "events",+ "explicit_datetime": "-30d",+ "event_filters": [+ {"type": "hogql", "key": "person_id IN (SELECT string_prop FROM extended_properties)"}+ ],+ }+ ],+ }+}+++def _create_warehouse_persons_join(team: Team) -> None:+ credential = DataWarehouseCredential.objects.create(team=team, access_key="_accesskey", access_secret="_secret")+ DataWarehouseTable.objects.create(+ team=team,+ name="extended_properties",+ columns={+ "string_prop": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)"},+ "bool_prop": {"hogql": "BooleanDatabaseField", "clickhouse": "Nullable(Bool)"},+ },+ credential=credential,+ url_pattern="",+ )+ DataWarehouseJoin.objects.create(+ team=team,+ source_table_name="persons",+ source_table_key="properties.email",+ joining_table_name="extended_properties",+ joining_table_key="string_prop",+ field_name="extended_properties",+ )+++@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))+class TestCohortRecalculationWarehouseAccessControl(BaseTest):+ def setUp(self):+ super().setUp()+ _create_warehouse_persons_join(self.team)+ self.cohort = Cohort.objects.create(team=self.team, name="warehouse-backed cohort", filters=WAREHOUSE_FILTERS)++ def test_background_recalculation_bypasses_warehouse_access_control(self):+ # Userless compile fails closed - this also proves the cohort genuinely resolves+ # through the warehouse table, so the bypass assertion below can't pass vacuously.+ with pytest.raises(TableAccessDeniedError):+ hogql_cohort_subquery_sql(self.cohort, team=self.team)++ # Recalculation always opts into the bypass, so the same cohort compiles.+ sql, _ = hogql_cohort_subquery_sql(self.cohort, team=self.team, bypass_warehouse_access_control=True)+ assert "extended_properties" in sql+++@patch("posthoganalytics.feature_enabled", new=Mock(return_value=True))+class TestCohortSaveWarehouseAccessControl(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()+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()+ _create_warehouse_persons_join(self.team)++ def _save_cohort(self):+ return self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {"name": "warehouse cohort", "filters": WAREHOUSE_FILTERS},+ )++ def test_denied_member_cannot_save_warehouse_cohort(self):+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")++ response = self._save_cohort()++ assert response.status_code == 400, response.content+ assert "Can't save this cohort" in str(response.json())+ assert "extended_properties" in str(response.json())+ assert not Cohort.objects.filter(team=self.team).exists()++ def test_member_with_access_can_save_warehouse_cohort(self):+ response = self._save_cohort()++ assert response.status_code == 201, response.content+ assert Cohort.objects.filter(team=self.team).exists()++ def test_denied_member_cannot_activate_static_warehouse_cohort(self):+ # Static cohorts are excluded from periodic recalc, so flipping to dynamic is the only+ # path that computes the preserved warehouse criteria - it must be checked as the saver+ # even though the PATCH carries no definition field.+ cohort = Cohort.objects.create(+ team=self.team, name="static warehouse snapshot", is_static=True, filters=WAREHOUSE_FILTERS+ )+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}/",+ {"is_static": False},+ )++ assert response.status_code == 400, response.content+ assert "Can't save this cohort" in str(response.json())+ assert "extended_properties" in str(response.json())++ def test_denied_member_cannot_save_query_cohort_over_warehouse_table(self):+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")++ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {+ "name": "query cohort",+ "is_static": True,+ "query": {"kind": "HogQLQuery", "query": "SELECT string_prop FROM extended_properties"},+ },+ )++ assert response.status_code == 400, response.content+ assert "Can't save this cohort" in str(response.json())+ assert "extended_properties" in str(response.json())++ def test_denied_member_cannot_update_via_legacy_groups(self):+ cohort = Cohort.objects.create(team=self.team, name="plain cohort")+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")++ # Legacy `groups` writes skip field-level validate_filters - the object-level gate must+ # still catch a warehouse reference smuggled in through them.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}/",+ {"groups": [{"properties": WAREHOUSE_FILTERS["properties"]["values"]}]},+ )++ assert response.status_code == 400, response.content+ assert "Can't save this cohort" in str(response.json())+ assert "extended_properties" in str(response.json())diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex c9e2336c57c5..500572ac0ef9 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -47,7 +47,7 @@ from posthog.constants import PropertyOperatorTypefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.events_query_runner import EventsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.models import Filter, Property, Team+from posthog.models import Filter, Property, Team, Userfrom posthog.models.property import OperatorInterval, PropertyGroupfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.types import AnyPropertyFilter@@ -267,7 +267,9 @@ class HogQLCohortQuery:else:raise ValueError("HogQLCohortQuery requires either a cohort or a filter")- def get_query_executor(self) -> HogQLQueryExecutor:+ def get_query_executor(+ self, *, user: Optional[User] = None, bypass_warehouse_access_control: bool = False+ ) -> HogQLQueryExecutor:return HogQLQueryExecutor(query_type="HogQLCohortQuery",query=self.get_query(),@@ -275,6 +277,8 @@ class HogQLCohortQuery:team=self.team,limit_context=LimitContext.COHORT_CALCULATION,settings=HogQLGlobalSettings(),+ user=user,+ bypass_warehouse_access_control=bypass_warehouse_access_control,)def get_query(self) -> SelectQuery | SelectSetQuery:diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex f0e4da67df08..7ba45a0939c3 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -316,7 +316,11 @@ def format_person_query(cohort: Cohort, index: int) -> tuple[str, dict[str, Any]return "SELECT generateUUIDv4() as id WHERE 0 = 19", {}# Compile the cohort criteria via HogQLCohortQuery and embed the result as a person-id subquery.- cohort_query, cohort_context = hogql_cohort_subquery_sql(cohort, team=cohort.team)+ # SECURITY-SENSITIVE: executes a saved, team-owned cohort definition with no acting user in+ # scope - warehouse access is enforced when the definition is saved (CohortSerializer).+ cohort_query, cohort_context = hogql_cohort_subquery_sql(+ cohort, team=cohort.team, bypass_warehouse_access_control=True+ )return _prefix_cohort_hogql_params(cohort_query, cohort_context.values, cohort=cohort, index=index)@@ -636,6 +640,9 @@ def _cohort_distinct_ids_sql(cohort: Cohort, index: int, *, team: Team) -> tuplemodifiers=_cohort_calculation_modifiers(),team=team,limit_context=LimitContext.COHORT_CALCULATION,+ # SECURITY-SENSITIVE: executes a saved, team-owned cohort definition with no acting user+ # in scope - warehouse access is enforced when the definition is saved (CohortSerializer).+ bypass_warehouse_access_control=True,settings=HogQLGlobalSettings(),).generate_clickhouse_sql()sql = _trim_trailing_settings(sql)@@ -788,10 +795,18 @@ def _recalculate_cohortpeople_for_team(cohort: Cohort, pending_version: int, tearaise-def hogql_cohort_subquery_sql(cohort: Cohort, *, team: Team) -> tuple[str, HogQLContext]:+def hogql_cohort_subquery_sql(+ cohort: Cohort,+ *,+ team: Team,+ bypass_warehouse_access_control: bool = False,+) -> tuple[str, HogQLContext]:from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery- sql, hogql_context = HogQLCohortQuery(cohort=cohort, team=team).get_query_executor().generate_clickhouse_sql()+ executor = HogQLCohortQuery(cohort=cohort, team=team).get_query_executor(+ bypass_warehouse_access_control=bypass_warehouse_access_control+ )+ sql, hogql_context = executor.generate_clickhouse_sql()return _trim_trailing_settings(sql), hogql_context@@ -810,7 +825,11 @@ def _recalculate_cohortpeople_for_team_hogql(history.save(update_fields=["finished_at", "count", "error", "error_code"])return 0else:- cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team)+ # SECURITY-SENSITIVE: recalculation always executes without warehouse access control.+ # It is internal maintenance of a team-owned definition with no acting user - access is+ # enforced when the filters are saved (CohortSerializer), and failing here would only+ # silently freeze the cohort's membership.+ cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team, bypass_warehouse_access_control=True)cohort_params = hogql_context.valuesrecalculate_cohortpeople_sql = RECALCULATE_COHORT_BY_ID.format(cohort_filter=cohort_query)@@ -1167,7 +1186,9 @@ def insert_actors_into_cohort_by_query(def insert_cohort_query_actors_into_ch(cohort: Cohort, *, team: Team):- context = HogQLContext(enable_select_queries=True, team_id=team.id)+ # SECURITY-SENSITIVE: background population from the cohort's saved source query, with no+ # acting user - the query was run by its author when they created the cohort from it.+ context = HogQLContext(enable_select_queries=True, team_id=team.id, bypass_warehouse_access_control=True)query = print_cohort_hogql_query(cohort, context, team=team)insert_actors_into_cohort_by_query(cohort, query, {}, context, team_id=team.id)@@ -1176,7 +1197,9 @@ def build_static_cohort_filters_query(cohort: Cohort, *, team: Team) -> tuple[st# Compile the cohort's criteria (cohort.properties) to ClickHouse SQL. The cohort is static, but# it's being populated for the first time, so we evaluate the criteria rather than reading the# (still-empty) static cohort table — HogQLCohortQuery builds from cohort.properties regardless of is_static.- cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team)+ # SECURITY-SENSITIVE: background population of a saved, team-owned definition with no acting+ # user - warehouse access is enforced when the definition is saved (CohortSerializer).+ cohort_query, hogql_context = hogql_cohort_subquery_sql(cohort, team=team, bypass_warehouse_access_control=True)# Params live on hogql_context.values, which the consumer already spreads — pass {} to avoid spreading twice.return f"SELECT id AS actor_id FROM ({cohort_query})", {}, hogql_context