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.

feat: enforce property-level access control for events query runner (#54798)

Reece Jonesfe494b278594
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index 8face8738257..f6adb4609314 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -27,7 +27,7 @@ from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runner
-from posthog.models import Action, Person
+from posthog.models import Action, Person, PropertyDefinition
from posthog.models.action.action import ActionStepJSON
from posthog.models.element import chain_to_elements
from posthog.models.person.person import get_distinct_ids_for_subquery
@@ -160,12 +160,54 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
return val.isoformat()
return str(val)
+ def _raise_on_restricted_property_select(self, select: list[ast.Expr]) -> None:
+ # User-authored ``select`` entries that explicitly reference a restricted event or person
+ # property must fail loudly — the printer's silent JSONDropKeys strip would otherwise turn
+ # the request into an empty string, which is surprising when the field name was typed by hand.
+ from posthog.hogql.errors import ResolutionError
+ from posthog.hogql.visitor import TraversingVisitor
+
+ from products.access_control.backend.property_access_control import get_restricted_property_names
+
+ restricted_event_props = get_restricted_property_names(
+ team_id=self.team.pk,
+ user=self.user,
+ property_type=PropertyDefinition.Type.EVENT,
+ )
+ restricted_person_props = get_restricted_property_names(
+ team_id=self.team.pk,
+ user=self.user,
+ property_type=PropertyDefinition.Type.PERSON,
+ )
+ if not restricted_event_props and not restricted_person_props:
+ return
+
+ class _Checker(TraversingVisitor):
+ def visit_field(self, node: ast.Field) -> None:
+ chain = [str(c) for c in node.chain]
+ # ``properties.<name>`` on the events table.
+ if len(chain) >= 2 and chain[0] == "properties" and chain[1] in restricted_event_props:
+ raise ResolutionError(f"Access to property '{chain[1]}' is restricted")
+ # ``person.properties.<name>`` (or ``poe.properties.<name>``) on the joined person.
+ if (
+ len(chain) >= 3
+ and chain[0] in ("person", "poe")
+ and chain[1] == "properties"
+ and chain[2] in restricted_person_props
+ ):
+ raise ResolutionError(f"Access to property '{chain[2]}' is restricted")
+
+ checker = _Checker()
+ for expr in select:
+ checker.visit(expr)
+
def to_query(self) -> ast.SelectQuery:
# Note: This code is inefficient and problematic, see https://github.com/PostHog/posthog/issues/13485 for details.
with self.timings.measure("build_ast"):
# columns & group_by
with self.timings.measure("columns"):
select_input, select = self.select_cols()
+ self._raise_on_restricted_property_select(select)
with self.timings.measure("aggregations"):
group_by: list[ast.Expr] = [column for column in select if not has_aggregation(column)]
@@ -381,6 +423,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
+ user=self.user,
)
# Convert star field from tuple to dict in each result
@@ -446,6 +489,18 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
if person_distinct_id in requested_batch:
distinct_to_person[person_distinct_id] = person
+ # Load restricted person properties to strip from the side-channel result
+ from products.access_control.backend.property_access_control import (
+ get_restricted_property_names,
+ strip_restricted_properties,
+ )
+
+ restricted_person_props = get_restricted_property_names(
+ team_id=self.team.pk,
+ user=self.user,
+ property_type=PropertyDefinition.Type.PERSON,
+ )
+
# Loop over all columns in case there is more than one "person" column
for column_index in person_indices:
for index, result in enumerate(self.paginator.results):
@@ -453,10 +508,11 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
self.paginator.results[index] = list(result)
if distinct_to_person.get(distinct_id):
person = distinct_to_person[distinct_id]
+ properties = strip_restricted_properties(person.properties or {}, restricted_person_props)
self.paginator.results[index][column_index] = {
"uuid": person.uuid,
"created_at": person.created_at,
- "properties": person.properties or {},
+ "properties": properties,
"distinct_id": distinct_id,
}
else:
diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.py
index d6293726f78f..9850aabd792c 100644
--- a/posthog/hogql_queries/test/test_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_events_query_runner.py
@@ -1067,3 +1067,80 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert isinstance(response, CachedEventsQueryResponse)
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0][0]["event"], "$pageview")
+
+ @freeze_time("2020-01-11T12:00:05Z")
+ def test_restricted_person_properties_stripped_from_person_column(self):
+ from posthog.models import PropertyDefinition
+
+ from products.access_control.backend.models.property_access_control import PropertyAccessControl
+ from products.access_control.backend.property_access_control import PropertyAccessLevel
+
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["p1"],
+ properties={"email": "[email protected]", "name": "Test User"},
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp="2020-01-11T12:00:01Z",
+ properties={"$browser": "Chrome"},
+ )
+ flush_persons_and_events()
+
+ # restrict "email" person property
+ prop_def = PropertyDefinition.objects.create(
+ team=self.team,
+ name="email",
+ type=PropertyDefinition.Type.PERSON,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=prop_def,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ query = EventsQuery(select=["person"], after="2020-01-10")
+ runner = EventsQueryRunner(query=query, team=self.team, user=self.user)
+ response = runner.run()
+
+ assert isinstance(response, CachedEventsQueryResponse)
+ assert len(response.results) > 0
+ person_data = response.results[0][0]
+ assert "email" not in person_data["properties"]
+ assert "name" in person_data["properties"]
+
+ @freeze_time("2020-01-11T12:00:05Z")
+ def test_restricted_event_property_in_select_raises_error(self):
+ from posthog.hogql.errors import ResolutionError
+
+ from posthog.models import PropertyDefinition
+
+ from products.access_control.backend.models.property_access_control import PropertyAccessControl
+ from products.access_control.backend.property_access_control import PropertyAccessLevel
+
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp="2020-01-11T12:00:01Z",
+ properties={"secret_field": "hidden"},
+ )
+ flush_persons_and_events()
+
+ prop_def = PropertyDefinition.objects.create(
+ team=self.team,
+ name="secret_field",
+ type=PropertyDefinition.Type.EVENT,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=prop_def,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ query = EventsQuery(select=["properties.secret_field"], after="2020-01-10")
+ runner = EventsQueryRunner(query=query, team=self.team, user=self.user)
+ with self.assertRaises(ResolutionError):
+ runner.run()