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: enforce prop access control across all supported tables (#74221)

Reece Jones345034659516
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index a0f7faf369c9..c43b51db25cc 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -166,7 +166,7 @@ execute_hogql_query(query=..., team=team, bypass_warehouse_access_control=True)
## 3. Property access control
-Hides sensitive event and person properties (e.g. `email`) from query results.
+Hides sensitive event, person, and group properties (e.g. `email`) from query results.
Rules live in the `PropertyAccessControl` model (`products/access_control/backend/models/property_access_control.py`).
Property access control is a paid feature, available on the Scale and Enterprise plans: it needs the `PROPERTY_ACCESS_CONTROL` entitlement, and without it resolution short-circuits to no restrictions.
@@ -179,6 +179,8 @@ They're masked when the query is printed to ClickHouse SQL, so a restricted read
- **Explicit reads** (`properties.email`) are replaced with `NULL`, and the resolver refuses to back them with a materialized column — `ClickHousePropertyResolver` in `posthog/hogql/transforms/clickhouse_property_resolution.py`.
- **Whole-blob reads** (`SELECT properties` or `SELECT *`) have the restricted keys stripped from the returned JSON via `JSONDropKeys(...)` — `ClickHousePrinter._maybe_apply_json_drop_keys()` in `posthog/hogql/printer/clickhouse.py`.
+Group restrictions retain their group type index, so a same-named property on another group type stays readable. The masking also applies to the Postgres-backed `system.groups.group_properties` field.
+
The restriction set is loaded once per query in `prepare_ast_for_printing()` and cached per `(team_id, user_id)` for the request lifetime.
### No user: default rules apply
@@ -193,7 +195,7 @@ Otherwise a denied user gets served an allowed user's cached rows.
The cache key is derived from `get_cache_payload()`:
-- `QueryRunner.get_cache_payload()` adds `restricted_properties` (sorted `(name, type)` pairs) when the user has property restrictions.
+- `QueryRunner.get_cache_payload()` adds named property restriction records, including the group type index, when the user has property restrictions.
- `AnalyticsQueryRunner.get_cache_payload()` adds `restricted_resources` (denied scopes) and `restricted_objects` (denied object IDs per scope) for levels 1 and 2.
Two things keep cache hit rates high:
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 4a3d9afa1121..8257c6ceed7a 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -3,6 +3,7 @@ from functools import cached_property
from typing import TYPE_CHECKING, Any, Literal, Optional
from posthog.hogql.constants import LimitContext
+from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.timings import HogQLTimings
from posthog.clickhouse.workload import Workload
@@ -31,7 +32,7 @@ def _default_modifiers() -> "HogQLQueryModifiers":
return HogQLQueryModifiers()
-@dataclass
+@dataclass(frozen=False)
class HogQLFieldAccess:
input: list[str]
type: Optional[Literal["event", "event.properties", "person", "person.properties"]]
@@ -39,7 +40,7 @@ class HogQLFieldAccess:
sql: str
-@dataclass
+@dataclass(frozen=False)
class HogQLContext:
"""Context given to a HogQL expression printer"""
@@ -131,10 +132,10 @@ class HogQLContext:
# filter and holding lazy introspection objects, so tables resolving to the same bound walk the
# database only once while surface-specific catalog metadata is fetched only when requested.
information_schema_introspection: Optional[Any] = field(default=None, compare=False, repr=False)
- # Property-level access control: set of (property_name, PropertyDefinition.Type) tuples
+ # Property-level access control: (property_name, PropertyDefinition.Type, group_type_index) tuples
# that the current user is denied access to. Populated before type resolution so that
# FieldType.get_child() can raise QueryError for restricted properties.
- restricted_properties: Optional[set[tuple[str, int]]] = None
+ restricted_properties: Optional[set[RestrictedProperty]] = None
# Per-query cache of CTE synthetic tables, keyed by id() of the CTE's SelectQueryType. Value pins a
# strong ref to the keyed type so its id can't be reused while cached; lookups verify identity.
diff --git a/posthog/hogql/database/schema/events.py b/posthog/hogql/database/schema/events.py
index 6e8266453ada..4218295bfbea 100644
--- a/posthog/hogql/database/schema/events.py
+++ b/posthog/hogql/database/schema/events.py
@@ -58,6 +58,8 @@ class EventsPersonSubTable(VirtualTable):
class EventsGroupSubTable(VirtualTable):
+ group_index: int = 0
+
def __init__(self, group_index: int):
super().__init__(
fields={
@@ -66,6 +68,7 @@ class EventsGroupSubTable(VirtualTable):
"properties": StringJSONDatabaseField(name=f"group{group_index}_properties", nullable=False),
}
)
+ self.group_index = group_index
def avoid_asterisk_fields(self):
return []
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index abccc7b9d5f6..39a3a8c84a57 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -35,7 +35,7 @@ from posthog.hogql.functions.udfs import JSON_DROP_KEYS_CLICKHOUSE_NAME
from posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_string
from posthog.hogql.printer.base import BasePrinter, get_channel_definition_dict, resolve_field_type
from posthog.hogql.printer.hogql import HogQLPrinter
-from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type
+from posthog.hogql.restricted_properties import RESTRICTABLE_JSON_BLOB_COLUMNS, restricted_property_keys_for_table_type
from posthog.hogql.type_system import parse_sql_runtime_type
from posthog.hogql.visitor import GetFieldsTraverser, clone_expr
@@ -583,10 +583,17 @@ class ClickHousePrinter(BasePrinter):
# 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"):
+ if resolved_field.name not in RESTRICTABLE_JSON_BLOB_COLUMNS:
return field_sql
- keys_to_drop = restricted_property_keys_for_table_type(type.table_type, self.context)
+ group_type_index = None
+ group_column_match = re.fullmatch(r"group(\d+)_properties", resolved_field.name)
+ if group_column_match:
+ group_type_index = int(group_column_match.group(1))
+
+ keys_to_drop = restricted_property_keys_for_table_type(
+ type.table_type, self.context, group_type_index=group_type_index
+ )
if not keys_to_drop:
return field_sql
diff --git a/posthog/hogql/printer/test/test_property_access_control.py b/posthog/hogql/printer/test/test_property_access_control.py
index 24cad8402f86..22f832540279 100644
--- a/posthog/hogql/printer/test/test_property_access_control.py
+++ b/posthog/hogql/printer/test/test_property_access_control.py
@@ -350,6 +350,79 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT person.properties FROM events")
assert "JSONDropKeys" not in sql
+ def _restrict_group_property(self, name: str = "arr", group_type_index: int = 0) -> None:
+ group_prop = PropertyDefinition.objects.create(
+ team=self.team,
+ name=name,
+ property_type="Numeric",
+ type=PropertyDefinition.Type.GROUP,
+ group_type_index=group_type_index,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=group_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ @parameterized.expand([("groups",), ("raw_groups",)])
+ def test_groups_tables_properties_blob_strips_restricted_keys(self, table_name: str):
+ # The groups blob (`group_properties`) was read unscrubbed, so `SELECT properties FROM groups` returned a group
+ # property an admin had restricted.
+ self._restrict_group_property()
+ sql, values = self._compile_select_with_values(f"SELECT properties FROM {table_name}")
+ assert "JSONDropKeys" in sql
+ assert "arr" not in sql
+ self._assert_value_present(values, "arr")
+
+ def test_denied_group_property_read_is_not_extracted(self):
+ # `SELECT properties.arr FROM groups` used to compile to a real JSON read of the restricted key.
+ self._restrict_group_property()
+ sql, values = self._compile_select_with_values("SELECT properties.arr FROM groups")
+ # The lazy groups table hoists the read into its argMax subquery, where the restricted value is a constant NULL.
+ assert "JSONExtract" not in sql
+ assert "'arr'" not in sql
+ assert not any("arr" in str(v) for v in values.values())
+
+ def test_system_groups_properties_blob_strips_restricted_keys(self):
+ self._restrict_group_property()
+ sql, values = self._compile_select_with_values("SELECT group_properties FROM system.groups")
+ assert "JSONDropKeys" in sql
+ assert "arr" not in sql
+ self._assert_value_present(values, "arr")
+
+ def test_denied_system_group_property_read_is_not_extracted(self):
+ self._restrict_group_property()
+ sql, values = self._compile_select_with_values("SELECT group_properties.arr FROM system.groups")
+ assert "JSONExtract" not in sql
+ assert "'arr'" not in sql
+ assert not any("arr" in str(value) for value in values.values())
+
+ def test_group_restriction_only_applies_to_matching_group_type(self):
+ self._restrict_group_property(group_type_index=0)
+ sql = self._compile_select("SELECT goe_1.properties.arr FROM events")
+ assert "JSONExtract" in sql
+ assert "arr" in sql
+
+ @parameterized.expand(
+ [
+ ("groups_lazy_join", "SELECT group_0.properties FROM events"),
+ ("group_on_events", "SELECT goe_0.properties FROM events"),
+ ]
+ )
+ def test_group_properties_blob_on_events_strips_restricted_keys(self, _case_name: str, query: str):
+ # Group properties reachable from events — through the groups lazy join and through the group-on-events blob
+ # columns — must be scrubbed too, or the restriction is one join away from bypassed.
+ self._restrict_group_property()
+ sql, values = self._compile_select_with_values(query)
+ assert "JSONDropKeys" in sql
+ assert "arr" not in sql
+ self._assert_value_present(values, "arr")
+
+ def test_group_restriction_does_not_affect_event_properties_blob(self):
+ self._restrict_group_property()
+ sql = self._compile_select("SELECT 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,
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 5cc68f3aa979..fb42c4ad428f 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -163,14 +163,16 @@ def prepare_ast_for_printing(
# load_property_metadata) — keeping it behind the call is what lets the printer package import
# without django.setup().
from products.access_control.backend.property_access_control import ( # noqa: PLC0415
- get_restricted_properties_for_team,
+ get_restricted_properties_with_group_type_index_for_team,
)
with context.timings.measure("load_restricted_properties"):
if context.team is not None and context.team.pk == context.team_id:
- context.restricted_properties = get_restricted_properties_for_team(user=context.user, team=context.team)
+ context.restricted_properties = get_restricted_properties_with_group_type_index_for_team(
+ user=context.user, team=context.team
+ )
else:
- context.restricted_properties = get_restricted_properties_for_team(
+ context.restricted_properties = get_restricted_properties_with_group_type_index_for_team(
user=context.user, team_id=context.team_id
)
diff --git a/posthog/hogql/property_access_types.py b/posthog/hogql/property_access_types.py
new file mode 100644
index 000000000000..8ae0f0cc224d
--- /dev/null
+++ b/posthog/hogql/property_access_types.py
@@ -0,0 +1,8 @@
+from posthog.dataclasses import frozen
+
+
+@frozen
+class RestrictedProperty:
+ name: str
+ property_type: int
+ group_type_index: int | None = None
diff --git a/posthog/hogql/restricted_properties.py b/posthog/hogql/restricted_properties.py
index cf54e7500da9..7f172bde929a 100644
--- a/posthog/hogql/restricted_properties.py
+++ b/posthog/hogql/restricted_properties.py
@@ -2,13 +2,32 @@ import structlog
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.schema.events import EventsPersonSubTable, EventsTable
+from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.schema.events import EventsGroupSubTable, EventsPersonSubTable, EventsTable
+from posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTable
from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
+from posthog.constants import GROUP_TYPES_LIMIT
+
logger = structlog.get_logger(__name__)
+# JSON blob columns that hold a restrictable property class, so the printer knows which blob reads to wrap in
+# JSONDropKeys. Everything here must be covered by a branch in `restricted_property_keys_for_table_type`, and vice
+# versa — a blob whose table type maps to a property class but whose column is missing here is read unscrubbed.
+RESTRICTABLE_JSON_BLOB_COLUMNS: frozenset[str] = frozenset(
+ {
+ "properties", # events.properties, persons.properties, groups.group_properties reads via the HogQL name
+ "person_properties", # EventsPersonSubTable (PoE mode)
+ "group_properties", # groups / raw_groups
+ # EventsGroupSubTable (group-on-events mode) exposes each group type's blob on the events table.
+ *(f"group{index}_properties" for index in range(GROUP_TYPES_LIMIT)),
+ }
+)
+
-def restricted_property_keys_for_table_type(table_type: ast.Type, context: HogQLContext) -> set[str]:
+def restricted_property_keys_for_table_type(
+ table_type: ast.Type, context: HogQLContext, *, group_type_index: int | None = None
+) -> set[str]:
"""Top-level property names restricted by property-level access control for a table, or an empty set.
Single source of truth shared by the ClickHouse printer (which JSONDropKeys-wraps the blob) and the property
@@ -34,13 +53,35 @@ def restricted_property_keys_for_table_type(table_type: ast.Type, context: HogQL
logger.warning("restricted_property_table_resolution_failed", table_type=type(table_type).__name__)
return set()
+ # EventsPersonSubTable and EventsGroupSubTable are virtual tables over `events`, not EventsTable subclasses, but
+ # they carry person/group properties — match them before the EventsTable branch either way.
if isinstance(table, EventsPersonSubTable):
prop_def_type = PropertyDefinition.Type.PERSON
+ elif isinstance(table, EventsGroupSubTable):
+ prop_def_type = PropertyDefinition.Type.GROUP
+ group_type_index = table.group_index
elif isinstance(table, EventsTable):
prop_def_type = PropertyDefinition.Type.EVENT
elif isinstance(table, (PersonsTable, RawPersonsTable)):
prop_def_type = PropertyDefinition.Type.PERSON
+ elif isinstance(table, (GroupsTable, RawGroupsTable)) or (
+ isinstance(table, PostgresTable) and table.postgres_table_name == "posthog_group"
+ ):
+ prop_def_type = PropertyDefinition.Type.GROUP
else:
+ # PropertyDefinition.Type.SESSION is deliberately absent: the sessions tables expose each session property as
+ # its own column rather than a JSON blob, so there is nothing for this function's callers to scrub. Restricting
+ # a session property therefore has no query-time effect yet — enforcing it needs field-level denial, not a
+ # blob-key drop.
return set()
- return {name for name, ptype in context.restricted_properties if ptype == prop_def_type}
+ return {
+ restriction.name
+ for restriction in context.restricted_properties
+ if restriction.property_type == prop_def_type
+ and (
+ prop_def_type != PropertyDefinition.Type.GROUP
+ or group_type_index is None
+ or restriction.group_type_index == group_type_index
+ )
+ }
diff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py
index 1044be850aec..85e2af1b6c11 100644
--- a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py
+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py
@@ -37,6 +37,7 @@ from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.util.where_clause_extractor import EventsPredicatePushdownExtractor
from posthog.hogql.parser import parse_select
from posthog.hogql.printer.utils import prepare_and_print_ast
+from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.resolver import resolve_types
from posthog.hogql.test.utils import pretty_print_in_tests
@@ -146,7 +147,9 @@ class TestEventsPredicatePushdownTransform(BaseTest):
enable_select_queries=True,
modifiers=HogQLQueryModifiers(pushDownPredicates=push_down),
)
- context.restricted_properties = {("email", PropertyDefinition.Type.EVENT)}
+ context.restricted_properties = {
+ RestrictedProperty(name="email", property_type=PropertyDefinition.Type.EVENT)
+ }
query, _ = prepare_and_print_ast(parse_select(select), context, "clickhouse")
return pretty_print_in_tests(query, self.team.pk)
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index 5c043d8bd588..8537013b8bbd 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -36,6 +36,7 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.property_planner import (
PropertyComparisonPlan,
PropertyLiteralConversion,
@@ -298,7 +299,7 @@ class TestPropertyTypes(BaseTest):
def _plan_where_comparison(
self,
select: str,
- restricted_properties: set[tuple[str, int]] | None = None,
+ restricted_properties: set[RestrictedProperty] | None = None,
) -> PropertyComparisonPlan:
context, resolved = self._resolve_select(select, restricted_properties=restricted_properties)
comparison = cast(ast.CompareOperation, resolved.where)
@@ -309,7 +310,7 @@ class TestPropertyTypes(BaseTest):
def _resolve_select(
self,
select: str,
- restricted_properties: set[tuple[str, int]] | None = None,
+ restricted_properties: set[RestrictedProperty] | None = None,
) -> tuple[HogQLContext, ast.SelectQuery]:
"""Resolve types and build the property-swapper registry without preparing further.
@@ -329,7 +330,7 @@ class TestPropertyTypes(BaseTest):
def _prepare_select(
self,
select: str,
- restricted_properties: set[tuple[str, int]] | None = None,
+ restricted_properties: set[RestrictedProperty] | None = None,
) -> tuple[HogQLContext, ast.SelectQuery]:
expr = parse_select(select)
context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)
@@ -503,7 +504,9 @@ class TestPropertyTypes(BaseTest):
with materialized("events", "$browser", is_nullable=True, create_minmax_index=True):
plan = self._plan_where_comparison(
"select count() from events where properties.$browser < 'm'",
- restricted_properties={("$browser", PropertyDefinition.Type.EVENT)},
+ restricted_properties={
+ RestrictedProperty(name="$browser", property_type=PropertyDefinition.Type.EVENT)
+ },
)
assert plan.access.source.kind == PropertySourceKind.JSON
@@ -756,7 +759,7 @@ class TestPropertyTypes(BaseTest):
class TestJSONExtractToMaterializedColumn(ClickhouseTestMixin, BaseTest):
- def _print_select(self, select: str, restricted_properties: set[tuple[str, int]] | None = None):
+ def _print_select(self, select: str, restricted_properties: set[RestrictedProperty] | None = None):
expr = parse_select(select)
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
if restricted_properties is not None:
@@ -951,8 +954,8 @@ class TestJSONExtractToMaterializedColumn(ClickhouseTestMixin, BaseTest):
"JSONHas(properties, 'secret') "
"from events",
restricted_properties={
- ("secret", PropertyDefinition.Type.EVENT),
- ("email", PropertyDefinition.Type.EVENT),
+ RestrictedProperty(name="secret", property_type=PropertyDefinition.Type.EVENT),
+ RestrictedProperty(name="email", property_type=PropertyDefinition.Type.EVENT),
},
)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 3f47743b1b6d..b6e73d3c2370 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -2585,19 +2585,35 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"customer_analytics": read("customer_analytics_config", lambda: self.team.customer_analytics_config),
}
- def _get_property_access_restrictions(self) -> list[tuple[str, int]] | None:
- """Returns a sorted list of restricted (property_name, type) pairs for the current user, or None if no restrictions.
+ def _get_property_access_restrictions(self) -> list[dict[str, str | int | None]] | None:
+ """Returns sorted restricted property metadata for the current user, or None if unrestricted.
The underlying ``get_restricted_properties_for_team`` memoizes per request,
so rendering a dashboard with N insights issues one PropertyAccessControl
lookup per (team, user) pair instead of N.
"""
- from products.access_control.backend.property_access_control import get_restricted_properties_for_team
+ from products.access_control.backend.property_access_control import (
+ get_restricted_properties_with_group_type_index_for_team,
+ )
- restricted = get_restricted_properties_for_team(user=self.user, team=self.team)
+ restricted = get_restricted_properties_with_group_type_index_for_team(user=self.user, team=self.team)
if not restricted:
return None
- return sorted(restricted)
+ return [
+ {
+ "name": restriction.name,
+ "property_type": restriction.property_type,
+ "group_type_index": restriction.group_type_index,
+ }
+ for restriction in sorted(
+ restricted,
+ key=lambda restriction: (
+ restriction.name,
+ restriction.property_type,
+ restriction.group_type_index if restriction.group_type_index is not None else -1,
+ ),
+ )
+ ]
def get_cache_key(self) -> str:
return generate_cache_key(self.team.pk, f"query_{bytes.decode(to_json(self.get_cache_payload()))}")
diff --git a/products/access_control/backend/property_access_control.py b/products/access_control/backend/property_access_control.py
index 83416d1432d2..c3731dc83c08 100644
--- a/products/access_control/backend/property_access_control.py
+++ b/products/access_control/backend/property_access_control.py
@@ -12,6 +12,8 @@ from django.dispatch import receiver
from celery.signals import task_postrun, task_prerun
+from posthog.hogql.property_access_types import RestrictedProperty
+
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership
from posthog.models.team import Team
@@ -35,7 +37,7 @@ from products.access_control.backend.models.role import RoleMembership
# (`task_prerun` / `task_postrun`); callers running outside those boundaries (management
# commands, ad-hoc scripts, code paths we haven't instrumented) simply pay the query cost
# rather than risk stale authorization data.
-_restriction_cache_var: ContextVar[dict[tuple[int, int | None], set[tuple[str, int]]] | None] = ContextVar(
+_restriction_cache_var: ContextVar[dict[tuple[int, int | None], set[RestrictedProperty]] | None] = ContextVar(
"property_access_restriction_cache", default=None
)
@@ -96,6 +98,7 @@ __all__ = [
"get_non_writable_property_names",
"get_property_access_level",
"get_restricted_properties_for_team",
+ "get_restricted_properties_with_group_type_index_for_team",
"get_restricted_property_names",
"is_property_access_control_enabled",
"strip_restricted_properties",
@@ -275,14 +278,14 @@ def get_non_writable_property_names(
return non_writable
-def get_restricted_properties_for_team(
+def get_restricted_properties_with_group_type_index_for_team(
*,
user: User | SyntheticUser | SharedLinkUser | None,
team: Team | None = None,
team_id: int | None = None,
-) -> set[tuple[str, int]]:
+) -> set[RestrictedProperty]:
"""
- Returns the set of (property_name, property_type) pairs that are restricted for the given user on the team.
+ Returns the set of (property_name, property_type, group_type_index) tuples that are restricted for the given user.
This is designed to be called once per query to batch-load all restrictions rather than checking one property
at a time.
@@ -297,7 +300,7 @@ def get_restricted_properties_for_team(
:param team_id: The team's id, for callers that don't have the instance loaded. Pass exactly one of
``team`` and ``team_id``.
- :returns: A set of (property_name, property_definition_type) tuples that are restricted.
+ :returns: Restricted property metadata. ``group_type_index`` is only set for group properties.
"""
# Shared-link user and synthetic user have no membership to resolve restrictions against;
# treat them as userless so only the default rules apply.
@@ -320,7 +323,7 @@ def get_restricted_properties_for_team(
# Short-circuit: no PROPERTY_ACCESS_CONTROL means no property access control rules exist
if not is_property_access_control_enabled(team=team, team_id=team_id):
- empty_no_feature: set[tuple[str, int]] = set()
+ empty_no_feature: set[RestrictedProperty] = set()
if cache is not None:
cache[cache_key] = empty_no_feature
return empty_no_feature
@@ -332,7 +335,7 @@ def get_restricted_properties_for_team(
)
if not rules.exists():
- empty: set[tuple[str, int]] = set()
+ empty: set[RestrictedProperty] = set()
if cache is not None:
cache[cache_key] = empty
return empty
@@ -366,7 +369,7 @@ def get_restricted_properties_for_team(
RoleMembership.objects.filter(organization_member=membership).values_list("role_id", flat=True)
)
- restricted: set[tuple[str, int]] = set()
+ restricted: set[RestrictedProperty] = set()
for _prop_def_id, prop_rules in rules_by_property.items():
prop_def = prop_rules[0].property_definition
@@ -376,13 +379,30 @@ def get_restricted_properties_for_team(
user_role_ids=user_role_ids,
)
if prop_def is not None and not level.grants_access():
- restricted.add((prop_def.name, prop_def.type))
+ restricted.add(
+ RestrictedProperty(
+ name=prop_def.name,
+ property_type=prop_def.type,
+ group_type_index=prop_def.group_type_index,
+ )
+ )
if cache is not None:
cache[cache_key] = restricted
return restricted
+def get_restricted_properties_for_team(
+ *,
+ user: User | SyntheticUser | SharedLinkUser | None,
+ team: Team | None = None,
+ team_id: int | None = None,
+) -> set[tuple[str, int]]:
+ """Return restricted property names and types for callers that do not need group index scope."""
+ restrictions = get_restricted_properties_with_group_type_index_for_team(user=user, team=team, team_id=team_id)
+ return {(restriction.name, restriction.property_type) for restriction in restrictions}
+
+
def _resolve_access_level(
rules: list[PropertyAccessControl],
*,
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index 26621cc2c94d..f0cb5d3933df 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -63,7 +63,9 @@ from posthog.models.user import User
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.utils import get_safe_cache, safe_cache_set
-from products.access_control.backend.property_access_control import get_restricted_properties_for_team
+from products.access_control.backend.property_access_control import (
+ get_restricted_properties_with_group_type_index_for_team,
+)
from products.experiments.backend.hogql_queries.exposure_query_logic import (
get_test_accounts_filter,
normalize_to_exposure_criteria,
@@ -353,7 +355,21 @@ def _cache_key(
default_exposure_event,
# Property restrictions are compiled into the SQL, so unlike recording access they
# can't be re-filtered on read; a restriction change has to miss the cache instead.
- sorted(get_restricted_properties_for_team(user=user, team=team)),
+ [
+ {
+ "name": restriction.name,
+ "property_type": restriction.property_type,
+ "group_type_index": restriction.group_type_index,
+ }
+ for restriction in sorted(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
+ key=lambda restriction: (
+ restriction.name,
+ restriction.property_type,
+ restriction.group_type_index if restriction.group_type_index is not None else -1,
+ ),
+ )
+ ],
]
)
digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.py
index 6f18d66dfa31..bb9741966839 100644
--- a/products/experiments/backend/session_event_deltas.py
+++ b/products/experiments/backend/session_event_deltas.py
@@ -101,7 +101,9 @@ from posthog.models.user import User
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.utils import get_safe_cache, pluralize, safe_cache_set
-from products.access_control.backend.property_access_control import get_restricted_properties_for_team
+from products.access_control.backend.property_access_control import (
+ get_restricted_properties_with_group_type_index_for_team,
+)
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
from products.experiments.backend.hogql_queries.exposure_query_logic import (
get_multiple_variant_handling_from_experiment,
@@ -751,7 +753,21 @@ def _cache_key(
sorted(updated.isoformat() for updated in experiment.saved_metrics.values_list("updated_at", flat=True)),
# Property restrictions are compiled into the SQL, so a restriction change has to miss
# the cache rather than be re-applied on read.
- sorted(get_restricted_properties_for_team(user=user, team=team)),
+ [
+ {
+ "name": restriction.name,
+ "property_type": restriction.property_type,
+ "group_type_index": restriction.group_type_index,
+ }
+ for restriction in sorted(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
+ key=lambda restriction: (
+ restriction.name,
+ restriction.property_type,
+ restriction.group_type_index if restriction.group_type_index is not None else -1,
+ ),
+ )
+ ],
]
)
digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
index c14352c15165..119c99d20040 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
@@ -18,6 +18,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.visitor import TraversingVisitor
from posthog.models import PropertyDefinition
@@ -880,10 +881,10 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
def restrictions_for(*, user, **_kwargs) -> set:
if user is None or not restricted:
return set()
- return {("plan", PropertyDefinition.Type.EVENT)}
+ return {RestrictedProperty(name="plan", property_type=PropertyDefinition.Type.EVENT)}
with patch(
- "products.access_control.backend.property_access_control.get_restricted_properties_for_team",
+ "products.access_control.backend.property_access_control.get_restricted_properties_with_group_type_index_for_team",
side_effect=restrictions_for,
):
prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")