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: check table access when saving action and test-account filters (#113436)

Alex Lideree764fd41ec5
diff --git a/posthog/api/property_filter_access_gate.py b/posthog/api/property_filter_access_gate.py
new file mode 100644
index 000000000000..42cb897c670b
--- /dev/null
+++ b/posthog/api/property_filter_access_gate.py
@@ -0,0 +1,61 @@
+"""Table-access check for property filters at save time.
+
+Background jobs evaluate the step filters of an action and the test-account filters of a team.
+The web analytics weekly digest and the achievements sweep are two of these jobs. These jobs
+have no user, so they bypass warehouse access control. The person who saves a filter must
+therefore have read access to each warehouse table that the filter reaches. Without this check,
+a person could point a filter at a denied table through a join and read the effect in the
+output of the job.
+"""
+
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import TableAccessDeniedError
+from posthog.hogql.modifiers import create_default_modifiers_for_user
+from posthog.hogql.printer import prepare_ast_for_printing
+from posthog.hogql.property import property_to_expr
+
+from posthog.constants import AvailableFeature
+from posthog.models.team import Team
+from posthog.models.user import User
+
+# The only filter types that can reach a warehouse table. A behavioral filter can through its nested
+# event filters. Event and person property filters cannot.
+_WAREHOUSE_REACHING_TYPES = frozenset({"behavioral", "data_warehouse", "data_warehouse_person_property", "hogql"})
+
+
+def table_blocking_property_filters(user: User, team: Team, filters: list[dict[str, Any]]) -> str | None:
+ """The first warehouse table the user cannot read among those the filters reach, or None
+ when the filters pass the check."""
+ filters = [f for f in filters if f.get("type") in _WAREHOUSE_REACHING_TYPES]
+ if not filters:
+ return None
+ # No access rule can deny a table in an organization without the feature, so the filters are
+ # not compiled for it.
+ if not team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return None
+
+ context = HogQLContext(
+ team_id=team.pk,
+ team=team,
+ user=user,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_user(user, team),
+ )
+ # Each filter is compiled on its own, so one that does not compile cannot hide a denial in
+ # another. Only access denials gate the save; anything else is the filter's own problem.
+ for property_filter in filters:
+ try:
+ query = ast.SelectQuery(
+ select=[ast.Constant(value=1)],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=property_to_expr(property_filter, team),
+ )
+ prepare_ast_for_printing(query, context=context, dialect="clickhouse")
+ except TableAccessDeniedError as e:
+ return e.table_name
+ except Exception:
+ continue
+ return None
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 383ce7117963..a29c0411c252 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -41,6 +41,7 @@ from posthog.schema import (
SourceMap,
)
+from posthog.api.property_filter_access_gate import table_blocking_property_filters
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import TeamBasicSerializer
@@ -3382,6 +3383,20 @@ def validate_team_attrs(
+ ", ".join(sorted(admin_fields_touched))
)
+ # A new team has no warehouse tables yet, so only an update can reach a denied one.
+ if "test_account_filters" in attrs and instance is not None:
+ team = instance if isinstance(instance, Team) else instance.passthrough_team
+ denied_table = table_blocking_property_filters(
+ cast(User, view.request.user), team, attrs["test_account_filters"]
+ )
+ if denied_table:
+ raise exceptions.ValidationError(
+ {
+ "test_account_filters": f"This filter uses the table '{denied_table}', which you don't have access to."
+ },
+ code="permission_denied",
+ )
+
if "primary_dashboard" in attrs:
if not instance:
raise exceptions.ValidationError(
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 3efccdea1a73..67b934e9cb18 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -48,6 +48,7 @@ from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.api_keys import create_project_secret_api_key
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
from posthog.utils import get_context_for_template, get_instance_realm
from products.access_control.backend.models.access_control import AccessControl
@@ -443,6 +444,45 @@ def team_api_test_factory():
[{"key": "$current_url", "value": "test"}],
)
+ @parameterized.expand(
+ [
+ # The filter that does not compile must neither break the save nor hide the denial.
+ ("flat", lambda denied: [{"type": "hogql", "key": ""}, denied]),
+ (
+ "nested_in_behavioral",
+ lambda _denied: [
+ {
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ "event_filters": [{"type": "hogql", "key": "person.denied_join.id = 'internal'"}],
+ }
+ ],
+ ),
+ ]
+ )
+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True)
+ @patch("posthog.hogql.property.posthoganalytics.feature_enabled", return_value=True)
+ def test_update_rejects_a_test_account_filter_through_a_denied_warehouse_table(
+ self, _name, filters_for, _behavioral_flag, _flag
+ ):
+ denied_filter = deny_warehouse_table_to_member(self.organization, self.team, self.user)
+ filters_before = self.team.test_account_filters
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/",
+ {"test_account_filters": filters_for(denied_filter)},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "test_account_filters"
+ assert "denied_warehouse_table" in response.json()["detail"]
+ self.team.refresh_from_db()
+ assert self.team.test_account_filters == filters_before
+
@patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")
@patch("posthoganalytics.capture")
def test_delete_team_own_second(
diff --git a/posthog/test/warehouse_access.py b/posthog/test/warehouse_access.py
new file mode 100644
index 000000000000..5ff189b6fabc
--- /dev/null
+++ b/posthog/test/warehouse_access.py
@@ -0,0 +1,55 @@
+from typing import Any
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team, User
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_tools.backend.facade.models import DataWarehouseJoin
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
+
+WAREHOUSE_ACCESS_CONTROL_FLAG = "posthog.hogql.database.database._evaluate_warehouse_access_control_flag"
+
+
+def filter_through_warehouse_join(team: Team) -> dict[str, Any]:
+ """A person property filter that reads `denied_warehouse_table` through a join on persons."""
+ credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=team)
+ DataWarehouseTable.objects.create(
+ name="denied_warehouse_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=team,
+ credential=credential,
+ url_pattern="s3://bucket/denied/*",
+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "valid": True}},
+ )
+ DataWarehouseJoin.objects.create(
+ team=team,
+ source_table_name="persons",
+ source_table_key="properties.email",
+ joining_table_name="denied_warehouse_table",
+ joining_table_key="id",
+ field_name="denied_join",
+ )
+ return {"type": "data_warehouse_person_property", "key": "denied_join.id", "value": "internal", "operator": "exact"}
+
+
+def deny_warehouse_table_to_member(organization: Organization, team: Team, user: User) -> dict[str, Any]:
+ """Make the user a plain member who is denied `denied_warehouse_table`, and return a filter
+ that reads that table. Patch `WAREHOUSE_ACCESS_CONTROL_FLAG` to True for the denial to apply."""
+ organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ organization.save()
+ membership = OrganizationMembership.objects.get(user=user, organization=organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ denied_filter = filter_through_warehouse_join(team)
+ AccessControl.objects.create(
+ team=team,
+ resource="warehouse_table",
+ resource_id=str(DataWarehouseTable.objects.get(team=team, name="denied_warehouse_table").id),
+ access_level="none",
+ organization_member=membership,
+ )
+ return denied_filter
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index c7fb731cdfb0..4b8b5a890105 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -23,6 +23,7 @@ from posthog.api.documentation import (
StringPropertyFilterSerializer,
)
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.property_filter_access_gate import table_blocking_property_filters
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
@@ -233,6 +234,17 @@ class ActionSerializer(
code="unique",
)
+ if "steps" in attrs:
+ step_filters = [prop for step in attrs["steps"] for prop in (step.get("properties") or [])]
+ denied_table = table_blocking_property_filters(
+ self.context["request"].user, self.context["get_team"](), step_filters
+ )
+ if denied_table:
+ raise serializers.ValidationError(
+ {"steps": f"This filter uses the table '{denied_table}', which you don't have access to."},
+ code="permission_denied",
+ )
+
return attrs
def create(self, validated_data: Any) -> Any:
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index fecc6141ffe5..cac0ddc704ea 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -14,6 +14,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import Tag, User
+from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -22,6 +23,20 @@ from products.product_analytics.backend.facade.models import Insight
class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ @patch(WAREHOUSE_ACCESS_CONTROL_FLAG, return_value=True)
+ def test_create_rejects_a_step_filter_through_a_denied_warehouse_table(self, _flag):
+ denied_filter = deny_warehouse_table_to_member(self.organization, self.team, self.user)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/actions/",
+ data={"name": "internal signup", "steps": [{"event": "$pageview", "properties": [denied_filter]}]},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "steps"
+ assert "denied_warehouse_table" in response.json()["detail"]
+ assert not Action.objects.filter(team=self.team, name="internal signup").exists()
+
@patch("products.actions.backend.api.action.report_user_action")
def test_create_action(self, patch_capture, *args):
response = self.client.post(