: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(authorization): answer permissions and membership checks (#126357)
Yasen6c903e931954
diff --git a/products/authorization/backend/facade/api.py b/products/authorization/backend/facade/api.pyindex fd1287f9becb..5821c2aa5da3 100644--- a/products/authorization/backend/facade/api.py+++ b/products/authorization/backend/facade/api.py@@ -89,7 +89,7 @@ def permissions(context: contracts.Context | None = None,) -> frozenset[Action]:"""Return every action the subject may take on the resource."""- raise NotImplementedError+ return legacy.permissions(resource, subject, context)def list_objects(diff --git a/products/authorization/backend/logic/legacy.py b/products/authorization/backend/logic/legacy.pyindex ab21e12aac36..4431e1c9700c 100644--- a/products/authorization/backend/logic/legacy.py+++ b/products/authorization/backend/logic/legacy.py@@ -2,10 +2,14 @@from collections.abc import Sequencefrom typing import Any, cast+from uuid import UUID-from posthog.models import Team, User+from posthog.models import OrganizationMembership, Team, User+from posthog.organization_caching import get_cached_organization_membershipfrom posthog.scopes import API_SCOPE_OBJECTS, APIScopeObject+from posthog.user_permissions import UserPermissions+from products.access_control.backend.facade import api as access_control_apifrom products.access_control.backend.facade.contracts import FallbackParent, ObjectAccessReffrom products.access_control.backend.facade.user_access_control import (RESOURCE_FALLBACK_MAP,@@ -13,7 +17,7 @@ from products.access_control.backend.facade.user_access_control import (UserAccessControl,)-from ..facade.contracts import CheckRequest, Context, Subject+from ..facade.contracts import CheckRequest, Context, Resource, Subjectfrom ..facade.enums import Action, ResourceTypefrom .session import PrincipalKey, Session, current@@ -29,7 +33,21 @@ RESOURCE_LEVELS: dict[Action, AccessControlLevelResource] = {Action.MANAGE_ACCESS: "manager",}-MEMBERSHIP_RESOURCES = frozenset({ResourceType.ORGANIZATION, ResourceType.PROJECT, ResourceType.ROLE})+_Level = OrganizationMembership.Level+_ADMIN_ACTIONS = dict.fromkeys((Action.EDIT, Action.DELETE, Action.SHARE, Action.MANAGE_ACCESS), _Level.ADMIN)++# JOIN and the staff-only actions have no row, so asking for them raises instead of granting admins.+MEMBERSHIP_LEVELS: dict[ResourceType, dict[Action, OrganizationMembership.Level]] = {+ ResourceType.ORGANIZATION: {+ **_ADMIN_ACTIONS,+ Action.VIEW: _Level.MEMBER,+ Action.CREATE: _Level.ADMIN,+ Action.DELETE: _Level.OWNER,+ Action.MANAGE_OWNERS: _Level.OWNER,+ },+ ResourceType.PROJECT: {**_ADMIN_ACTIONS, Action.VIEW: _Level.MEMBER, Action.CREATE: _Level.ADMIN},+ ResourceType.ROLE: {**_ADMIN_ACTIONS, Action.VIEW: _Level.MEMBER},+}def check(requests: Sequence[CheckRequest], context: Context | None) -> list[bool]:@@ -39,10 +57,16 @@ def check(requests: Sequence[CheckRequest], context: Context | None) -> list[booreturn [_check(session, request) for request in requests]+def permissions(resource: Resource, subject: Subject | None, context: Context | None) -> frozenset[Action]:+ actions = list(MEMBERSHIP_LEVELS.get(resource.type, RESOURCE_LEVELS))+ results = check([CheckRequest(resource=resource, action=action, subject=subject) for action in actions], context)+ return frozenset(action for action, allowed in zip(actions, results, strict=True) if allowed)++def _check(session: Session, request: CheckRequest) -> bool:resource, action = request.resource, request.action- if resource.type in MEMBERSHIP_RESOURCES:- raise NotImplementedError(f"Checks on {resource.type} resources are not supported yet.")+ if resource.type in MEMBERSHIP_LEVELS:+ return _check_membership(session, request)level = RESOURCE_LEVELS.get(action)if level is None:raise ValueError(f"{action} does not apply to {resource.type} resources.")@@ -87,6 +111,57 @@ def _check(session: Session, request: CheckRequest) -> bool:return access.check_access_level_for_ref(ref, level)+def _check_membership(session: Session, request: CheckRequest) -> bool:+ resource, action = request.resource, request.action+ level = MEMBERSHIP_LEVELS[resource.type].get(action)+ if level is None:+ raise ValueError(f"{action} does not apply to {resource.type} resources.")+ if resource.id is None:+ raise ValueError(f"A {resource.type} check needs `id`.")+ if resource.type == ResourceType.ROLE and resource.organization_id is None:+ raise ValueError("A role check needs `organization_id`.")++ principal = _principal(session, request.subject)+ # Only a user holds a membership. The other principals have no organization or project level.+ if not isinstance(principal, User):+ return False++ if resource.type == ResourceType.PROJECT:+ return _check_project(session, principal, int(resource.id), action, level)+ if resource.type == ResourceType.ROLE:+ organization_id = cast(UUID, resource.organization_id)+ if not access_control_api.role_belongs_to_organization(+ role_id=UUID(resource.id), organization_id=organization_id+ ):+ return False+ else:+ organization_id = UUID(resource.id)+ membership = get_cached_organization_membership(organization_id, principal)+ return membership is not None and membership.level >= level+++def _check_project(+ session: Session, user: User, project_id: int, action: Action, level: OrganizationMembership.Level+) -> bool:+ access = _access(session, user, project_id)+ if access is None:+ return False+ team = cast(Team, access.team)+ if action == Action.MANAGE_ACCESS:+ return access.check_can_modify_access_levels_for_object(team)+ user_level = _user_permissions(session, user).team(team).effective_membership_level+ return user_level is not None and user_level >= level+++def _user_permissions(session: Session, user: User) -> UserPermissions:+ if user.pk in session.permissions:+ return session.permissions[user.pk]+ permissions = UserPermissions(user)+ if session.can_cache():+ session.permissions[user.pk] = permissions+ return permissions++def _scope(resource_type: ResourceType) -> APIScopeObject:if resource_type.value not in API_SCOPE_OBJECTS:raise ValueError(f"The current access rules have no scope for {resource_type}.")diff --git a/products/authorization/backend/logic/session.py b/products/authorization/backend/logic/session.pyindex d246f59c0229..e7234af9bdc8 100644--- a/products/authorization/backend/logic/session.py+++ b/products/authorization/backend/logic/session.py@@ -14,6 +14,7 @@ from posthog.dataclasses import frozenif TYPE_CHECKING:from posthog.models import User+ from posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -31,11 +32,13 @@ class Session:principal: Callable[[], Any] | None = Noneusers: dict[int, User | None] = field(default_factory=dict)access: dict[PrincipalKey, UserAccessControl] = field(default_factory=dict)+ permissions: dict[int, UserPermissions] = field(default_factory=dict)uncommitted: bool = Falsedef clear(self) -> None:self.users.clear()self.access.clear()+ self.permissions.clear()def committed(self) -> None:self.clear()diff --git a/products/authorization/backend/presentation/resources.py b/products/authorization/backend/presentation/resources.pyindex 840c36d72088..dbc85ed3464d 100644--- a/products/authorization/backend/presentation/resources.py+++ b/products/authorization/backend/presentation/resources.py@@ -16,7 +16,8 @@ from products.access_control.backend.facade.user_access_control import (from ..facade.contracts import Parent, Resourcefrom ..facade.enums import ResourceType-MEMBERSHIP_RESOURCES = frozenset({ResourceType.ORGANIZATION, ResourceType.PROJECT, ResourceType.ROLE})+# These types answer from the user's membership level, so they carry no team, creator or parent.+MEMBERSHIP_RESOURCES = frozenset({ResourceType.ORGANIZATION, ResourceType.PROJECT})# These types always read the object's own team, so a view team's admin can't reach another environment's object.OWN_TEAM_RESOURCES = frozenset({ResourceType.DASHBOARD})@@ -26,14 +27,14 @@ def resource_for_object(obj: Model, *, team: Team | None = None) -> Resource:`project_id` is the object's team id, because access rules are scoped to a team. Pass `team`only where today's check reads another team's rules for this object, such as the view's team.- `OWN_TEAM_RESOURCES` ignore `team`.+ `OWN_TEAM_RESOURCES` and `MEMBERSHIP_RESOURCES` ignore `team`."""scope = model_to_resource(obj)if scope is None:raise ValueError(f"{type(obj).__name__} has no access control resource.")resource_type = ResourceType(scope)if resource_type in MEMBERSHIP_RESOURCES:- raise NotImplementedError(f"Building a {resource_type} resource from a model is not supported yet.")+ return Resource(type=resource_type, id=str(obj.pk))rules_team = None if resource_type in OWN_TEAM_RESOURCES else teamteam_id = rules_team.id if rules_team is not None else getattr(obj, "team_id", None)if team_id is None:diff --git a/products/authorization/backend/tests/test_check.py b/products/authorization/backend/tests/test_check.pyindex d8fec069ec4f..582c098c17de 100644--- a/products/authorization/backend/tests/test_check.py+++ b/products/authorization/backend/tests/test_check.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom typing import Anyfrom uuid import UUID@@ -12,13 +13,16 @@ from django.test import RequestFactoryfrom parameterized import parameterizedfrom posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, Team, User+from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.user_permissions import UserPermissions-from products.access_control.backend.facade.testing import create_access_control+from products.access_control.backend.facade.contracts import FallbackParent, ObjectAccessRef+from products.access_control.backend.facade.testing import create_access_control, create_rolefrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.authorization.backend.facade import api as authorizationfrom products.authorization.backend.facade.contracts import CheckRequest, Context, Parent, Resource, Subjectfrom products.authorization.backend.facade.enums import Action, ResourceType+from products.authorization.backend.logic import sessionfrom products.authorization.backend.middleware import AuthorizationSessionMiddlewarefrom products.authorization.backend.presentation.resources import resource_for_objectfrom products.dashboards.backend.models.dashboard import Dashboard@@ -146,6 +150,79 @@ class TestCheckMatchesCurrentRules(BaseTest):assert allowed is expectedassert allowed == UserAccessControl(self.user, self.team).check_access_level_for_object(table, "viewer")+ @parameterized.expand(+ [+ ("fallback_type_without_parent", ResourceType.WAREHOUSE_TABLE, None, True),+ (+ "fallback_type_with_wrong_parent",+ ResourceType.WAREHOUSE_TABLE,+ Parent(type=ResourceType.WAREHOUSE_OBJECTS, id="5"),+ True,+ ),+ (+ "parent_on_a_type_without_one",+ ResourceType.DASHBOARD,+ Parent(type=ResourceType.EXTERNAL_DATA_SOURCE, id="5"),+ True,+ ),+ (+ "fallback_type_with_no_source",+ ResourceType.WAREHOUSE_TABLE,+ Parent(type=ResourceType.EXTERNAL_DATA_SOURCE, id=None),+ False,+ ),+ (+ "fallback_type_with_source",+ ResourceType.WAREHOUSE_TABLE,+ Parent(type=ResourceType.EXTERNAL_DATA_SOURCE, id="5"),+ False,+ ),+ ("type_without_a_parent", ResourceType.DASHBOARD, None, False),+ ]+ )+ def test_parent_checks_match_v1(+ self, _name: str, resource_type: ResourceType, parent: Parent | None, raises: bool+ ) -> None:+ resource = Resource(type=resource_type, id="1", project_id=self.team.id, parent=parent)+ ref = ObjectAccessRef(+ resource=resource_type.value, # type: ignore[arg-type]+ id="1",+ team_id=self.team.id,+ created_by_id=None,+ fallback_parent=FallbackParent(resource=parent.type.value, id=parent.id) if parent else None, # type: ignore[arg-type]+ )+ access = UserAccessControl(self.user, self.team)++ def outcome(call: Callable[[], bool]) -> bool | str:+ try:+ return call()+ except ValueError:+ return "raises"++ sdk = outcome(+ lambda: authorization.check(resource=resource, action=Action.VIEW, subject=Subject(user_id=self.user.id))+ )+ v1 = outcome(lambda: access.check_access_level_for_ref(ref, "viewer"))++ assert sdk == v1+ assert (sdk == "raises") is raises++ @parameterized.expand(+ [+ ("no_parent", None),+ ("matching_parent", Parent(type=ResourceType.EXTERNAL_DATA_SOURCE, id="5")),+ ]+ )+ def test_category_check_on_a_fallback_type_matches_v1(self, _name: str, parent: Parent | None) -> None:+ self._rule("warehouse_table", "none")+ category = Resource(type=ResourceType.WAREHOUSE_TABLE, project_id=self.team.id, parent=parent)++ allowed = authorization.check(resource=category, action=Action.VIEW, subject=Subject(user_id=self.user.id))++ assert allowed == UserAccessControl(self.user, self.team).check_access_level_for_resource(+ "warehouse_table", "viewer"+ )+def test_check_without_a_subject_reads_the_user_that_authentication_set(self) -> None:self._rule("dashboard", "none", str(self.dashboard.id), member=True)results: list[bool] = []@@ -251,6 +328,135 @@ class TestCheckMatchesCurrentRules(BaseTest):assert (own_team, other, other_with_view_team) == (True, False, False)+ @parameterized.expand(+ [+ ("no_rules", OrganizationMembership.Level.MEMBER, None, None),+ ("project_closed", OrganizationMembership.Level.MEMBER, "none", None),+ ("project_closed_member_rule", OrganizationMembership.Level.MEMBER, "none", "member"),+ ("project_closed_admin_rule", OrganizationMembership.Level.MEMBER, "none", "admin"),+ ("member_rule_none", OrganizationMembership.Level.MEMBER, None, "none"),+ ("org_admin_on_closed_project", OrganizationMembership.Level.ADMIN, "none", None),+ ]+ )+ def test_project_check_matches_v1(+ self, _name: str, org_level: OrganizationMembership.Level, project_rule: str | None, member_rule: str | None+ ) -> None:+ self.organization_membership.level = org_level+ self.organization_membership.save()+ if project_rule:+ self._rule("project", project_rule, str(self.team.id))+ if member_rule:+ self._rule("project", member_rule, str(self.team.id), member=True)+ subject = Subject(user_id=self.user.id)+ resource = resource_for_object(self.team)+ level = UserPermissions(self.user).team(self.team).effective_membership_level++ results = [+ authorization.check(resource=resource, action=action, subject=subject)+ for action in (Action.VIEW, Action.EDIT, Action.MANAGE_ACCESS)+ ]++ assert results == [+ level is not None,+ level is not None and level >= OrganizationMembership.Level.ADMIN,+ UserAccessControl(self.user, self.team).check_can_modify_access_levels_for_object(self.team),+ ]++ @parameterized.expand(+ [+ ("member", OrganizationMembership.Level.MEMBER, {Action.VIEW}),+ (+ "admin",+ OrganizationMembership.Level.ADMIN,+ {Action.VIEW, Action.EDIT, Action.CREATE, Action.SHARE, Action.MANAGE_ACCESS},+ ),+ (+ "owner",+ OrganizationMembership.Level.OWNER,+ {+ Action.VIEW,+ Action.EDIT,+ Action.CREATE,+ Action.SHARE,+ Action.MANAGE_ACCESS,+ Action.DELETE,+ Action.MANAGE_OWNERS,+ },+ ),+ ]+ )+ def test_organization_permissions_follow_the_membership_level(+ self, _name: str, org_level: OrganizationMembership.Level, expected: set[Action]+ ) -> None:+ self.organization_membership.level = org_level+ self.organization_membership.save()++ allowed = authorization.permissions(+ resource=resource_for_object(self.organization), subject=Subject(user_id=self.user.id)+ )++ assert allowed == expected++ def test_user_outside_the_organization_has_no_permissions(self) -> None:+ outsider = User.objects.create(email="[email protected]")+ subject = Subject(user_id=outsider.id)++ assert (+ authorization.permissions(resource=resource_for_object(self.organization), subject=subject) == frozenset()+ )+ assert authorization.permissions(resource=resource_for_object(self.team), subject=subject) == frozenset()++ def test_role_check_needs_the_role_in_that_organization(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ other_organization = Organization.objects.create(name="Other")+ subject = Subject(user_id=self.user.id)+ role_id = create_role(organization_id=self.organization.id, name="Engineers")+ foreign_role_id = create_role(organization_id=other_organization.id, name="Engineers")++ own, foreign = (+ authorization.check(+ resource=Resource(type=ResourceType.ROLE, id=str(id), organization_id=self.organization.id),+ action=Action.DELETE,+ subject=subject,+ )+ for id in (role_id, foreign_role_id)+ )++ assert (own, foreign) == (True, False)++ def test_permissions_on_an_object_match_each_check(self) -> None:+ self._rule("dashboard", "viewer", str(self.dashboard.id))+ resource = resource_for_object(self.dashboard)+ subject = Subject(user_id=self.user.id)++ allowed = authorization.permissions(resource=resource, subject=subject)++ assert allowed == {Action.VIEW, Action.QUERY}++ def test_rule_write_clears_the_project_level_a_session_loaded(self) -> None:+ resource = resource_for_object(self.team)+ subject = Subject(user_id=self.user.id)++ with authorization.authorization_session():+ before = authorization.check(resource=resource, action=Action.VIEW, subject=subject)+ self._rule("project", "none", str(self.team.id))+ after = authorization.check(resource=resource, action=Action.VIEW, subject=subject)++ assert (before, after) == (True, False)++ def test_principal_that_is_not_a_user_has_no_membership(self) -> None:+ class ServicePrincipal:+ is_authenticated = True++ with session.scope(ServicePrincipal):+ allowed = [+ authorization.check(resource=resource_for_object(obj), action=Action.VIEW)+ for obj in (self.organization, self.team)+ ]++ assert allowed == [False, False]+def test_resource_for_object_with_a_team_reads_that_team_rules(self) -> None:other_team = Team.objects.create(organization=self.organization, name="Other")source = ExternalDataSource.objects.create(@@ -277,23 +483,42 @@ class TestCheckMatchesCurrentRules(BaseTest):@parameterized.expand([(- "organization",- {"resource": Resource(type=ResourceType.ORGANIZATION, id=str(UUID(int=1)))},- NotImplementedError,+ "join_on_an_organization",+ {"resource": Resource(type=ResourceType.ORGANIZATION, id=str(UUID(int=1))), "action": Action.JOIN},+ ValueError,+ ),+ (+ "staff_action_on_a_project",+ {"resource": Resource(type=ResourceType.PROJECT, id="1"), "action": Action.SUPPORT},+ ValueError,+ ),+ ("organization_without_an_id", {"resource": Resource(type=ResourceType.ORGANIZATION)}, ValueError),+ ("project_without_an_id", {"resource": Resource(type=ResourceType.PROJECT, project_id=1)}, ValueError),+ (+ "role_without_an_organization",+ {"resource": Resource(type=ResourceType.ROLE, id=str(UUID(int=1)))},+ ValueError,),("action_without_a_level", {"action": Action.JOIN}, ValueError),("no_project", {"resource": Resource(type=ResourceType.DASHBOARD, id="1")}, ValueError),(- "warehouse_table_without_parent",+ "warehouse_table_without_parent_in_a_missing_team",{"resource": Resource(type=ResourceType.WAREHOUSE_TABLE, id="1", project_id=1)},ValueError,),(- "parent_of_another_type",+ "warehouse_table_without_parent_for_an_unknown_user",+ {+ "resource": Resource(type=ResourceType.WAREHOUSE_TABLE, id="1", project_id=1),+ "subject": Subject(user_id=999999),+ },+ ValueError,+ ),+ (+ "category_with_a_parent_of_another_type",{"resource": Resource(type=ResourceType.WAREHOUSE_TABLE,- id="1",project_id=1,parent=Parent(type=ResourceType.WAREHOUSE_OBJECTS, id="1"),)