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 in hogql 'properties' column (#54796)

Reece Jones6a0d71f98924
diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.py
index bb2263ac8b8e..b6000e7b2cab 100644
--- a/posthog/hogql/ast.py
+++ b/posthog/hogql/ast.py
@@ -689,11 +689,9 @@ class FieldType(Type):
# to determine if this field supports property access (JSON / array).
constant_type = self.resolve_constant_type(context)
if isinstance(constant_type, (StringJSONType, StringArrayType)):
- self._check_property_access_control(name, context)
return PropertyType(chain=[name], field_type=self)
raise ResolutionError(f'Can not access property "{name}" on field "{self.name}".')
if isinstance(database_field, StringJSONDatabaseField):
- self._check_property_access_control(name, context)
return PropertyType(chain=[name], field_type=self)
if isinstance(database_field, StringArrayDatabaseField):
return PropertyType(chain=[name], field_type=self)
@@ -704,48 +702,6 @@ class FieldType(Type):
f'Can not access property "{name}" on field "{self.name}" of type: {type(database_field).__name__}'
)
- def _check_property_access_control(self, property_name: str | int, context: HogQLContext) -> None:
- """
- Raises ResolutionError if the property is restricted by property-level access control.
-
- The error message intentionally matches the message for genuinely non-existent fields
- so that an attacker cannot distinguish between "this property exists but I can't see it"
- and "this property doesn't exist".
- """
- if not context.restricted_properties or self.name != "properties":
- return
-
- from posthog.hogql.database.schema.events import EventsTable
- from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
-
- from products.event_definitions.backend.models.property_definition import PropertyDefinition
-
- prop_name_str = str(property_name)
- prop_def_types: list[int] = []
-
- if isinstance(self.table_type, BaseTableType):
- try:
- table = self.table_type.resolve_database_table(context)
- except ResolutionError:
- return
-
- if isinstance(table, EventsTable):
- if isinstance(self.table_type, VirtualTableType) and self.table_type.field == "poe":
- prop_def_types.append(PropertyDefinition.Type.PERSON)
- else:
- prop_def_types.append(PropertyDefinition.Type.EVENT)
- elif isinstance(table, (PersonsTable, RawPersonsTable)):
- prop_def_types.append(PropertyDefinition.Type.PERSON)
- else:
- return
-
- if not prop_def_types:
- return
-
- for prop_type in prop_def_types:
- if (prop_name_str, prop_type) in context.restricted_properties:
- raise ResolutionError(f'Can not access property "{prop_name_str}" on field "{self.name}".')
-
def resolve_table_type(self, context: HogQLContext):
return self.table_type
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index eafc2f037a86..2fac52b79bc6 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -441,6 +441,91 @@ class ClickHousePrinter(BasePrinter):
return self.visit(node.type)
+ def visit_field_type(self, type: ast.FieldType):
+ field_sql = super().visit_field_type(type)
+ return self._maybe_apply_json_drop_keys(type, field_sql)
+
+ def _get_materialized_property_source_for_property_type(
+ self, type: ast.PropertyType
+ ) -> PrintableMaterializedColumn | PrintableMaterializedPropertyGroupItem | None:
+ # If this property is restricted by property-level access control, skip the
+ # materialized-column / property-group shortcut and force the JSON-extract path
+ # below. The JSON column itself is wrapped by ``JSONDropKeys`` in
+ # ``_maybe_apply_json_drop_keys`` (see ``visit_field_type``), so the extracted
+ # value collapses to an empty string instead of leaking the materialized value.
+ if self._is_property_type_restricted(type):
+ return None
+ return super()._get_materialized_property_source_for_property_type(type)
+
+ def _is_property_type_restricted(self, type: ast.PropertyType) -> bool:
+ if not self.context.restricted_properties or len(type.chain) == 0:
+ return False
+ keys_to_drop = self._get_restricted_keys_for_table_type(type.field_type.table_type)
+ if not keys_to_drop:
+ return False
+ # Only the first chain element is a top-level key on the JSON blob; nested
+ # accesses (``properties.foo.bar``) are restricted iff their root key is.
+ return str(type.chain[0]) in keys_to_drop
+
+ def _maybe_apply_json_drop_keys(self, type: ast.FieldType, field_sql: str) -> str:
+ """
+ Wraps a StringJSONDatabaseField in JSONDropKeys() to strip restricted property keys
+ when the raw JSON blob is selected directly (e.g., `SELECT properties FROM events`).
+ """
+ if not self.context.restricted_properties:
+ return field_sql
+
+ from posthog.hogql.database.models import StringJSONDatabaseField
+
+ resolved_field = type.resolve_database_field(self.context)
+ if not isinstance(resolved_field, StringJSONDatabaseField):
+ return field_sql
+
+ # Use the resolved DB column name, not ``type.name``. With column-alias table syntax
+ # (``FROM events AS e(uuid, event, ..., p)``) the AST field name is the alias (``p``),
+ # but ClickHouse resolves it back to the original column. Comparing ``type.name`` here
+ # would incorrectly skip JSONDropKeys wrapping for the aliased ``properties`` column.
+ # ``person_properties`` is the underlying DB column for ``EventsPersonSubTable.properties``
+ # (PoE mode); it is also a JSON blob that must be stripped of restricted person-property keys.
+ if resolved_field.name not in ("properties", "person_properties"):
+ return field_sql
+
+ keys_to_drop = self._get_restricted_keys_for_table_type(type.table_type)
+ if not keys_to_drop:
+ return field_sql
+
+ keys_placeholder = self.context.add_sensitive_value(sorted(keys_to_drop))
+ return f"JSONDropKeys({keys_placeholder})({field_sql})"
+
+ def _get_restricted_keys_for_table_type(self, table_type: ast.Type) -> set[str]:
+ """
+ Given a table type, returns the set of property names that should be stripped
+ from the JSON blob based on restricted_properties in the context.
+ """
+ from posthog.hogql.database.schema.events import EventsPersonSubTable, EventsTable
+ from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
+
+ from products.event_definitions.backend.models.property_definition import PropertyDefinition
+
+ if not isinstance(table_type, ast.BaseTableType):
+ return set()
+
+ try:
+ table = table_type.resolve_database_table(self.context)
+ except Exception:
+ return set()
+
+ if isinstance(table, EventsPersonSubTable):
+ prop_def_type = PropertyDefinition.Type.PERSON
+ elif isinstance(table, EventsTable):
+ prop_def_type = PropertyDefinition.Type.EVENT
+ elif isinstance(table, (PersonsTable, RawPersonsTable)):
+ prop_def_type = PropertyDefinition.Type.PERSON
+ else:
+ return set()
+
+ return {name for name, ptype in self.context.restricted_properties or set() if ptype == prop_def_type}
+
def _get_property_group_source_for_field(
self, field_type: ast.FieldType, property_name: str
) -> PrintableMaterializedPropertyGroupItem | None:
diff --git a/posthog/hogql/printer/test/test_property_access_control.py b/posthog/hogql/printer/test/test_property_access_control.py
index a1e00ebe7a1f..38601fc703bb 100644
--- a/posthog/hogql/printer/test/test_property_access_control.py
+++ b/posthog/hogql/printer/test/test_property_access_control.py
@@ -1,7 +1,10 @@
from posthog.test.base import BaseTest
+from parameterized import parameterized
+
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode
+
from posthog.hogql.context import HogQLContext
-from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
@@ -29,7 +32,7 @@ class TestRestrictPropertiesInHogQL(BaseTest):
type=PropertyDefinition.Type.EVENT,
)
- def _compile_select(self, query: str, user=None) -> str:
+ def _compile_select_with_values(self, query: str, user=None) -> tuple[str, dict]:
if user is None:
user = self.user
context = HogQLContext(
@@ -40,8 +43,22 @@ class TestRestrictPropertiesInHogQL(BaseTest):
)
node = parse_select(query)
sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")
+ return sql, context.values
+
+ def _compile_select(self, query: str, user=None) -> str:
+ sql, _ = self._compile_select_with_values(query, user)
return sql
+ def _assert_value_present(self, values: dict, expected: str) -> None:
+ # Restricted keys are now passed to JSONDropKeys as a single list parameter,
+ # so we may need to look inside list values as well as scalar values.
+ for v in values.values():
+ if v == expected:
+ return
+ if isinstance(v, list) and expected in v:
+ return
+ raise AssertionError(f"Expected {expected!r} in values (scalars or lists), got {values!r}")
+
def test_no_restrictions_passes_through(self):
sql = self._compile_select("SELECT properties.secret_field FROM events")
assert "secret_field" in sql
@@ -55,16 +72,20 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT properties.secret_field FROM events")
assert "secret_field" in sql
- def test_denied_event_property_raises_error(self):
+ def test_denied_event_property_is_stripped_silently(self):
+ # Restricted properties are removed from the JSON blob via JSONDropKeys rather than
+ # raising an error, so explicit access (``properties.secret_field``) compiles to a
+ # JSON extract over the stripped blob and resolves to an empty string at runtime.
PropertyAccessControl.objects.create(
team=self.team,
property_definition=self.event_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- with self.assertRaises(ResolutionError) as cm:
- self._compile_select("SELECT properties.secret_field FROM events")
- assert "secret_field" in str(cm.exception)
- assert "properties" in str(cm.exception)
+ sql, values = self._compile_select_with_values("SELECT properties.secret_field FROM events")
+ assert "JSONDropKeys" in sql
+ # the restricted key only appears as a parameter placeholder — never as an inline literal
+ assert "'secret_field'" not in sql
+ self._assert_value_present(values, "secret_field")
def test_allowed_property_not_affected(self):
PropertyAccessControl.objects.create(
@@ -75,15 +96,21 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT properties.public_field FROM events")
assert "public_field" in sql
- def test_mixed_denied_and_allowed_raises_for_denied(self):
+ def test_mixed_denied_and_allowed_strips_only_denied(self):
PropertyAccessControl.objects.create(
team=self.team,
property_definition=self.event_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- with self.assertRaises(ResolutionError) as cm:
- self._compile_select("SELECT properties.secret_field, properties.public_field FROM events")
- assert "secret_field" in str(cm.exception)
+ sql, values = self._compile_select_with_values(
+ "SELECT properties.secret_field, properties.public_field FROM events"
+ )
+ assert "JSONDropKeys" in sql
+ # the denied property is parameterised by JSONDropKeys, never inlined as a literal;
+ # the allowed property is extracted by name (also parameterised)
+ assert "'secret_field'" not in sql
+ self._assert_value_present(values, "secret_field")
+ self._assert_value_present(values, "public_field")
def test_user_override_allows_access(self):
# default: none
@@ -102,7 +129,9 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT properties.secret_field FROM events")
assert "secret_field" in sql
- def test_denied_person_property_raises_error(self):
+ def test_denied_person_property_is_stripped_silently(self):
+ # Restricted person properties are removed from ``person.properties`` rather than
+ # raising — so the same query produces consistent (empty) output across PoE modes.
person_prop = PropertyDefinition.objects.create(
team=self.team,
name="secret_person_field",
@@ -114,9 +143,10 @@ class TestRestrictPropertiesInHogQL(BaseTest):
property_definition=person_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- with self.assertRaises(ResolutionError) as cm:
- self._compile_select("SELECT person.properties.secret_person_field FROM events")
- assert "secret_person_field" in str(cm.exception)
+ sql, values = self._compile_select_with_values("SELECT person.properties.secret_person_field FROM events")
+ assert "JSONDropKeys" in sql
+ assert "'secret_person_field'" not in sql
+ self._assert_value_present(values, "secret_person_field")
def test_no_user_context_uses_default_rules(self):
PropertyAccessControl.objects.create(
@@ -131,8 +161,11 @@ class TestRestrictPropertiesInHogQL(BaseTest):
enable_select_queries=True,
)
node = parse_select("SELECT properties.secret_field FROM events")
- with self.assertRaises(ResolutionError):
- prepare_and_print_ast(node, context=context, dialect="clickhouse")
+ sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")
+ # default rules still apply without a user — the restricted key is stripped
+ assert "JSONDropKeys" in sql
+ assert "'secret_field'" not in sql
+ assert "secret_field" in context.values.values()
def test_non_property_fields_not_affected(self):
PropertyAccessControl.objects.create(
@@ -144,14 +177,18 @@ class TestRestrictPropertiesInHogQL(BaseTest):
assert "event" in sql
assert "timestamp" in sql
- def test_denied_property_in_where_raises_error(self):
+ def test_denied_property_in_where_is_stripped(self):
PropertyAccessControl.objects.create(
team=self.team,
property_definition=self.event_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- with self.assertRaises(ResolutionError):
- self._compile_select("SELECT event FROM events WHERE properties.secret_field = 'foo'")
+ # the WHERE clause compiles, but the restricted property is stripped from the JSON,
+ # so the comparison effectively runs against an empty string
+ sql, values = self._compile_select_with_values("SELECT event FROM events WHERE properties.secret_field = 'foo'")
+ assert "JSONDropKeys" in sql
+ assert "'secret_field'" not in sql
+ self._assert_value_present(values, "secret_field")
def test_select_star_works_with_restrictions(self):
PropertyAccessControl.objects.create(
@@ -186,19 +223,203 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT properties.secret_field FROM events")
assert "secret_field" in sql
- def test_error_is_indistinguishable_from_nonexistent_field(self):
+ def test_silent_strip_does_not_leak_access_control_information(self):
+ # The compiled SQL must not embed the restricted property name as a literal,
+ # error message, or comment — anything an attacker could read off the wire to
+ # tell "this property exists but I can't see it" apart from "this property
+ # doesn't exist". Restricted keys are passed through ``add_sensitive_value`` so
+ # they appear only in the parameter dict, not the SQL string.
PropertyAccessControl.objects.create(
team=self.team,
property_definition=self.event_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- # the error for a restricted property should use the exact same message format
- # as the standard ResolutionError for accessing a child on a non-traversable field,
- # so that an attacker cannot distinguish restricted from non-existent
- with self.assertRaises(ResolutionError) as cm:
- self._compile_select("SELECT properties.secret_field FROM events")
- error_msg = str(cm.exception)
- assert error_msg == 'Can not access property "secret_field" on field "properties".'
- # the error should not mention restriction-specific words
+ sql, values = self._compile_select_with_values("SELECT properties.secret_field FROM events")
+ # restricted key never appears as an inline literal in SQL — only as a parameter
+ assert "'secret_field'" not in sql
for forbidden_word in ["restricted", "denied", "permission", "not allowed"]:
- assert forbidden_word not in error_msg.lower(), f"Error message leaks access control info: '{error_msg}'"
+ assert forbidden_word not in sql.lower(), f"SQL leaks access control info: '{sql}'"
+ self._assert_value_present(values, "secret_field")
+
+ @parameterized.expand(
+ [
+ ("events_properties", "SELECT properties FROM events", PropertyDefinition.Type.EVENT, "secret_field"),
+ ("events_star", "SELECT * FROM events", PropertyDefinition.Type.EVENT, "secret_field"),
+ (
+ "events_person_properties",
+ "SELECT person.properties FROM events",
+ PropertyDefinition.Type.PERSON,
+ "secret_person_field",
+ ),
+ ]
+ )
+ def test_restricted_properties_blob_uses_json_drop_keys(
+ self,
+ _case_name: str,
+ query: str,
+ property_type: int,
+ restricted_key: str,
+ ):
+ property_definition = self.event_prop
+ if property_type == PropertyDefinition.Type.PERSON:
+ property_definition = PropertyDefinition.objects.create(
+ team=self.team,
+ name=restricted_key,
+ property_type="String",
+ type=PropertyDefinition.Type.PERSON,
+ )
+
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=property_definition,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ sql, values = self._compile_select_with_values(query)
+ assert "JSONDropKeys" in sql
+ assert restricted_key not in sql
+ self._assert_value_present(values, restricted_key)
+
+ def test_properties_blob_no_wrapping_without_restrictions(self):
+ sql = self._compile_select("SELECT properties FROM events")
+ assert "JSONDropKeys" not in sql
+
+ def test_properties_blob_strips_multiple_restricted_keys(self):
+ another_prop = PropertyDefinition.objects.create(
+ team=self.team,
+ name="another_secret",
+ property_type="String",
+ type=PropertyDefinition.Type.EVENT,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=another_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ sql, values = self._compile_select_with_values("SELECT properties FROM events")
+ assert "JSONDropKeys" in sql
+ assert "another_secret" not in sql
+ assert "secret_field" not in sql
+ self._assert_value_present(values, "another_secret")
+ self._assert_value_present(values, "secret_field")
+
+ @parameterized.expand([("persons",), ("raw_persons",)])
+ def test_persons_tables_properties_blob_strips_restricted_keys(self, table_name: str):
+ person_prop = PropertyDefinition.objects.create(
+ team=self.team,
+ name="secret_person_field",
+ property_type="String",
+ type=PropertyDefinition.Type.PERSON,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=person_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ sql, values = self._compile_select_with_values(f"SELECT properties FROM {table_name}")
+ assert "JSONDropKeys" in sql
+ assert "secret_person_field" not in sql
+ self._assert_value_present(values, "secret_person_field")
+
+ def test_event_restriction_does_not_affect_person_properties_blob(self):
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ # restricting an event property should not wrap person.properties in JSONDropKeys
+ sql = self._compile_select("SELECT person.properties FROM events")
+ assert "JSONDropKeys" not in sql
+
+ def test_restrictions_do_not_affect_non_event_or_person_tables(self):
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ # the groups table has a StringJSONDatabaseField named "properties",
+ # but restrictions should only apply to events/persons tables
+ sql = self._compile_select("SELECT properties FROM groups")
+ assert "JSONDropKeys" not in sql
+
+ def test_explicit_property_access_on_non_event_table_not_blocked(self):
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ # accessing properties.secret_field on the groups table should not raise,
+ # even though "secret_field" is restricted on the events table
+ sql = self._compile_select("SELECT properties.secret_field FROM groups")
+ assert "secret_field" in sql
+
+ def test_column_aliased_properties_blob_still_uses_json_drop_keys(self):
+ # regression: ColumnAliasedTableType (``FROM events AS e(uuid, event, properties_alias)``)
+ # exposed ``properties`` under a different AST name; the guard previously compared the
+ # alias to "properties" and skipped JSONDropKeys, leaking restricted keys.
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ sql, values = self._compile_select_with_values("SELECT e.c FROM events AS e (a, b, c)")
+ assert "JSONDropKeys" in sql
+ assert "secret_field" not in sql
+ self._assert_value_present(values, "secret_field")
+
+ def test_column_aliased_explicit_property_access_is_stripped(self):
+ # regression: explicit access ``e.c.secret_field`` (where ``c`` aliases ``properties``)
+ # must be stripped via JSONDropKeys, matching the unaliased case.
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ sql, values = self._compile_select_with_values("SELECT e.c.secret_field FROM events AS e (a, b, c)")
+ assert "JSONDropKeys" in sql
+ assert "'secret_field'" not in sql
+ self._assert_value_present(values, "secret_field")
+
+ @parameterized.expand(
+ [
+ ("disabled_joined", PersonsOnEventsMode.DISABLED),
+ ("poe_no_override", PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS),
+ ("poe_override", PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS),
+ ("override_joined", PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED),
+ ]
+ )
+ def test_person_property_access_is_consistent_across_poe_modes(
+ self, _case_name: str, persons_on_events_mode: PersonsOnEventsMode
+ ):
+ # regression: previously, ``person.properties.email`` raised a ResolutionError in joined
+ # mode but silently returned an empty value in PoE mode. The intended behaviour is to
+ # strip restricted keys from the JSON blob (returning empty) in *all* modes, so the same
+ # query produces the same compiled output regardless of how person properties are sourced.
+ person_prop = PropertyDefinition.objects.create(
+ team=self.team,
+ name="email",
+ property_type="String",
+ type=PropertyDefinition.Type.PERSON,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=person_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ user=self.user,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode=persons_on_events_mode),
+ )
+ node = parse_select("SELECT uuid, event, person.properties.email FROM events")
+ sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")
+ assert "JSONDropKeys" in sql
+ # the restricted key never leaks as an inline literal in any PoE mode
+ assert "'email'" not in sql
+ assert "email" in context.values.values()
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
index 8d1db09c35d3..285b25a44433 100644
--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
+++ b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
@@ -844,94 +844,13 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate.2
'''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT events__session.`$entry_pathname` AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
+
+ SELECT timestamp
+ from events
+ WHERE team_id = 99999
+ AND timestamp > '2015-01-01'
+ order by timestamp
+ limit 1
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user
diff --git a/products/access_control/backend/property_access_control.py b/products/access_control/backend/property_access_control.py
index d1e0b73d1a32..11bb0af936ed 100644
--- a/products/access_control/backend/property_access_control.py
+++ b/products/access_control/backend/property_access_control.py
@@ -69,7 +69,7 @@ def get_property_access_level(
user=user,
organization_id=property.team.organization_id,
)
- .only("id")
+ .only("id", "level")
.first()
)
@@ -126,7 +126,7 @@ def get_restricted_properties_for_team(
membership_qs = OrganizationMembership.objects.filter(
user=user,
organization_id=org_id,
- ).only("id")
+ ).only("id", "level")
membership = membership_qs.first()
if membership is None:
@@ -160,7 +160,14 @@ def _resolve_access_level(
"""
Resolves the effective access level from a set of rules for a single property definition,
following the hierarchy: user-specific > role-specific > default.
+
+ Org admins bypass member- and role-specific overrides and always get the default access level
+ for the property, mirroring the admin bypass in `UserAccessControl.access_level_for_object`.
"""
+ # Org admins bypass all access control rules and get full access
+ if membership is not None and membership.level >= OrganizationMembership.Level.ADMIN:
+ return get_default_access_level()
+
# 1. user-specific rule
if membership is not None:
for rule in rules:
diff --git a/products/access_control/backend/tests/test_property_access_control.py b/products/access_control/backend/tests/test_property_access_control.py
index cb3f4fa663ee..98deadcd27df 100644
--- a/products/access_control/backend/tests/test_property_access_control.py
+++ b/products/access_control/backend/tests/test_property_access_control.py
@@ -99,6 +99,55 @@ class TestGetPropertyAccessLevel(BaseTest):
assert level == PropertyAccessLevel.READ
assert level.grants_access()
+ def test_org_admin_bypasses_default_restriction(self):
+ from posthog.models import OrganizationMembership
+
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.prop_def,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ level = get_property_access_level(property=self.prop_def, user=self.user)
+ assert level == PropertyAccessLevel.READ_WRITE
+
+ def test_org_admin_bypasses_user_specific_restriction(self):
+ from posthog.models import OrganizationMembership
+
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.prop_def,
+ access_level=PropertyAccessLevel.NONE.value,
+ organization_member=self.organization_membership,
+ )
+ level = get_property_access_level(property=self.prop_def, user=self.user)
+ assert level == PropertyAccessLevel.READ_WRITE
+
+ def test_org_admin_bypasses_role_restriction(self):
+ from posthog.models import OrganizationMembership
+
+ from ee.models.rbac.role import Role, RoleMembership
+
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ role = Role.objects.create(name="Restricted", organization=self.organization)
+ RoleMembership.objects.create(role=role, user=self.user, organization_member=self.organization_membership)
+
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.prop_def,
+ access_level=PropertyAccessLevel.NONE.value,
+ role=role,
+ )
+ level = get_property_access_level(property=self.prop_def, user=self.user)
+ assert level == PropertyAccessLevel.READ_WRITE
+
def test_grants_access_helper(self):
assert PropertyAccessLevel.READ_WRITE.grants_access() is True
assert PropertyAccessLevel.READ.grants_access() is True