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(hogql): match REST when object grants outlive resource access (#79740)

Reece Jones79a9533db44b
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 111ac0c2e84d..9d197185bc2d 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -466,8 +466,8 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:
@cache
-def _system_table_access_scopes() -> Mapping[str, APIScopeObject]:
- """Table name -> access scope for the access-controlled Postgres system tables.
+def _scoped_system_tables() -> Mapping[str, PostgresTable]:
+ """Table name -> the access-controlled Postgres system table itself.
Cached for the process lifetime — this result directly gates table visibility in access-control
decisions, so every entry here MUST remain process-static. Do NOT make a system table's
@@ -478,7 +478,7 @@ def _system_table_access_scopes() -> Mapping[str, APIScopeObject]:
"""
return MappingProxyType(
{
- name: table_node.table.access_scope
+ name: table_node.table
for name, table_node in SystemTables().children.items()
if isinstance(table_node.table, PostgresTable) and table_node.table.access_scope is not None
}
@@ -489,7 +489,7 @@ def _system_table_access_scopes() -> Mapping[str, APIScopeObject]:
def _system_table_required_features() -> Mapping[str, str]:
"""Table name -> required AvailableFeature for system tables behind a billing entitlement.
- Same process-static invariant as _system_table_access_scopes: the entitlement a table *requires*
+ Same process-static invariant as _scoped_system_tables: the entitlement a table *requires*
is a static property of the table. What varies per organization is whether that entitlement is
*available*, which is resolved uncached in _unentitled_system_tables. Returned read-only so a
caller can't mutate the shared cached mapping.
@@ -535,7 +535,7 @@ def _compute_system_table_access_decision(
from posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl # noqa: PLC0415
from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415
- scoped_tables = _system_table_access_scopes()
+ scoped_tables = _scoped_system_tables()
# Applies to every principal below, admins included - an entitlement the organization does not
# have cannot be granted by a role.
unentitled = _unentitled_system_tables(team)
@@ -544,7 +544,7 @@ def _compute_system_table_access_decision(
if user is None or isinstance(user, SyntheticUser | SharedLinkUser):
readable_scopes = user.readable_system_table_access_scopes() if user is not None else set()
return None, unentitled | {
- name for name, access_scope in scoped_tables.items() if access_scope not in readable_scopes
+ name for name, table in scoped_tables.items() if table.access_scope not in readable_scopes
}
user_access_control = user_access_control or UserAccessControl(user=user, team=team)
@@ -553,11 +553,21 @@ def _compute_system_table_access_decision(
if org_membership and org_membership.level >= OrganizationMembership.Level.ADMIN:
return user_access_control, unentitled
+ # Resources the user holds object-level grants on despite having no resource-level access. REST
+ # serves those routes and narrows the rows to the grants; the printer guard does the same, so the
+ # table stays queryable here instead of disappearing (see build_access_control_guard).
+ allowlisted_scopes = user_access_control.allowlisted_resource_ids_by_scope
+
denied: set[str] = set(unentitled)
- for name, access_scope in scoped_tables.items():
+ for name, table in scoped_tables.items():
+ access_scope = cast(APIScopeObject, table.access_scope)
access_level = user_access_control.access_level_for_resource(access_scope)
if access_level and access_level != NO_ACCESS_LEVEL:
continue # User has access, keep it
+ # Keep the table only when the guard can actually narrow its rows to the grant, so a table
+ # whose ids don't key those grants (resource_level_access_only) still fails closed.
+ if access_scope in allowlisted_scopes and table.access_control_id is not None:
+ continue
denied.add(name)
return user_access_control, denied
diff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.py
index 8a72cc9d38fd..0534cc83c778 100644
--- a/posthog/hogql/database/postgres_table.py
+++ b/posthog/hogql/database/postgres_table.py
@@ -97,6 +97,16 @@ class PostgresTable(FunctionCallTable):
# to the foreign key pointing at that parent (e.g. system.dashboard_tiles -> "dashboard_id"),
# so denying the parent also hides its child rows.
access_control_id_field: Optional[str] = None
+ # Column holding the id of the user who created the access-controlled object, mirroring REST's
+ # creator exemption in `filter_queryset_by_access_level`: a creator keeps access to their own
+ # object even when object-level rules deny it.
+ access_control_creator_id_field: Optional[str] = None
+ # Set when object-level grants under `access_scope` can never key this table's rows: it holds
+ # team-level definitions shared across every object of that resource and is gated at resource
+ # level only (e.g. system.message_categories under "hog_flow"). Grant ids then live in a
+ # different space than this table's ids, so its rows can't be narrowed to a grant and
+ # resource-level access is required to query it at all.
+ resource_level_access_only: bool = False
predicates: list[Expr] = []
def get_predicates(self) -> list[Expr]:
@@ -108,8 +118,22 @@ class PostgresTable(FunctionCallTable):
@property
def access_control_id(self) -> Optional[str]:
+ if self.resource_level_access_only:
+ return None
return self.access_control_id_field or self.primary_key
+ @property
+ def access_control_creator_id(self) -> Optional[str]:
+ """Creator column to exempt from object-level filtering, or None when there is nothing to exempt.
+
+ Only meaningful when the rows ARE the access-controlled object: a child row's own creator
+ says nothing about who created the parent the grant is keyed on, so the exemption is dropped
+ for child tables rather than applied to the wrong person.
+ """
+ if self.access_control_id_field is not None or self.resource_level_access_only:
+ return None
+ return self.access_control_creator_id_field
+
def to_printed_hogql(self):
return escape_hogql_identifier(self.name)
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 23b315280292..d27850c7917c 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -371,12 +371,16 @@ dashboards: PostgresTable = PostgresTable(
name="dashboards",
postgres_table_name="posthog_dashboard",
access_scope="dashboard",
+ access_control_creator_id_field="created_by_id",
description="Dashboards: collections of insight tiles; one row per dashboard.",
fields={
"id": IntegerDatabaseField(name="id", description="Dashboard id."),
"team_id": IntegerDatabaseField(name="team_id"),
"name": StringDatabaseField(name="name", description="Dashboard name."),
"description": StringDatabaseField(name="description", description="Dashboard description."),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the dashboard."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the dashboard was created."),
"_deleted": BooleanDatabaseField(name="deleted", hidden=True),
"deleted": ExpressionField(
@@ -442,6 +446,7 @@ datasets: PostgresTable = PostgresTable(
name="datasets",
postgres_table_name="llm_analytics_dataset_v2",
access_scope="dataset",
+ access_control_creator_id_field="created_by_id",
description="AI observability datasets used to curate inputs and expected outputs; one row per dataset.",
fields={
"id": UUIDDatabaseField(name="id", description="Dataset UUID."),
@@ -558,6 +563,7 @@ insights: PostgresTable = PostgresTable(
name="insights",
postgres_table_name="posthog_dashboarditem",
access_scope="insight",
+ access_control_creator_id_field="created_by_id",
description="Saved insights (the model is historically named 'dashboarditem'); one row per insight, including its query definition.",
fields={
"id": IntegerDatabaseField(name="id", description="Insight id."),
@@ -610,12 +616,16 @@ experiments: PostgresTable = PostgresTable(
name="experiments",
postgres_table_name="posthog_experiment",
access_scope="experiment",
+ access_control_creator_id_field="created_by_id",
description="A/B test experiments; one row per experiment, linked to the feature flag that controls variant assignment.",
fields={
"id": IntegerDatabaseField(name="id", description="Experiment id."),
"team_id": IntegerDatabaseField(name="team_id"),
"name": StringDatabaseField(name="name", description="Experiment name."),
"description": StringDatabaseField(name="description", description="Experiment description/hypothesis."),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the experiment."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the experiment was created."),
"updated_at": DateTimeDatabaseField(name="updated_at", description="When the experiment was last updated."),
"filters": StringJSONDatabaseField(
@@ -649,6 +659,7 @@ data_warehouse_sources: PostgresTable = PostgresTable(
name="data_warehouse_sources",
postgres_table_name="posthog_externaldatasource",
access_scope="external_data_source",
+ access_control_creator_id_field="created_by_id",
description="Configured data warehouse sources (Stripe, Postgres, Hubspot, etc.); one row per connected source. "
"Covers both synced sources, whose tables are queryable by name from this catalog, and direct "
"connections, whose tables are live-queried by passing the source's id as the query's connection id — "
@@ -720,6 +731,9 @@ data_warehouse_sources: PostgresTable = PostgresTable(
"prefix": StringDatabaseField(
name="prefix", description="Table-name prefix applied to all tables synced from this source."
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the source."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the source was connected."),
"updated_at": DateTimeDatabaseField(name="updated_at", description="When the source config was last updated."),
"_deleted": BooleanDatabaseField(name="deleted", hidden=True),
@@ -905,6 +919,7 @@ endpoints: PostgresTable = PostgresTable(
postgres_table_name="endpoints_endpoint",
predicates=[parse_expr("deleted != true")],
access_scope="endpoint",
+ access_control_creator_id_field="created_by_id",
description="Data-modeling endpoints: named, callable saved queries; one row per endpoint (deleted endpoints are excluded).",
fields={
"id": StringDatabaseField(name="id", description="Endpoint UUID."),
@@ -923,6 +938,9 @@ endpoints: PostgresTable = PostgresTable(
"derived_from_insight": StringDatabaseField(
name="derived_from_insight", description="Short id of the insight this endpoint was created from, if any."
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the endpoint."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the endpoint was created."),
"updated_at": DateTimeDatabaseField(name="updated_at", description="When the endpoint was last updated."),
"last_executed_at": DateTimeDatabaseField(
@@ -937,6 +955,7 @@ feature_flags: PostgresTable = PostgresTable(
name="feature_flags",
postgres_table_name="posthog_featureflag",
access_scope="feature_flag",
+ access_control_creator_id_field="created_by_id",
description="Feature flags; one row per flag, with its targeting filters and rollout configuration.",
fields={
"id": IntegerDatabaseField(name="id", description="Flag id."),
@@ -950,6 +969,9 @@ feature_flags: PostgresTable = PostgresTable(
name="rollout_percentage",
description="Top-level rollout percentage (0-100); detailed rules live in filters.",
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the flag."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the flag was created."),
"_deleted": BooleanDatabaseField(name="deleted", hidden=True),
"deleted": ExpressionField(
@@ -1084,6 +1106,7 @@ session_recording_playlists: PostgresTable = PostgresTable(
name="session_recording_playlists",
postgres_table_name="posthog_sessionrecordingplaylist",
access_scope="session_recording_playlist",
+ access_control_creator_id_field="created_by_id",
description="Saved playlists/collections of session recordings, defined by filters or pinned recordings; one row per playlist.",
fields={
"id": IntegerDatabaseField(name="id", description="Playlist id."),
@@ -1179,6 +1202,7 @@ surveys: PostgresTable = PostgresTable(
name="surveys",
postgres_table_name="posthog_survey",
access_scope="survey",
+ access_control_creator_id_field="created_by_id",
description="In-app surveys; one row per survey, including its questions and display configuration.",
fields={
"id": IntegerDatabaseField(name="id", description="Survey id."),
@@ -1193,6 +1217,9 @@ surveys: PostgresTable = PostgresTable(
"end_date": DateTimeDatabaseField(
name="end_date", description="When the survey was stopped; NULL if still running."
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the survey."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the survey was created."),
},
)
@@ -1290,6 +1317,7 @@ actions: PostgresTable = PostgresTable(
name="actions",
postgres_table_name="posthog_action",
access_scope="action",
+ access_control_creator_id_field="created_by_id",
description="Actions: named event matchers that group raw events into meaningful user actions; one row per action.",
fields={
"id": IntegerDatabaseField(name="id", description="Action id."),
@@ -1302,6 +1330,9 @@ actions: PostgresTable = PostgresTable(
expr=ast.Call(name="toInt", args=[ast.Field(chain=["_deleted"])]),
description="1 if the action has been deleted, 0 otherwise.",
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the action."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the action was created."),
"updated_at": DateTimeDatabaseField(name="updated_at", description="When the action was last updated."),
"steps_json": StringJSONDatabaseField(
@@ -1358,6 +1389,7 @@ hog_flows: PostgresTable = PostgresTable(
name="hog_flows",
postgres_table_name="posthog_hogflow",
access_scope="hog_flow",
+ access_control_creator_id_field="created_by_id",
description="Hog flows: multi-step automation/messaging workflows; one row per flow, with its graph of actions and edges.",
fields={
"id": StringDatabaseField(name="id", description="Flow UUID."),
@@ -1374,6 +1406,9 @@ hog_flows: PostgresTable = PostgresTable(
),
"edges": StringJSONDatabaseField(name="edges", description="JSON edges connecting actions in the flow graph."),
"actions": StringJSONDatabaseField(name="actions", description="JSON nodes/actions that make up the flow."),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the flow."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the flow was created."),
"updated_at": DateTimeDatabaseField(name="updated_at", description="When the flow was last updated."),
},
@@ -1426,6 +1461,9 @@ message_categories: PostgresTable = PostgresTable(
name="message_categories",
postgres_table_name="posthog_messagecategory",
access_scope="hog_flow",
+ # Team-level messaging data not tied to any single flow, so a per-flow grant never keys these
+ # rows: resource-level "hog_flow" access is what MessagePreferencesViewSet checks too.
+ resource_level_access_only=True,
description="Message categories recipients can opt out of; one row per category. Join its id against the keys of message_recipient_preferences.preferences.",
fields={
"id": StringDatabaseField(name="id", description="Category UUID, used as the key in recipient preferences."),
@@ -1455,6 +1493,9 @@ message_recipient_preferences: PostgresTable = PostgresTable(
name="message_recipient_preferences",
postgres_table_name="posthog_messagerecipientpreference",
access_scope="hog_flow",
+ # Team-level messaging data not tied to any single flow, so a per-flow grant never keys these
+ # rows: resource-level "hog_flow" access is what MessagePreferencesViewSet checks too.
+ resource_level_access_only=True,
description="Messaging preferences per recipient; one row per recipient. The preferences map records opt-outs and opt-ins per message category.",
fields={
"id": StringDatabaseField(name="id", description="Preference row UUID."),
@@ -1524,6 +1565,7 @@ notebooks: PostgresTable = PostgresTable(
name="notebooks",
postgres_table_name="posthog_notebook",
access_scope="notebook",
+ access_control_creator_id_field="created_by_id",
description="Notebooks: rich-text documents that embed insights, recordings, and queries; one row per notebook.",
fields={
"id": StringDatabaseField(name="id", description="Notebook UUID."),
@@ -1552,6 +1594,9 @@ notebooks: PostgresTable = PostgresTable(
name="visibility", description="Visibility setting, e.g. 'private' or shared."
),
"version": IntegerDatabaseField(name="version", description="Notebook version number."),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the notebook."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the notebook was created."),
"last_modified_at": DateTimeDatabaseField(
name="last_modified_at", description="When the notebook was last modified."
@@ -2123,6 +2168,7 @@ evaluation_directories: PostgresTable = PostgresTable(
name="evaluation_directories",
postgres_table_name="llm_analytics_evaluationdirectory",
access_scope="evaluation",
+ access_control_creator_id_field="created_by_id",
description="Directories used to organize online evaluations; one row per directory.",
fields={
"id": UUIDDatabaseField(name="id", description="Directory UUID."),
@@ -2142,6 +2188,7 @@ evaluations: PostgresTable = PostgresTable(
name="evaluations",
postgres_table_name="llm_analytics_evaluation",
access_scope="evaluation",
+ access_control_creator_id_field="created_by_id",
description="Online evaluations that score AI generations or traces; one row per evaluation.",
fields={
"id": UUIDDatabaseField(name="id", description="Evaluation UUID."),
@@ -2185,6 +2232,7 @@ review_queues: PostgresTable = PostgresTable(
name="review_queues",
postgres_table_name="llm_analytics_reviewqueue",
access_scope="llm_analytics",
+ access_control_creator_id_field="created_by_id",
description="AI observability review queues: named lists of traces queued for human review; one row per queue.",
fields={
"id": UUIDDatabaseField(name="id", description="Queue UUID."),
@@ -2213,6 +2261,7 @@ review_queue_items: PostgresTable = PostgresTable(
name="review_queue_items",
postgres_table_name="llm_analytics_reviewqueueitem",
access_scope="llm_analytics",
+ access_control_creator_id_field="created_by_id",
description="Individual LLM traces queued in a review queue; one row per queued trace.",
fields={
"id": UUIDDatabaseField(name="id", description="Queue item UUID."),
@@ -2244,6 +2293,7 @@ trace_reviews: PostgresTable = PostgresTable(
name="trace_reviews",
postgres_table_name="llm_analytics_tracereview",
access_scope="llm_analytics",
+ access_control_creator_id_field="created_by_id",
description="Human reviews of LLM traces; one row per review, with scores attached in trace_review_scores.",
fields={
"id": UUIDDatabaseField(name="id", description="Review UUID."),
@@ -2322,6 +2372,7 @@ score_definitions: PostgresTable = PostgresTable(
name="score_definitions",
postgres_table_name="llm_analytics_scoredefinition",
access_scope="llm_analytics",
+ access_control_creator_id_field="created_by_id",
description="Definitions of scores/metrics used when reviewing LLM traces; one row per score definition.",
fields={
"id": UUIDDatabaseField(name="id", description="Score definition UUID."),
@@ -2349,6 +2400,7 @@ early_access_features: PostgresTable = PostgresTable(
name="early_access_features",
postgres_table_name="posthog_earlyaccessfeature",
access_scope="early_access_feature",
+ access_control_creator_id_field="created_by_id",
description="Early access features users can opt into; one row per feature, backed by a feature flag.",
fields={
"id": StringDatabaseField(name="id", description="Early access feature UUID."),
@@ -2364,6 +2416,9 @@ early_access_features: PostgresTable = PostgresTable(
"documentation_url": StringDatabaseField(
name="documentation_url", description="Link to the feature's documentation."
),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="User who created the feature."
+ ),
"created_at": DateTimeDatabaseField(name="created_at", description="When the feature was created."),
},
)
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 45d497dd9df7..716b7b94515a 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -3101,6 +3101,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -4647,6 +4657,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -5588,6 +5608,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -5717,6 +5747,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -6487,6 +6527,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -6794,6 +6844,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -6982,6 +7042,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -7624,6 +7694,16 @@
"table": null,
"type": "json"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -8843,6 +8923,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -10171,6 +10261,16 @@
"table": null,
"type": "datetime"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -13211,6 +13311,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -14757,6 +14867,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -15698,6 +15818,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -15827,6 +15957,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -16597,6 +16737,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -16904,6 +17054,16 @@
"table": null,
"type": "string"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -17092,6 +17252,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -17734,6 +17904,16 @@
"table": null,
"type": "json"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -18953,6 +19133,16 @@
"table": null,
"type": "integer"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
@@ -20281,6 +20471,16 @@
"table": null,
"type": "datetime"
},
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
"created_at": {
"chain": null,
"fields": null,
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index 67ef620ed5eb..1e2672b2f46a 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -45,18 +45,12 @@ _FACADE_OBJECT_GRANT_TABLES: dict[str, str] = {
"customer_analytics_account": "account",
}
-# Team-level definition tables gated under an object-restrictable scope for resource-level
-# access only: their rows describe shapes shared by every account, not any single account's
-# data, so object-level denies don't apply (the default pk guard never matches a denied id).
+# Team-level definition tables gated under an object-restrictable scope for resource-level access
+# only, declared by `resource_level_access_only` on the table itself because it drives the runtime
+# decision too: their rows describe shapes shared by every object of the resource, so object-level
+# grants never key them.
_SCOPE_GATED_METADATA_TABLES: frozenset[str] = frozenset(
- {
- "custom_property_definitions",
- "account_relationship_definitions",
- # Team-level messaging data not tied to any single flow; MessagePreferencesViewSet
- # grants the same rows at resource level (hog_flow:read) with no object-level check.
- "message_categories",
- "message_recipient_preferences",
- }
+ name for name, table in _SCOPED_SYSTEM_TABLES.items() if table.resource_level_access_only
)
@@ -511,6 +505,55 @@ class TestObjectAccessControlIdField(SimpleTestCase):
)
+class TestObjectAccessControlCreatorField(SimpleTestCase):
+ """REST exempts an object's creator from object-level denial
+ (`~Q(created_by=self._user)` in `filter_queryset_by_access_level`), and the HogQL guard
+ reproduces that only for tables that declare `access_control_creator_id_field` and expose the
+ column. A restrictable table that has a creator but doesn't declare it silently hides rows from
+ the person who created them, so require the declaration wherever REST would honor it."""
+
+ @parameterized.expand(sorted(_SCOPED_SYSTEM_TABLES))
+ def test_creator_field_is_declared_and_queryable(self, table_name: str) -> None:
+ table = _SCOPED_SYSTEM_TABLES[table_name]
+ model = _model_by_pg_table().get(table.postgres_table_name)
+ assert model is not None, f"could not resolve a Django model for system.{table_name}"
+
+ registry = _object_grant_registry()
+ rows_are_the_object = registry.get(model) == table.access_scope and not table.resource_level_access_only
+ model_columns = {field.attname for field in model._meta.get_fields() if hasattr(field, "attname")}
+
+ if not rows_are_the_object:
+ # A child row's creator isn't the parent's, and metadata rows have no denied object at
+ # all, so a declaration here would exempt the wrong person.
+ self.assertIsNone(
+ table.access_control_creator_id_field,
+ f"system.{table_name} rows are not the access-controlled object; a creator exemption "
+ f"would apply to the wrong person — remove access_control_creator_id_field.",
+ )
+ return
+
+ if "created_by_id" not in model_columns:
+ self.assertIsNone(
+ table.access_control_creator_id_field,
+ f"system.{table_name}'s model has no creator; remove access_control_creator_id_field.",
+ )
+ return
+
+ self.assertEqual(
+ table.access_control_creator_id_field,
+ "created_by_id",
+ f"system.{table_name} is object-restrictable under '{table.access_scope}' and its rows have a "
+ f"creator, so REST keeps them visible to that creator. Set "
+ f'access_control_creator_id_field="created_by_id" so HogQL does too.',
+ )
+ self.assertIn(
+ "created_by_id",
+ table.fields,
+ f"system.{table_name} declares a creator exemption, but the guard can only reference an "
+ f"exposed field — add created_by_id to its fields.",
+ )
+
+
class TestSystemTableAccessScope(SimpleTestCase):
"""A system table's `access_scope` must be the concrete resource under which object-level
access control grants are stored — never a pure umbrella parent.
diff --git a/posthog/hogql/printer/access_control.py b/posthog/hogql/printer/access_control.py
index 8541df85ca0d..bcfaedea5b18 100644
--- a/posthog/hogql/printer/access_control.py
+++ b/posthog/hogql/printer/access_control.py
@@ -10,6 +10,7 @@ from posthog.hogql.database.postgres_table import PostgresTable
if TYPE_CHECKING:
from posthog.schema import AccessControlFilterWarning
+ from posthog.rbac.user_access_control import UserAccessControl
from posthog.scopes import APIScopeObject
@@ -41,11 +42,15 @@ def build_access_control_guard(
context: HogQLContext,
) -> Optional[ast.Expr]:
"""
- Build the WHERE clause AST node that filters out access-controlled resource IDs
- for the current user. Returns None if no filtering is needed.
-
- Deny set lives on UserAccessControl.blocked_resource_ids_by_scope — single source
- of truth, shared with the cache-key fingerprint in query_runner.py.
+ Build the WHERE clause AST node that restricts the table to the access-controlled objects the
+ current user may read. Returns None if no filtering is needed.
+
+ Mirrors `UserAccessControl.filter_queryset_by_access_level`, the REST equivalent, branch for
+ branch: with no resource-level access the rows are narrowed to the user's explicit grants,
+ otherwise the objects denied to them are removed, and either way the objects they created stay
+ visible. The id sets live on UserAccessControl (`allowlisted_resource_ids_by_scope` /
+ `blocked_resource_ids_by_scope`) — single source of truth, shared with the cache-key fingerprint
+ in query_runner.py.
"""
resource = table.access_scope
if not resource:
@@ -58,21 +63,71 @@ def build_access_control_guard(
if not context.database or not context.database.user_access_control:
return None
- blocked_ids = context.database.user_access_control.blocked_resource_ids_by_scope.get(resource, set())
- if not blocked_ids:
- return None
+ user_access_control = context.database.user_access_control
+
+ allowlisted_ids = user_access_control.allowlisted_resource_ids_by_scope.get(resource)
+ if allowlisted_ids:
+ # No resource-level access at all: only the explicitly granted objects are readable.
+ guard: ast.Expr = ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=_id_as_string(id_field, table_type),
+ right=ast.Constant(value=sorted(allowlisted_ids), is_sensitive=True),
+ type=ast.BooleanType(),
+ )
+ else:
+ blocked_ids = user_access_control.blocked_resource_ids_by_scope.get(resource, set())
+ if not blocked_ids:
+ return None
+ guard = ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=_id_as_string(id_field, table_type),
+ right=ast.Constant(value=sorted(blocked_ids), is_sensitive=True),
+ type=ast.BooleanType(),
+ )
+
+ creator_exemption = _build_creator_exemption(table, table_type, user_access_control)
+ if creator_exemption is not None:
+ guard = ast.Or(exprs=[guard, creator_exemption], type=ast.BooleanType())
# Surface that this query is subject to filtering so callers don't mistake a possibly-partial
# result for the full set. Note the guard applying doesn't mean rows were actually excluded —
# the user's blocked objects may not have matched the query anyway.
context.access_control_restricted_resources.add(resource)
- return ast.CompareOperation(
- op=ast.CompareOperationOp.NotIn,
- left=ast.Call(
- name="toString",
- args=[ast.Field(chain=[id_field], type=ast.FieldType(name=id_field, table_type=table_type))],
- ),
- right=ast.Constant(value=sorted(blocked_ids), is_sensitive=True),
- type=ast.BooleanType(),
+ return guard
+
+
+def _id_as_string(id_field: str, table_type: ast.TableOrSelectType) -> ast.Expr:
+ """Object id as a string, because access control stores `resource_id` as text."""
+ return ast.Call(
+ name="toString",
+ args=[ast.Field(chain=[id_field], type=ast.FieldType(name=id_field, table_type=table_type))],
+ )
+
+
+def _build_creator_exemption(
+ table: PostgresTable,
+ table_type: ast.TableOrSelectType,
+ user_access_control: "UserAccessControl",
+) -> Optional[ast.Expr]:
+ """`created_by_id = <current user>`, the REST creator exemption, or None when it can't apply.
+
+ A NULL creator must not exempt the row, hence the ifNull: without it the comparison is NULL and
+ takes the whole OR with it.
+ """
+ creator_field = table.access_control_creator_id
+ if creator_field is None or creator_field not in table.fields:
+ return None
+
+ return ast.Call(
+ name="ifNull",
+ args=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=[creator_field], type=ast.FieldType(name=creator_field, table_type=table_type)),
+ right=ast.Constant(value=user_access_control.user.pk),
+ type=ast.BooleanType(),
+ ),
+ ast.Constant(value=False),
+ ],
)
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index d45717ebb8f6..67d1ab63a80a 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -362,6 +362,112 @@ class TestAccessControlGuard(BaseTest):
assert f"notIn(toString(system__{table}.account_id), %({deny_keys[0]})s)" in sql, table
+class TestRestParityForObjectGrants(BaseTest):
+ """HogQL object-level filtering must resolve the same rows REST's
+ `filter_queryset_by_access_level` does: resource-level "none" plus an object grant serves the
+ granted objects (rather than denying the table), and a creator keeps their own objects."""
+
+ def setUp(self):
+ super().setUp()
+ from posthog.constants import AvailableFeature
+
+ 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()
+ self.membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ self.membership.level = OrganizationMembership.Level.MEMBER
+ self.membership.save()
+
+ def _ac(self, **kwargs):
+ from ee.models import AccessControl
+
+ return AccessControl.objects.create(team=self.team, **kwargs)
+
+ def _compile(self, query: str) -> tuple[str, HogQLContext]:
+ from posthog.hogql.parser import parse_select
+
+ context = HogQLContext(team_id=self.team.pk, team=self.team, user=self.user, enable_select_queries=True)
+ prepared = prepare_ast_for_printing(parse_select(query), context=context, dialect="clickhouse")
+ assert prepared is not None
+ return print_prepared_ast(prepared, context=context, dialect="clickhouse"), context
+
+ def _id_list_placeholders(self, context: HogQLContext) -> dict[str, list]:
+ return {k: v for k, v in context.values.items() if k.endswith("_sensitive") and isinstance(v, list)}
+
+ def test_resource_denial_with_an_object_grant_narrows_instead_of_denying(self):
+ # REST serves the dashboards route on an object grant alone and returns just the granted
+ # dashboard. Removing system.dashboards outright made the granted dashboard unreachable.
+ self._ac(resource="dashboard", access_level="none")
+ self._ac(
+ resource="dashboard",
+ resource_id="dash-granted",
+ access_level="viewer",
+ organization_member=self.membership,
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+ assert "system.dashboards" not in database._denied_tables
+
+ sql, context = self._compile("SELECT id FROM system.dashboards")
+ placeholders = self._id_list_placeholders(context)
+ assert list(placeholders.values()) == [["dash-granted"]]
+ allow_key = next(iter(placeholders))
+ assert f"in(toString(system__dashboards.id), %({allow_key})s)" in sql
+
+ def test_object_grant_reaches_child_rows_of_the_granted_object(self):
+ # The narrowing keys off the parent id on child tables, so a grant on one dashboard exposes
+ # that dashboard's tiles and nothing else.
+ self._ac(resource="dashboard", access_level="none")
+ self._ac(
+ resource="dashboard",
+ resource_id="dash-granted",
+ access_level="viewer",
+ organization_member=self.membership,
+ )
+
+ sql, context = self._compile("SELECT id FROM system.dashboard_tiles")
+ allow_key = next(iter(self._id_list_placeholders(context)))
+ assert f"in(toString(system__dashboard_tiles.dashboard_id), %({allow_key})s)" in sql
+
+ def test_resource_denial_still_denies_a_table_the_grant_cannot_narrow(self):
+ # message_categories is team-level data under the "hog_flow" scope, so a per-flow grant says
+ # nothing about which rows are readable. It has to keep failing closed.
+ self._ac(resource="hog_flow", access_level="none")
+ self._ac(
+ resource="hog_flow",
+ resource_id="flow-granted",
+ access_level="viewer",
+ organization_member=self.membership,
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+ assert "system.message_categories" in database._denied_tables
+
+ @parameterized.expand(
+ [
+ ("resource_denied", "none", "in(toString(system__dashboards.id)"),
+ ("resource_granted", "editor", "notIn(toString(system__dashboards.id)"),
+ ]
+ )
+ def test_creator_keeps_their_own_denied_object(self, _name, resource_level, expected_id_guard):
+ # REST exempts the creator from object-level denial on both branches of the filter, so a
+ # dashboard's creator must not lose it to HogQL either.
+ self._ac(resource="dashboard", access_level=resource_level)
+ self._ac(
+ resource="dashboard",
+ resource_id="dash-mine",
+ access_level="none" if resource_level == "editor" else "viewer",
+ organization_member=self.membership,
+ )
+
+ sql, _context = self._compile("SELECT id FROM system.dashboards")
+ assert expected_id_guard in sql
+ assert f"ifNull(equals(system__dashboards.created_by_id, {self.user.pk}), 0)" in sql
+ assert sql.count("or(") == 1
+
+
class TestDeniedTableError(BaseTest):
"""Test that denied tables show a helpful error message."""
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 3ef00d49aeab..e12602734a73 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -2694,10 +2694,22 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):
if queried_resources == set():
return payload
- if restricted_objects := self._get_object_access_restrictions(queried_resources):
+ restricted_objects = self._get_object_access_restrictions(queried_resources)
+ allowlisted_objects = self._get_object_access_allowlist(queried_resources)
+ restricted_resources = self._get_resource_access_restrictions(queried_resources)
+ if restricted_objects:
payload["restricted_objects"] = restricted_objects
- if restricted_resources := self._get_resource_access_restrictions(queried_resources):
+ if allowlisted_objects:
+ payload["allowlisted_objects"] = allowlisted_objects
+ if restricted_resources:
payload["restricted_resources"] = restricted_resources
+ if (restricted_objects or allowlisted_objects or restricted_resources) and (
+ user_access_control := self.user_access_control
+ ):
+ # Access-control filtering exempts objects the user created (see build_access_control_guard),
+ # including when the resource is denied without any object-level rules. Partition by principal
+ # whenever access control narrows the query.
+ payload["restricted_for_user"] = user_access_control.user.pk
return payload
@@ -2714,6 +2726,20 @@ class AnalyticsQueryRunner(QueryRunner, Generic[AR]):
return None
return {resource: sorted(ids) for resource, ids in sorted(blocked.items())}
+ def _get_object_access_allowlist(self, queried_resources: Optional[set[str]]) -> dict[str, list[str]] | None:
+ """Per-resource object IDs that are the only ones readable, scoped to the resources this query
+ reads. Distinct from the deny set: two users can be denied nothing yet be narrowed to
+ different grants, which would otherwise collide on one cache entry."""
+ user_access_control = self.user_access_control
+ if user_access_control is None:
+ return None
+ allowlisted = user_access_control.allowlisted_resource_ids_by_scope
+ if queried_resources is not None:
+ allowlisted = {resource: ids for resource, ids in allowlisted.items() if resource in queried_resources}
+ if not allowlisted:
+ return None
+ return {resource: sorted(ids) for resource, ids in sorted(allowlisted.items())}
+
def _get_resource_access_restrictions(self, queried_resources: Optional[set[str]]) -> list[str] | None:
"""Resources the user has no resource-level access to, scoped to the resources this query reads."""
# user is typed Optional[User] but runtime also passes SyntheticUser (project secret keys)
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 9e22dffdfd6b..c4dc717f99fc 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -1605,6 +1605,76 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):
payload = HogQLQueryRunner(query=query, team=self.team, user=self.user).get_cache_payload()
assert "restricted_objects" not in payload # notebook object deny doesn't touch a surveys query
+ def test_object_grants_under_a_denied_resource_partition_cache(self):
+ # Both users are denied notebooks at the resource level and see only what they were granted,
+ # so neither has a deny set to partition on - without the allowlist in the fingerprint they
+ # would share one entry and be served each other's notebook.
+ from products.notebooks.backend.models import Notebook
+
+ other_user = self._create_user("[email protected]")
+ other_membership = other_user.organization_memberships.get(organization=self.organization)
+ mine = Notebook.objects.create(team=self.team, created_by=self.user, title="Mine")
+ theirs = Notebook.objects.create(team=self.team, created_by=other_user, title="Theirs")
+
+ self._ac(resource="notebook", access_level="none")
+ self._ac(
+ resource="notebook",
+ resource_id=str(mine.id),
+ access_level="viewer",
+ organization_member=self.organization_membership,
+ )
+ self._ac(
+ resource="notebook",
+ resource_id=str(theirs.id),
+ access_level="viewer",
+ organization_member=other_membership,
+ )
+
+ query = {"kind": "HogQLQuery", "query": "select * from system.notebooks"}
+ my_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)
+ their_runner = HogQLQueryRunner(query=query, team=self.team, user=other_user)
+
+ assert my_runner.get_cache_payload()["allowlisted_objects"] == {"notebook": [str(mine.id)]}
+ assert their_runner.get_cache_payload()["allowlisted_objects"] == {"notebook": [str(theirs.id)]}
+ assert my_runner.get_cache_key() != their_runner.get_cache_key()
+
+ def test_creator_exemption_partitions_cache_between_identically_denied_users(self):
+ # The same notebook is denied to both users, so their deny sets match - but the guard keeps it
+ # visible to whoever created it, so they must not share a cache entry.
+ from products.notebooks.backend.models import Notebook
+
+ other_user = self._create_user("[email protected]")
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, title="Mine")
+ self._ac(resource="notebook", access_level="editor")
+ self._ac(resource="notebook", resource_id=str(notebook.id), access_level="none")
+
+ query = {"kind": "HogQLQuery", "query": "select * from system.notebooks"}
+ creator_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)
+ other_runner = HogQLQueryRunner(query=query, team=self.team, user=other_user)
+
+ assert creator_runner.get_cache_payload()["restricted_objects"] == {"notebook": [str(notebook.id)]}
+ assert other_runner.get_cache_payload()["restricted_objects"] == {"notebook": [str(notebook.id)]}
+ assert creator_runner.get_cache_key() != other_runner.get_cache_key()
+
+ def test_creator_exemption_partitions_cache_without_object_level_rules(self):
+ # A resource deny still leaves a creator's own objects visible. With no object rules, both users
+ # otherwise have the same fingerprint and could be served each other's cached result.
+ from products.notebooks.backend.models import Notebook
+
+ other_user = self._create_user("[email protected]")
+ Notebook.objects.create(team=self.team, created_by=self.user, title="Mine")
+ self._ac(resource="notebook", access_level="none")
+
+ query = {"kind": "HogQLQuery", "query": "select * from system.notebooks"}
+ creator_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)
+ other_runner = HogQLQueryRunner(query=query, team=self.team, user=other_user)
+
+ assert "restricted_objects" not in creator_runner.get_cache_payload()
+ assert "restricted_objects" not in other_runner.get_cache_payload()
+ assert creator_runner.get_cache_payload()["restricted_resources"] == ["notebook"]
+ assert other_runner.get_cache_payload()["restricted_resources"] == ["notebook"]
+ assert creator_runner.get_cache_key() != other_runner.get_cache_key()
+
def test_run_recomputes_fingerprint_when_user_changes(self):
# run(user=...) swaps the user after construction; the snapshot must rebuild for the new user.
other_user = self._create_user("[email protected]")
diff --git a/posthog/rbac/test/test_user_access_control_pbt.py b/posthog/rbac/test/test_user_access_control_pbt.py
index 750792e86ba8..ce60407017b8 100644
--- a/posthog/rbac/test/test_user_access_control_pbt.py
+++ b/posthog/rbac/test/test_user_access_control_pbt.py
@@ -743,6 +743,51 @@ class TestUserAccessControlProperties(BaseAccessControlPropertyTest):
blocked, _allowed = oracle_blocked_and_allowed_object_ids(object_specs_by_id)
assert result == ({resource: blocked} if blocked else {})
+ @given(scenario=queryset_scenario())
+ @settings(max_examples=50, deadline=None, suppress_health_check=SUPPRESSED_HEALTH_CHECKS)
+ def test_hogql_guard_inputs_resolve_the_same_rows_as_the_queryset_filter(self, scenario):
+ # HogQL can't run filter_queryset_by_access_level, so it rebuilds the same decision in SQL from
+ # allowlisted_resource_ids_by_scope, blocked_resource_ids_by_scope and the row's creator (see
+ # build_access_control_guard). Evaluate that decision here and hold it to the REST oracle: a
+ # divergence means HogQL and the API disagree about who can see an object. Members only - HogQL
+ # exempts org admins from object-level filtering outright, while the queryset filter does so
+ # only when its caller passes include_all_if_admin.
+ resource, model_cls, objects, resource_specs = scenario
+ self._set_membership_level(OrganizationMembership.Level.MEMBER)
+
+ object_specs_by_id: dict[str, list[RowSpec]] = {}
+ creator_ids: set[str] = set()
+ for specs, owned in objects:
+ creator = self.user if owned else self.other_user
+ obj = build_instance(model_cls, self.team, creator)
+ self._materialize(specs, resource, obj)
+ object_specs_by_id[str(obj.pk)] = specs
+ if owned:
+ creator_ids.add(str(obj.pk))
+ self._materialize(resource_specs, resource, obj=None)
+
+ uac = self._fresh_uac()
+ allowlisted = uac.allowlisted_resource_ids_by_scope.get(resource)
+ blocked = uac.blocked_resource_ids_by_scope.get(resource, set())
+ model_has_creator = model_has_created_by(model_cls)
+
+ def guard_admits(object_id: str) -> bool:
+ if model_has_creator and object_id in creator_ids:
+ return True
+ if allowlisted:
+ return object_id in allowlisted
+ return object_id not in blocked
+
+ visible = {object_id for object_id in object_specs_by_id if guard_admits(object_id)}
+ assert visible == oracle_visible_object_ids(
+ resource,
+ resource_specs,
+ object_specs_by_id,
+ creator_ids,
+ model_has_creator=model_has_creator,
+ is_org_admin=False,
+ )
+
@given(
data=object_resource_and_rows(),
team_rows=project_rows(),
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 2aaebaa3dab3..fc49d9bfe0a4 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -533,6 +533,7 @@ class UserAccessControl:
# hasattr on an un-computed cached_property would re-populate the value we're clearing
self.__dict__.pop("_cached_access_controls", None)
self.__dict__.pop("blocked_resource_ids_by_scope", None)
+ self.__dict__.pop("allowlisted_resource_ids_by_scope", None)
self.__dict__.pop("blocked_resources", None)
self.__dict__.pop("_organization_membership", None)
self.__dict__.pop("_user_role_ids", None)
@@ -1279,6 +1280,38 @@ class UserAccessControl:
result[resource] = blocked
return result
+ @cached_property
+ def allowlisted_resource_ids_by_scope(self) -> dict[APIScopeObject, set[str]]:
+ """Per-resource set of object IDs that are the *only* ones the user may read, for resources
+ where they hold object-level grants but no resource-level access at all.
+
+ This is the allowlist branch of `filter_queryset_by_access_level`: with "none" at the
+ resource level, REST serves the route and narrows rows to the explicitly granted objects
+ instead of merely removing denied ones. HogQL consumers must narrow the same way — a
+ resource absent from this mapping falls back to removing `blocked_resource_ids_by_scope`.
+
+ Empty for org admins and when there is no team / EE / entitlement, matching
+ `blocked_resource_ids_by_scope`.
+ """
+ if not EE_AVAILABLE or not self._team or self.is_organization_admin:
+ return {}
+
+ if not self.access_controls_supported:
+ # Without the entitlement, stale rules in the DB must be ignored, not enforced
+ return {}
+
+ object_rows_by_resource: dict[APIScopeObject, list[_AccessControl]] = defaultdict(list)
+ for ac in self._cached_access_controls:
+ if ac.resource_id is not None:
+ object_rows_by_resource[cast(APIScopeObject, ac.resource)].append(ac)
+
+ result: dict[APIScopeObject, set[str]] = {}
+ for resource, acs in object_rows_by_resource.items():
+ _blocked, allowed = self._blocked_and_allowed_object_ids(acs)
+ if allowed and not self.has_resource_access(resource):
+ result[resource] = allowed
+ return result
+
def has_resource_access(self, resource: APIScopeObject) -> bool:
"""Whether the user has any resource-level access (level is set and not "none")"""
level = self.access_level_for_resource(resource)
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index d3a87388c557..425b5646dc6a 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -563,6 +563,8 @@ account_relationship_definitions: PostgresTable = PostgresTable(
postgres_table_name="customer_analytics_accountrelationshipdefinition",
# Sub-resource of accounts; gated at the account resource level (see customer_analytics backend CLAUDE.md).
access_scope="account",
+ # Team-level definitions shared by every account, so a per-account grant never keys these rows.
+ resource_level_access_only=True,
description="Customer analytics account relationship definitions: team-defined relationship types between PostHog users and accounts (CSM, Account executive, ...), one row per definition. Per-account assignments live in system.account_relationships and via the system.accounts.relationships lazy join.",
fields={
"id": UUIDDatabaseField(name="id", description="Relationship definition UUID."),
@@ -629,6 +631,7 @@ accounts: PostgresTable = PostgresTable(
# `account` here (where the per-object grants are stored) instead of the
# `customer_analytics` umbrella. Resource-level gating still works via RESOURCE_INHERITANCE_MAP.
access_scope="account",
+ access_control_creator_id_field="created_by_id",
description="Customer analytics accounts (companies/organizations being tracked); one row per account, with CRM identifiers extracted from properties.",
fields={
"id": UUIDDatabaseField(name="id", description="Account UUID."),
@@ -682,6 +685,8 @@ custom_property_definitions: PostgresTable = PostgresTable(
postgres_table_name="customer_analytics_custompropertydefinition",
# Sub-resource of accounts; gated at the account resource level (see customer_analytics backend CLAUDE.md).
access_scope="account",
+ # Team-level definitions shared by every account, so a per-account grant never keys these rows.
+ resource_level_access_only=True,
description="Customer analytics custom property definitions: team-scoped attribute shapes (the property's name and type), one row per definition. Per-account values are exposed via the system.accounts.custom_properties lazy join.",
fields={
"id": UUIDDatabaseField(name="id", description="Custom property definition UUID."),