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(rbac): correctly resolve the inherited level for object default (#83468)

Alex Lidercf4335651cc1
diff --git a/ee/api/rbac/access_control.py b/ee/api/rbac/access_control.py
index 870c8762e956..366434e2afb8 100644
--- a/ee/api/rbac/access_control.py
+++ b/ee/api/rbac/access_control.py
@@ -1,6 +1,9 @@
from collections.abc import Callable
+from dataclasses import asdict
from typing import TYPE_CHECKING, Any, cast
+from django.db.models import Model
+
from rest_framework import exceptions, serializers, status
from rest_framework.decorators import action
from rest_framework.request import Request
@@ -11,14 +14,15 @@ from posthog.api.documentation import extend_schema
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
+from posthog.rbac.subject_access_control import SubjectAccessControl
from posthog.rbac.user_access_control import (
ACCESS_CONTROL_LEVELS_RESOURCE,
ACCESS_CONTROL_MAX_OBJECTS_PER_RESOURCE,
- RESOURCE_INHERITANCE_MAP,
- RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS,
AccessSource,
+ ResolvedAccess,
UserAccessControl,
default_access_level,
+ fallback_parent_object,
highest_access_level,
minimum_access_level,
ordered_access_levels,
@@ -33,6 +37,26 @@ else:
_GenericViewSet = object
+def _inherited_source_display_name(obj: Model, access: ResolvedAccess) -> str | None:
+ """A human name for the parent object an inherited level comes through, so the UI can say
+ which one. Only object-scoped sources have one, and the parent is always the object's own
+ fallback relation (that's where the walk got its id), so it is read off the object — cached
+ by Django, free when already loaded — never refetched by id. The name field comes from the
+ same registry the settings UI names objects with, so a new fallback parent needs no code here."""
+ from ee.api.rbac.access_control_settings import (
+ _display_model, # noqa: PLC0415 — access_control_settings imports this module; deferring breaks the cycle
+ )
+
+ if access.source != "parent_object":
+ return None
+ parent = fallback_parent_object(obj, access.source_resource)
+ display = _display_model(access.source_resource)
+ if parent is None or display is None:
+ return None
+ name = getattr(parent, display.name_field, None)
+ return str(name) if name else None
+
+
class OrganizationMemberField(serializers.PrimaryKeyRelatedField):
def __init__(self, **kwargs):
kwargs.setdefault(
@@ -48,6 +72,46 @@ class OrganizationMemberField(serializers.PrimaryKeyRelatedField):
super().__init__(**kwargs)
+class ResolvedAccessSerializer(serializers.Serializer):
+ """A resolved access level with the rule that supplied it — the wire form of `ResolvedAccess`."""
+
+ access_level = serializers.CharField(help_text="The access level that applies.")
+ source = serializers.ChoiceField( # type: ignore[assignment] # field named `source` shadows DRF Field.source
+ choices=[
+ "object",
+ "parent_object",
+ "resource",
+ "parent_resource",
+ "system_default",
+ "org_admin",
+ "creator",
+ "org_membership",
+ ],
+ help_text="How the level was derived: a rule on the object, its parent object, the resource, the parent "
+ "resource, the built-in default, or one of the bypasses (org admin, creator, organization membership).",
+ )
+ source_subject = serializers.ChoiceField(
+ choices=["member", "role", "default"],
+ allow_null=True,
+ help_text="Whose rule decided: a member's own, a role's, or the default for everyone. Null when no rule did.",
+ )
+ source_resource = serializers.CharField(help_text="The resource the deciding rule belongs to.")
+ source_resource_id = serializers.CharField(
+ allow_null=True,
+ help_text="The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).",
+ )
+
+
+class InheritedAccessSerializer(ResolvedAccessSerializer):
+ """The level an object falls back to without its own override, plus a display name for the parent it
+ comes through when there is one."""
+
+ source_display_name = serializers.CharField(
+ allow_null=True,
+ help_text="A human name for the parent object the level comes through (e.g. a table's source type).",
+ )
+
+
class UserAccessInfoSerializer(serializers.Serializer):
"""Serializer for user access information"""
@@ -340,32 +404,23 @@ class AccessControlViewSetMixin(_GenericViewSet):
if not is_resource_level:
# The level this object falls back to when it carries no default of its own, so the UI
- # can spell out what removing the override means. Follows RESOURCE_INHERITANCE_MAP
- # because that's the resource the runtime check consults — a warehouse view is gated by
- # the warehouse_objects rules, not by its own.
+ # can spell out what removing the override means. Resolved by the access walker itself
+ # (the object's own rows masked out, everyone perspective), so the shown level cannot
+ # disagree with how access is actually enforced — a re-derivation here would miss the
+ # fallback-parent tier (a table gated by its source).
#
# None for a project is load-bearing: it is what stops the UI offering "No override" on
# a project's own default, which has nothing above it to fall back to. "No override"
# belongs to object defaults only — project-level access is configured in its own
# panel, which has no inherited tier to fall back to.
- inherited_resource = (
- None
- if resource in RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS
- else RESOURCE_INHERITANCE_MAP.get(resource, resource)
+ inherited = SubjectAccessControl(user_access_control.user, team).inherited_access_for_object(obj)
+ payload["inherited_access"] = (
+ InheritedAccessSerializer(
+ {**asdict(inherited), "source_display_name": _inherited_source_display_name(obj, inherited)}
+ ).data
+ if inherited
+ else None
)
- payload["inherited_resource"] = inherited_resource
- payload["inherited_access_level"] = None
- if inherited_resource:
- everyone_rule = AccessControl.objects.filter(
- team=team,
- resource=inherited_resource,
- resource_id=None,
- organization_member=None,
- role=None,
- ).first()
- payload["inherited_access_level"] = (
- everyone_rule.access_level if everyone_rule else default_access_level(inherited_resource)
- )
return Response(payload)
diff --git a/ee/api/rbac/test/test_access_control.py b/ee/api/rbac/test/test_access_control.py
index 005859187e3f..907d2ead6bcb 100644
--- a/ee/api/rbac/test/test_access_control.py
+++ b/ee/api/rbac/test/test_access_control.py
@@ -24,7 +24,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
-from products.warehouse_sources.backend.models import DataWarehouseTable
+from products.warehouse_sources.backend.models import DataWarehouseTable, ExternalDataSource
from ee.api.rbac.access_control_settings import _display_model, resources_with_object_access_controls
from ee.api.test.base import APILicensedTest
@@ -297,9 +297,15 @@ class TestAccessControlResourceLevelAPI(BaseAccessControlTest):
"user_can_edit_access_levels": True,
"minimum_access_level": "none",
"maximum_access_level": "manager",
- "inherited_resource": "notebook",
- # No project-wide rule for notebooks, so the resource's built-in default applies
- "inherited_access_level": "editor",
+ # No rule anywhere above this notebook, so the resource's built-in default applies
+ "inherited_access": {
+ "access_level": "editor",
+ "source": "system_default",
+ "source_subject": None,
+ "source_resource": "notebook",
+ "source_resource_id": None,
+ "source_display_name": None,
+ },
}
def test_get_access_controls_resolves_the_project_wide_level_it_falls_back_to(self):
@@ -317,8 +323,13 @@ class TestAccessControlResourceLevelAPI(BaseAccessControlTest):
res = self._get_access_controls()
assert res.status_code == status.HTTP_200_OK, res.json()
- assert res.json()["inherited_resource"] == "notebook"
- assert res.json()["inherited_access_level"] == "viewer"
+ inherited = res.json()["inherited_access"]
+ assert inherited["access_level"] == "viewer"
+ assert (inherited["source"], inherited["source_subject"], inherited["source_resource"]) == (
+ "resource",
+ "default",
+ "notebook",
+ )
def test_inherited_resource_follows_the_resource_it_actually_inherits_from(self):
self._org_membership(OrganizationMembership.Level.ADMIN)
@@ -329,8 +340,39 @@ class TestAccessControlResourceLevelAPI(BaseAccessControlTest):
res = self.client.get(f"/api/projects/@current/session_recording_playlists/{playlist.short_id}/access_controls")
assert res.status_code == status.HTTP_200_OK, res.json()
# Playlists are gated by the session_recording rules, so that's what "no override" falls back to
- assert res.json()["inherited_resource"] == "session_recording"
- assert res.json()["inherited_access_level"] == "viewer"
+ inherited = res.json()["inherited_access"]
+ assert inherited["access_level"] == "viewer"
+ assert (inherited["source"], inherited["source_resource"]) == ("resource", "session_recording")
+
+ def test_inherited_access_resolves_through_a_table_source(self):
+ # The old inline re-derivation ignored the fallback-parent tier, so a table under a
+ # restricted source displayed the tables-wide level instead of the source's
+ self._org_membership(OrganizationMembership.Level.ADMIN)
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src",
+ connection_id="conn",
+ destination_id="dest",
+ source_type="Stripe",
+ prefix="test",
+ )
+ table = DataWarehouseTable.objects.create(
+ team=self.team, name="customers", format="Parquet", external_data_source=source, columns={}
+ )
+ AccessControl.objects.create(
+ team=self.team, resource="external_data_source", resource_id=str(source.id), access_level="viewer"
+ )
+
+ res = self.client.get(f"/api/projects/@current/warehouse_tables/{table.id}/access_controls")
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ assert res.json()["inherited_access"] == {
+ "access_level": "viewer",
+ "source": "parent_object",
+ "source_subject": "default",
+ "source_resource": "external_data_source",
+ "source_resource_id": str(source.id),
+ "source_display_name": "Stripe",
+ }
def test_project_reports_no_inherited_level(self):
self._org_membership(OrganizationMembership.Level.ADMIN)
@@ -338,8 +380,7 @@ class TestAccessControlResourceLevelAPI(BaseAccessControlTest):
assert res.status_code == status.HTTP_200_OK, res.json()
# Nothing sits above a project, so it must report no inherited level — that absence is what
# keeps "No override" an object-default affordance rather than a project-level one
- assert res.json()["inherited_resource"] is None
- assert res.json()["inherited_access_level"] is None
+ assert res.json()["inherited_access"] is None
def test_change_rejected_if_not_org_admin(self):
self._org_membership(OrganizationMembership.Level.MEMBER)
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index ab6293d6eac6..1d40906b23e6 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -1298,23 +1298,27 @@ export const accessControlLogic = kea<accessControlLogicType>([
},
],
- // What the object falls back to with no default of its own: the project's rule for
- // everyone, or the resource's built-in level when the project sets no rule at all.
- // A null inherited_resource means nothing sits above this object, so there is no
- // "No override" to offer — a project's own default is the case that hits.
+ // What the object falls back to with no default of its own, resolved by the backend's
+ // access walker so it cannot disagree with enforcement. A null inherited_access means
+ // nothing sits above this object, so there is no "No override" to offer — a project's
+ // own default is the case that hits.
inheritedAccess: [
(s) => [s.accessControls],
(accessControls: AccessControlResponseType | null): InheritedAccess | null => {
- const inheritedResource = accessControls?.inherited_resource
- const inheritedLevel = accessControls?.inherited_access_level
- if (!inheritedResource || !inheritedLevel) {
+ const inherited = accessControls?.inherited_access
+ if (!inherited) {
return null
}
+ // A configured rule and the built-in fallback are both "the default for <x>", so
+ // one phrasing covers them without claiming someone set it. A level that comes
+ // through the object's parent (a table's source) names that parent.
+ const reason =
+ inherited.source === 'parent_object' && inherited.source_display_name
+ ? `Based on the default for the ${inherited.source_display_name} source`
+ : `Based on the default for ${pluralizeResource(inherited.source_resource)}`
return {
- label: humanizeAccessControlLevel(inheritedLevel),
- // A configured project rule and the built-in fallback are both "the default
- // for <resource>", so one reason covers them without claiming someone set it
- reason: `Based on the default for ${pluralizeResource(inheritedResource)}`,
+ label: humanizeAccessControlLevel(inherited.access_level),
+ reason,
}
},
],
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index afe1502956c3..292ec096719e 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5928,6 +5928,29 @@ export type AccessControlUpdateType = Pick<AccessControlType, 'access_level' | '
resource?: AccessControlType['resource']
}
+/** Which rule supplied an inherited access level — mirrors `ResolvedAccess.source` on the backend. */
+export type InheritedAccessSource =
+ | 'object'
+ | 'parent_object'
+ | 'resource'
+ | 'parent_resource'
+ | 'system_default'
+ | 'org_admin'
+ | 'creator'
+ | 'org_membership'
+
+/** What an object falls back to while it carries no override of its own, with the rule that
+ * decided it, resolved by the same walker that enforces access. */
+export type InheritedAccessType = {
+ access_level: AccessControlLevel
+ source: InheritedAccessSource
+ source_subject: 'member' | 'role' | 'default' | null
+ source_resource: APIScopeObject
+ source_resource_id: string | null
+ /** Human name of the parent object the level comes through (e.g. a table's source type). */
+ source_display_name: string | null
+}
+
export type AccessControlResponseType = {
access_controls: AccessControlType[]
available_access_levels: AccessControlLevel[]
@@ -5935,11 +5958,9 @@ export type AccessControlResponseType = {
default_access_level: AccessControlLevel
minimum_access_level?: AccessControlLevel
user_can_edit_access_levels: boolean
- /** Resource whose project-wide rules apply while the object carries no override of its own. */
- inherited_resource?: APIScopeObject | null
- /** The level that applies while the object carries no override: the project-wide rule for
- * `inherited_resource`, or its built-in default when no rule is set. */
- inherited_access_level?: AccessControlLevel | null
+ /** The level and rule that apply while the object carries no override of its own; null when
+ * nothing sits above the object (e.g. a project). */
+ inherited_access?: InheritedAccessType | null
}
export type InheritedAccessLevelReason = 'project_default' | 'role_override' | 'organization_admin'
diff --git a/posthog/rbac/subject_access_control.py b/posthog/rbac/subject_access_control.py
new file mode 100644
index 000000000000..6d4f2cf1fd6b
--- /dev/null
+++ b/posthog/rbac/subject_access_control.py
@@ -0,0 +1,107 @@
+from functools import cached_property
+from typing import Any, Optional, cast
+
+from django.db.models import Model, Q
+
+from posthog.models import OrganizationMembership, Team, User
+from posthog.rbac.user_access_control import (
+ RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS,
+ ResolvedAccess,
+ UserAccessControl,
+ _AccessControl,
+ model_to_resource,
+)
+
+
+class SubjectAccessControl(UserAccessControl):
+ """Resolves access for a subject rather than for the requesting user.
+
+ The subject decides which rules count:
+ - no subject: only the default rules (scoped to no member and no role) — what applies to everyone
+ - member=...: the default rules, the member's own rules, and the rules of the member's roles
+ - role_id=...: the default rules and that role's rules
+
+ A member subject keeps the org-admin bypass when their membership level grants it; the
+ other subjects never have it.
+
+ For attribution and display (what does or would this subject have) — never for enforcing
+ the requesting user's access, which is UserAccessControl's job. `user`/`team` are still the
+ requesting user's context; the subject only changes whose rules resolve.
+ """
+
+ def __init__(
+ self,
+ user: User,
+ team: Optional[Team] = None,
+ organization_id: Optional[str] = None,
+ *,
+ member: Optional[OrganizationMembership] = None,
+ role_id: Optional[str] = None,
+ ):
+ super().__init__(user, team, organization_id)
+ self._subject_member = member
+ self._subject_role_id = role_id
+
+ def inherited_access_for_object(self, obj: Model) -> Optional[ResolvedAccess]:
+ """The access the subject would have if their override on this object were removed — the
+ inherited level the UI shows next to "No override".
+
+ Runs the subject's precheck (a member keeps their creator and org-admin bypasses even
+ without the override) and then the same object walk, over the subject's rules with the
+ subject's own rows on this object left out — so the answer cannot disagree with how
+ access would actually be enforced.
+
+ None when nothing sits above the object (the resources without resource-level
+ controls, e.g. a project) — that None is load-bearing for the UI, which must not
+ offer "No override" there.
+ """
+ resource = model_to_resource(obj)
+ if not resource or resource in RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS:
+ return None
+
+ member = self._subject_member
+ is_creator = member is not None and getattr(obj, "created_by", None) == member.user
+ resolved, access = self._object_access_level_precheck(resource, is_creator)
+ if resolved:
+ return access
+
+ rows = [
+ ac
+ for ac in self._get_access_controls(self._access_controls_filters_for_object(resource, str(obj.id))) # type: ignore
+ if not self._is_subject_row(ac)
+ ]
+ return self._object_access_level_from_rows(
+ resource, rows, fallback_parent_id=self._fallback_parent_id(obj, resource)
+ )
+
+ def _is_subject_row(self, access_control: _AccessControl) -> bool:
+ """Whether this row is the subject's own — the kind of rule "No override" would remove."""
+ if self._subject_member is not None:
+ return access_control.organization_member_id == self._subject_member.id
+ if self._subject_role_id is not None:
+ return str(access_control.role_id) == str(self._subject_role_id)
+ return access_control.organization_member_id is None and access_control.role_id is None
+
+ @cached_property
+ def _user_role_ids(self):
+ if self._subject_member is not None:
+ if not self.rbac_supported:
+ return []
+ return list(
+ cast(Any, self._subject_member.user)
+ .role_memberships.filter(role__organization_id=self._organization_id)
+ .values_list("role_id", flat=True)
+ )
+ return [self._subject_role_id] if self._subject_role_id else []
+
+ def _filter_options(self, filters: dict[str, Any]) -> Q:
+ q = Q(**filters, organization_member=None, role=None)
+ if self._subject_member is not None:
+ q |= Q(**filters, organization_member=self._subject_member, role=None)
+ if self._user_role_ids:
+ q |= Q(**filters, organization_member=None, role__in=self._user_role_ids)
+ return q
+
+ @property
+ def is_organization_admin(self) -> bool:
+ return bool(self._subject_member and self._subject_member.level >= OrganizationMembership.Level.ADMIN)
diff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.py
index 16694699fef1..df6b71d9cdf4 100644
--- a/posthog/rbac/test/test_user_access_control.py
+++ b/posthog/rbac/test/test_user_access_control.py
@@ -10,6 +10,7 @@ from posthog.models.file_system.file_system import FileSystem
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.rbac.subject_access_control import SubjectAccessControl
from posthog.rbac.user_access_control import (
RESOURCE_INHERITANCE_MAP,
AccessSource,
@@ -2242,6 +2243,56 @@ class TestUserAccessControlFallbackParent(BaseUserAccessControlTest):
expected_ids = {None: None, "source": str(self.source.id), "table": str(self.sourced_table.id)}
assert access.source_resource_id == expected_ids[expected_id_of]
+ def test_inherited_access_for_a_subject(self):
+ # The inherited level is "what would this subject have without their override": the walk
+ # runs over the subject's rules with their own row on the object left out, and a member
+ # keeps the bypasses enforcement would still give them
+ role = Role.objects.create(name="Data", organization=self.organization)
+ table = self.sourced_table
+ self._create_access_control(resource="warehouse_table", resource_id=str(table.id), access_level="viewer")
+ self._create_access_control(
+ resource="warehouse_table",
+ resource_id=str(table.id),
+ access_level="none",
+ organization_member=self.membership,
+ )
+ self._create_access_control(
+ resource="warehouse_table", resource_id=str(table.id), access_level="none", role=role
+ )
+ self._clear_uac_caches()
+
+ default_access = SubjectAccessControl(self.user, self.team).inherited_access_for_object(table)
+ assert default_access is not None
+ assert (default_access.access_level, default_access.source) == ("editor", "system_default")
+
+ member_access = SubjectAccessControl(self.user, self.team, member=self.membership).inherited_access_for_object(
+ table
+ )
+ assert member_access is not None
+ assert (member_access.access_level, member_access.source, member_access.source_subject) == (
+ "viewer",
+ "object",
+ "default",
+ )
+
+ role_access = SubjectAccessControl(self.user, self.team, role_id=str(role.id)).inherited_access_for_object(
+ table
+ )
+ assert role_access is not None
+ assert (role_access.access_level, role_access.source, role_access.source_subject) == (
+ "viewer",
+ "object",
+ "default",
+ )
+
+ self.membership.level = OrganizationMembership.Level.ADMIN
+ self.membership.save()
+ admin_access = SubjectAccessControl(self.user, self.team, member=self.membership).inherited_access_for_object(
+ table
+ )
+ assert admin_access is not None
+ assert (admin_access.access_level, admin_access.source) == ("manager", "org_admin")
+
def test_precheck_outcomes_report_their_source(self):
resolved, access = self.user_access_control._object_access_level_precheck("warehouse_table", is_creator=True)
assert resolved and access is not None
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index e1c20b527dfa..42fcd13da783 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -528,8 +528,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
@cache
-def _fallback_parent_field(model: type[Model], parent_resource: APIScopeObject) -> Optional[str]:
- """Attribute holding the id of `model`'s `parent_resource` foreign key, if it has one.
+def _fallback_parent_fk(model: type[Model], parent_resource: APIScopeObject) -> Optional[ForeignKey]:
+ """`model`'s foreign key to `parent_resource`, if it has one.
Found by introspection rather than a declared field map so the relationship is read off the
schema that already defines it. Cached because it depends only on the model class.
@@ -539,7 +539,7 @@ def _fallback_parent_field(model: type[Model], parent_resource: APIScopeObject)
if not isinstance(field, ForeignKey) or field.related_model is None:
continue
if model_to_resource(cast(Model, field.related_model)) == parent_resource:
- return field.attname
+ return field
return None
@@ -549,13 +549,25 @@ def fallback_parent_object_id(obj: Model, parent_resource: APIScopeObject) -> Op
None is what makes a self-managed table skip its source tiers rather than inherit from a
source it doesn't have.
"""
- field = _fallback_parent_field(type(obj), parent_resource)
- if field is None:
+ fk = _fallback_parent_fk(type(obj), parent_resource)
+ if fk is None:
return None
- parent_id = getattr(obj, field, None)
+ parent_id = getattr(obj, fk.attname, None)
return str(parent_id) if parent_id is not None else None
+def fallback_parent_object(obj: Model, parent_resource: APIScopeObject) -> Optional[Model]:
+ """The object `obj` falls back to for access, or None when it has no such parent.
+
+ Read off the object's own relation — Django caches it on the instance — so callers that
+ only need to display the parent never refetch it by id.
+ """
+ fk = _fallback_parent_fk(type(obj), parent_resource)
+ if fk is None:
+ return None
+ return getattr(obj, fk.name, None)
+
+
@frozen
class ObjectAccessDecision:
blocked_ids: frozenset[str]