Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(authorization): answer check calls with the current access rules (#124865)

Yasena9500410e17d
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index cb1e5d58d590..a83b733a11bc 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -215,6 +215,9 @@ MIDDLEWARE = [
# Must run immediately after AuthenticationMiddleware so downstream middleware
# (activity logging, structlog binding, etc.) sees the swapped staff user on /admin/* paths.
"posthog.middleware.AdminImpersonationMiddleware",
+ # Opens one authorization session per request, so `authorization.check()` without a subject
+ # uses the request's user. Middleware above this line runs outside the session and must pass a subject.
+ "products.authorization.backend.middleware.AuthorizationSessionMiddleware",
"posthog.middleware.SocialAuthExceptionMiddleware",
"posthog.middleware.SessionAgeMiddleware",
"posthog.middleware.KnownLoginDeviceCookieMiddleware",
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 8f622608f96e..5434f6c0653a 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -94,6 +94,7 @@ post_delete:products.actions.backend.models.action.action_deleted
post_delete:products.ai_observability.backend.models.llm_prompt.invalidate_llm_prompt_cache
post_delete:products.ai_observability.backend.models.llm_prompt.invalidate_llm_prompt_label_cache
post_delete:products.ai_observability.backend.models.provider_keys.provider_key_deleted
+post_delete:products.authorization.backend.logic.session.invalidate
post_delete:products.canvas.backend.search_sync.canvas_deleted
post_delete:products.cdp.backend.models.hog_functions.hog_function.team_inject_web_apps_changd
post_delete:products.cdp.backend.models.hook.hook_deleted
@@ -194,6 +195,7 @@ post_save:products.ai_observability.backend.models.llm_prompt.invalidate_llm_pro
post_save:products.ai_observability.backend.models.provider_keys.provider_key_saved
post_save:products.ai_observability.backend.models.taggers.tagger_saved
post_save:products.annotations.backend.activity_logging.annotation_created
+post_save:products.authorization.backend.logic.session.invalidate
post_save:products.autoresearch.backend.signals.on_task_run_saved
post_save:products.canvas.backend.search_sync.canvas_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.action_saved
diff --git a/products/authorization/backend/apps.py b/products/authorization/backend/apps.py
index 3e5cac5ce734..e24f18afaf2e 100644
--- a/products/authorization/backend/apps.py
+++ b/products/authorization/backend/apps.py
@@ -1,8 +1,19 @@
"""Django app configuration for authorization."""
from django.apps import AppConfig
+from django.db.models.signals import post_delete, post_save
+
+from .logic import session
+
+# A write to these models clears the session's cached rules.
+RULE_MODELS = ("ee.AccessControl", "ee.RoleMembership", "posthog.OrganizationMembership")
class AuthorizationConfig(AppConfig):
name = "products.authorization.backend"
label = "authorization"
+
+ def ready(self) -> None:
+ for model in RULE_MODELS:
+ post_save.connect(session.invalidate, sender=model, dispatch_uid=f"authorization-save-{model}")
+ post_delete.connect(session.invalidate, sender=model, dispatch_uid=f"authorization-delete-{model}")
diff --git a/products/authorization/backend/facade/api.py b/products/authorization/backend/facade/api.py
index 8af27a20601e..fd1287f9becb 100644
--- a/products/authorization/backend/facade/api.py
+++ b/products/authorization/backend/facade/api.py
@@ -10,14 +10,27 @@ Each function raises NotImplementedError until its logic lands.
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import Iterator, Sequence
+from contextlib import contextmanager
from typing import overload
from uuid import UUID
+from ..logic import legacy, session
from . import contracts
from .enums import Action, Level, SubjectType
+@contextmanager
+def authorization_session() -> Iterator[None]:
+ """Share user, project and rule lookups between the checks in the block.
+
+ Every request already runs in a session. Open one in a task or a command that checks many
+ resources. It does not bind a current user, so checks in it still pass `subject`.
+ """
+ with session.scope():
+ yield
+
+
def synchronize_organization(organization_id: UUID) -> None:
"""Reconcile the organization's authorization graph with committed database state."""
raise NotImplementedError
@@ -56,8 +69,17 @@ def check(
subject: contracts.Subject | None = None,
context: contracts.Context | None = None,
) -> bool | list[bool]:
- """Return whether the subject may take the action on the resource, or one result per request, in order."""
- raise NotImplementedError
+ """Return whether the subject may take the action on the resource, or one result per request, in order.
+
+ `subject=None` means the user of the current request. Outside a request, pass `subject`.
+ """
+ if requests is None:
+ if resource is None or action is None:
+ raise TypeError("Pass `resource` and `action`, or a sequence of check requests.")
+ return legacy.check([contracts.CheckRequest(resource=resource, action=action, subject=subject)], context)[0]
+ if resource is not None or action is not None or subject is not None:
+ raise TypeError("Pass either a sequence of check requests or `resource` and `action`, not both.")
+ return legacy.check(requests, context)
def permissions(
diff --git a/products/authorization/backend/facade/contracts.py b/products/authorization/backend/facade/contracts.py
index a26f09f6344a..a2d42deaa7cd 100644
--- a/products/authorization/backend/facade/contracts.py
+++ b/products/authorization/backend/facade/contracts.py
@@ -31,14 +31,31 @@ class OpenFgaStatus:
error: str | None
+@dataclass(frozen=True, kw_only=True)
+class Parent:
+ """The parent a resource falls back to. `type` must match the fallback map; `id=None` means no parent."""
+
+ type: ResourceType
+ id: str | None
+
+
@dataclass(frozen=True, kw_only=True)
class Resource:
- """One resource, or with `id=None` every resource of `type`, for list and create checks."""
+ """One resource, or with `id=None` every resource of `type`, for list and create checks.
+
+ `created_by_id` and `parent` are the facts the current access rules read from the object.
+ `created_by_id` is the creator's user id. A resource built without it gives the creator no
+ extra access. `parent` is the object it falls back to, such as a warehouse table's source.
+ A check on a type that falls back raises without it, because skipping the parent's rules can
+ give access the parent denies. Build the resource from the model when the model is at hand.
+ """
type: ResourceType
id: str | None = None
project_id: int | None = None
organization_id: UUID | None = None
+ created_by_id: int | None = None
+ parent: Parent | None = None
@dataclass(frozen=True, kw_only=True)
diff --git a/products/authorization/backend/facade/enums.py b/products/authorization/backend/facade/enums.py
index 070567e3011d..358f4b95d8a9 100644
--- a/products/authorization/backend/facade/enums.py
+++ b/products/authorization/backend/facade/enums.py
@@ -64,6 +64,7 @@ class ResourceType(StrEnum):
HOG_FUNCTION = "hog_function"
INTEGRATION = "integration"
SESSION_RECORDING_PLAYLIST = "session_recording_playlist"
+ SIGNAL_SCOUT = "signal_scout"
TASK = "task"
USAGE_METRIC = "usage_metric"
ACTION = "action"
diff --git a/products/authorization/backend/logic/__init__.py b/products/authorization/backend/logic/__init__.py
index 599313967c4e..09ed2d83d7cd 100644
--- a/products/authorization/backend/logic/__init__.py
+++ b/products/authorization/backend/logic/__init__.py
@@ -1,11 +1,10 @@
-"""Internals for authorization. Only facade/api.py calls this package.
+"""Internals for authorization. Only facade/api.py, the request middleware and the app config call this package.
-The implementation lands here in small steps:
+Until the rollout, `legacy.py` answers the facade with the current access control rules, so a call
+site that moves to the facade keeps its behavior. The OpenFGA implementation lands here in small steps:
- an OpenFGA client, and the bootstrap of its store and authorization model,
- the authorization model sources, which define the relations and permissions of each resource type,
- the projection that writes each organization's members, roles, access rules and share links as relationships,
- the checks and object lists that answer the facade,
- the rollout that moves each organization from the access control rules to these checks.
-
-Nothing outside this product calls the facade until the rollout is in place.
"""
diff --git a/products/authorization/backend/logic/legacy.py b/products/authorization/backend/logic/legacy.py
new file mode 100644
index 000000000000..ab21e12aac36
--- /dev/null
+++ b/products/authorization/backend/logic/legacy.py
@@ -0,0 +1,136 @@
+"""Answers checks with the current access rules (`UserAccessControl`), so each decision matches today's."""
+
+from collections.abc import Sequence
+from typing import Any, cast
+
+from posthog.models import Team, User
+from posthog.scopes import API_SCOPE_OBJECTS, APIScopeObject
+
+from products.access_control.backend.facade.contracts import FallbackParent, ObjectAccessRef
+from products.access_control.backend.facade.user_access_control import (
+ RESOURCE_FALLBACK_MAP,
+ AccessControlLevelResource,
+ UserAccessControl,
+)
+
+from ..facade.contracts import CheckRequest, Context, Subject
+from ..facade.enums import Action, ResourceType
+from .session import PrincipalKey, Session, current
+
+# MANAGE_ACCESS reads its level through the "can modify access levels" rule, which also lets
+# the creator and project admins in.
+RESOURCE_LEVELS: dict[Action, AccessControlLevelResource] = {
+ Action.VIEW: "viewer",
+ Action.QUERY: "viewer",
+ Action.EDIT: "editor",
+ Action.DELETE: "editor",
+ Action.SHARE: "editor",
+ Action.CREATE: "editor",
+ Action.MANAGE_ACCESS: "manager",
+}
+
+MEMBERSHIP_RESOURCES = frozenset({ResourceType.ORGANIZATION, ResourceType.PROJECT, ResourceType.ROLE})
+
+
+def check(requests: Sequence[CheckRequest], context: Context | None) -> list[bool]:
+ if context is not None and context != Context():
+ raise NotImplementedError("The current access rules read no request context.")
+ session = current() or Session()
+ return [_check(session, request) for request in requests]
+
+
+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.")
+ level = RESOURCE_LEVELS.get(action)
+ if level is None:
+ raise ValueError(f"{action} does not apply to {resource.type} resources.")
+ # Access rules are scoped to a team, so project_id carries the team id.
+ if resource.project_id is None:
+ raise ValueError(f"A {resource.type} check needs project_id.")
+ scope = _scope(resource.type)
+ parent_type = RESOURCE_FALLBACK_MAP.get(scope)
+ if resource.id is not None and parent_type and resource.parent is None:
+ raise ValueError(
+ f"A {resource.type} check needs `parent`, or it skips the parent's rules. "
+ f"Use Parent(type=ResourceType.{parent_type.upper()}, id=None) when the object has no parent."
+ )
+ if resource.parent is not None and resource.parent.type.value != parent_type:
+ raise ValueError(f"A {resource.type} falls back to {parent_type}, not {resource.parent.type}.")
+
+ principal = _principal(session, request.subject)
+ if principal is None:
+ return False
+ access = _access(session, principal, resource.project_id)
+ if access is None:
+ return False
+
+ if resource.id is None:
+ if action == Action.MANAGE_ACCESS:
+ return access.check_can_modify_access_levels_for_object(cast(Team, access.team))
+ return access.check_access_level_for_resource(scope, level)
+
+ ref = ObjectAccessRef(
+ resource=scope,
+ id=resource.id,
+ team_id=resource.project_id,
+ created_by_id=resource.created_by_id,
+ fallback_parent=(
+ FallbackParent(resource=_scope(resource.parent.type), id=resource.parent.id)
+ if resource.parent is not None
+ else None
+ ),
+ )
+ if action == Action.MANAGE_ACCESS:
+ return access.check_can_modify_access_levels_for_ref(ref)
+ return access.check_access_level_for_ref(ref, level)
+
+
+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}.")
+ return cast(APIScopeObject, resource_type.value)
+
+
+def _principal(session: Session, subject: Subject | None) -> Any:
+ """The user that the current access rules evaluate, or None to deny.
+
+ Without a subject this is the request's user as authentication left it, which can also be a
+ share link or a service principal. The rules evaluate it the same way a view does today.
+ """
+ request_user = session.principal() if session.principal is not None else None
+ if subject is None:
+ if session.principal is None:
+ raise ValueError("Pass a subject. No request is active, so there is no current user.")
+ return request_user if getattr(request_user, "is_authenticated", False) else None
+ if subject.user_id is None:
+ raise NotImplementedError("Only user subjects are supported yet.")
+ if isinstance(request_user, User) and request_user.pk == subject.user_id:
+ return request_user
+ if subject.user_id in session.users:
+ return session.users[subject.user_id]
+ user = User.objects.filter(pk=subject.user_id).first()
+ if session.can_cache():
+ session.users[subject.user_id] = user
+ return user
+
+
+def _principal_key(principal: Any) -> PrincipalKey:
+ if isinstance(principal, User):
+ return ("user", principal.pk)
+ return ("object", id(principal))
+
+
+def _access(session: Session, principal: Any, team_id: int) -> UserAccessControl | None:
+ key = _principal_key(principal)
+ if key in session.access:
+ # v1 keeps one instance per team, sharing the user's membership and roles across them.
+ return session.access[key].for_team_ids([team_id]).get(team_id)
+ team = Team.objects.filter(pk=team_id).first()
+ if team is None:
+ return None
+ access = UserAccessControl(user=cast(User, principal), team=team)
+ if session.can_cache():
+ session.access[key] = access
+ return access
diff --git a/products/authorization/backend/logic/session.py b/products/authorization/backend/logic/session.py
new file mode 100644
index 000000000000..d246f59c0229
--- /dev/null
+++ b/products/authorization/backend/logic/session.py
@@ -0,0 +1,82 @@
+"""The authorization session: the current user, and the lookups every check in one scope shares."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import field
+from typing import TYPE_CHECKING, Any
+
+from django.db import connection, transaction
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ from posthog.models import User
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+PrincipalKey = tuple[str, int]
+
+
+@frozen(frozen=False)
+class Session:
+ """Cached rules and lookups for one request or one `authorization_session()` block.
+
+ `principal` reads the user at check time, because DRF authenticates after the middleware.
+ `uncommitted` means a rule write waits for its commit, so nothing is cached until then.
+ """
+
+ principal: Callable[[], Any] | None = None
+ users: dict[int, User | None] = field(default_factory=dict)
+ access: dict[PrincipalKey, UserAccessControl] = field(default_factory=dict)
+ uncommitted: bool = False
+
+ def clear(self) -> None:
+ self.users.clear()
+ self.access.clear()
+
+ def committed(self) -> None:
+ self.clear()
+ self.uncommitted = False
+
+ def can_cache(self) -> bool:
+ # A rollback never runs `committed`, so caching resumes once no transaction is open.
+ if self.uncommitted and not connection.in_atomic_block:
+ self.committed()
+ return not self.uncommitted
+
+
+_current: ContextVar[Session | None] = ContextVar("authorization_session", default=None)
+
+
+def current() -> Session | None:
+ return _current.get()
+
+
+@contextmanager
+def scope(principal: Callable[[], Any] | None = None) -> Iterator[Session]:
+ """Open a session until the block exits. A block without a principal reuses a session that is already open."""
+ active = _current.get()
+ if active is not None and principal is None:
+ yield active
+ return
+ opened = Session(principal=principal)
+ token = _current.set(opened)
+ try:
+ yield opened
+ finally:
+ _current.reset(token)
+
+
+def invalidate(**_: Any) -> None:
+ """Clear the cached rules after a rule change, so later checks in this request see it."""
+ session = _current.get()
+ if session is None:
+ return
+ session.clear()
+ # A rollback sends no signal, so cache nothing until commit.
+ if connection.in_atomic_block:
+ session.uncommitted = True
+ transaction.on_commit(session.committed)
diff --git a/products/authorization/backend/middleware.py b/products/authorization/backend/middleware.py
new file mode 100644
index 000000000000..65e21d6b803a
--- /dev/null
+++ b/products/authorization/backend/middleware.py
@@ -0,0 +1,20 @@
+"""Opens an authorization session for each request."""
+
+from collections.abc import Callable
+
+from django.http import HttpRequest, HttpResponse
+
+from .logic import session
+
+
+class AuthorizationSessionMiddleware:
+ """Binds `subject=None` to the request's user for every check the request makes."""
+
+ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
+ self.get_response = get_response
+
+ def __call__(self, request: HttpRequest) -> HttpResponse:
+ # DRF replaces request.user when it authenticates, after this middleware runs, so the
+ # session reads the attribute at check time.
+ with session.scope(principal=lambda: getattr(request, "user", None)):
+ return self.get_response(request)
diff --git a/products/authorization/backend/presentation/__init__.py b/products/authorization/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/authorization/backend/presentation/resources.py b/products/authorization/backend/presentation/resources.py
new file mode 100644
index 000000000000..840c36d72088
--- /dev/null
+++ b/products/authorization/backend/presentation/resources.py
@@ -0,0 +1,48 @@
+"""Builds an authorization `Resource` from a model, with the facts the access rules read from it.
+
+It lives outside the facade because it takes a Django model, which the facade must not accept.
+"""
+
+from django.db.models import Model
+
+from posthog.models import Team
+
+from products.access_control.backend.facade.user_access_control import (
+ RESOURCE_FALLBACK_MAP,
+ fallback_parent_object_id,
+ model_to_resource,
+)
+
+from ..facade.contracts import Parent, Resource
+from ..facade.enums import ResourceType
+
+MEMBERSHIP_RESOURCES = frozenset({ResourceType.ORGANIZATION, ResourceType.PROJECT, ResourceType.ROLE})
+# 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})
+
+
+def resource_for_object(obj: Model, *, team: Team | None = None) -> Resource:
+ """The `Resource` for one object, with its creator and the parent it falls back to.
+
+ `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`.
+ """
+ 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.")
+ rules_team = None if resource_type in OWN_TEAM_RESOURCES else team
+ team_id = rules_team.id if rules_team is not None else getattr(obj, "team_id", None)
+ if team_id is None:
+ raise ValueError(f"{type(obj).__name__} has no team, so its access rules cannot be resolved.")
+ parent = RESOURCE_FALLBACK_MAP.get(scope)
+ return Resource(
+ type=resource_type,
+ id=str(obj.pk),
+ project_id=team_id,
+ created_by_id=getattr(obj, "created_by_id", None),
+ parent=Parent(type=ResourceType(parent), id=fallback_parent_object_id(obj, parent)) if parent else None,
+ )
diff --git a/products/authorization/backend/tests/test_check.py b/products/authorization/backend/tests/test_check.py
new file mode 100644
index 000000000000..d8fec069ec4f
--- /dev/null
+++ b/products/authorization/backend/tests/test_check.py
@@ -0,0 +1,316 @@
+from typing import Any
+from uuid import UUID
+
+import pytest
+from posthog.test.base import BaseTest
+
+from django.contrib.auth.models import AnonymousUser
+from django.db import transaction
+from django.http import HttpRequest, HttpResponse
+from django.test import RequestFactory
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Team, User
+
+from products.access_control.backend.facade.testing import create_access_control
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.authorization.backend.facade import api as authorization
+from products.authorization.backend.facade.contracts import CheckRequest, Context, Parent, Resource, Subject
+from products.authorization.backend.facade.enums import Action, ResourceType
+from products.authorization.backend.middleware import AuthorizationSessionMiddleware
+from products.authorization.backend.presentation.resources import resource_for_object
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+
+V1_LEVELS = {Action.VIEW: "viewer", Action.CREATE: "editor", Action.EDIT: "editor", Action.DELETE: "editor"}
+OBJECT_ACTIONS = [Action.VIEW, Action.EDIT, Action.DELETE, Action.MANAGE_ACCESS]
+CATEGORY_ACTIONS = [Action.VIEW, Action.CREATE, Action.MANAGE_ACCESS]
+
+
+class TestCheckMatchesCurrentRules(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.dashboard = Dashboard.objects.create(team=self.team, name="Revenue", created_by=self.other_user)
+
+ def _rule(self, resource: str, level: str, resource_id: str | None = None, member: bool = False) -> None:
+ create_access_control(
+ team_id=self.team.id,
+ resource=resource,
+ access_level=level,
+ resource_id=resource_id,
+ organization_member_id=self.organization_membership.id if member else None,
+ )
+
+ def _v1(self, action: Action, obj: Any = None) -> bool:
+ access = UserAccessControl(self.user, self.team)
+ if obj is None:
+ if action == Action.MANAGE_ACCESS:
+ return access.check_can_modify_access_levels_for_object(self.team)
+ return access.check_access_level_for_resource("dashboard", V1_LEVELS[action]) # type: ignore[arg-type]
+ if action == Action.MANAGE_ACCESS:
+ return access.check_can_modify_access_levels_for_object(obj)
+ return access.check_access_level_for_object(obj, V1_LEVELS[action]) # type: ignore[arg-type]
+
+ @parameterized.expand(
+ [
+ ("no_rules",),
+ ("resource_none",),
+ ("object_none",),
+ ("member_viewer_on_object",),
+ ("member_editor_on_object",),
+ ("member_manager_on_object",),
+ ("creator_with_object_none",),
+ ("project_admin_with_object_none",),
+ ("org_admin_with_object_none",),
+ ]
+ )
+ def test_object_check_matches_v1(self, scenario: str) -> None:
+ dashboard_id = str(self.dashboard.id)
+ if scenario == "resource_none":
+ self._rule("dashboard", "none")
+ elif scenario in ("object_none", "creator_with_object_none", "project_admin_with_object_none"):
+ self._rule("dashboard", "none", dashboard_id)
+ elif scenario in ("member_viewer_on_object", "member_editor_on_object"):
+ self._rule("dashboard", "none")
+ self._rule("dashboard", scenario.split("_")[1], dashboard_id, member=True)
+ elif scenario == "member_manager_on_object":
+ self._rule("dashboard", "manager", dashboard_id, member=True)
+ elif scenario == "org_admin_with_object_none":
+ self._rule("dashboard", "none", dashboard_id)
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ if scenario == "creator_with_object_none":
+ self.dashboard.created_by = self.user
+ self.dashboard.save()
+ if scenario == "project_admin_with_object_none":
+ self._rule("project", "admin", str(self.team.id), member=True)
+
+ resource = resource_for_object(self.dashboard)
+ results = authorization.check(
+ [
+ CheckRequest(resource=resource, action=action, subject=Subject(user_id=self.user.id))
+ for action in OBJECT_ACTIONS
+ ]
+ )
+
+ assert results == [self._v1(action, self.dashboard) for action in OBJECT_ACTIONS]
+
+ @parameterized.expand([("no_rules",), ("resource_none",), ("member_viewer_on_resource",), ("project_admin",)])
+ def test_category_check_matches_v1(self, scenario: str) -> None:
+ if scenario == "resource_none":
+ self._rule("dashboard", "none")
+ elif scenario == "member_viewer_on_resource":
+ self._rule("dashboard", "none")
+ self._rule("dashboard", "viewer", member=True)
+ elif scenario == "project_admin":
+ self._rule("project", "admin", str(self.team.id), member=True)
+
+ category = Resource(type=ResourceType.DASHBOARD, project_id=self.team.id)
+ results = [
+ authorization.check(resource=category, action=action, subject=Subject(user_id=self.user.id))
+ for action in CATEGORY_ACTIONS
+ ]
+
+ assert results == [self._v1(action) for action in CATEGORY_ACTIONS]
+
+ @parameterized.expand([("sourced_table", True, False), ("self_managed_table", False, True)])
+ def test_warehouse_table_falls_back_to_its_source(self, _name: str, sourced: bool, expected: bool) -> None:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id="src",
+ connection_id="conn",
+ destination_id="dest",
+ source_type="Stripe",
+ prefix="test",
+ )
+ table = DataWarehouseTable.objects.create(
+ name="customers",
+ format="Parquet",
+ team=self.team,
+ external_data_source=source if sourced else None,
+ columns={},
+ )
+ self._rule("external_data_source", "none", str(source.id))
+
+ allowed = authorization.check(
+ resource=resource_for_object(table), action=Action.VIEW, subject=Subject(user_id=self.user.id)
+ )
+
+ assert allowed is expected
+ assert allowed == UserAccessControl(self.user, self.team).check_access_level_for_object(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] = []
+
+ def view(request: HttpRequest) -> HttpResponse:
+ # DRF sets the user here, after every middleware has run.
+ request.user = self.other_user
+ results.append(authorization.check(resource=resource_for_object(self.dashboard), action=Action.EDIT))
+ return HttpResponse()
+
+ request = RequestFactory().get("/")
+ request.user = AnonymousUser()
+ AuthorizationSessionMiddleware(view)(request)
+
+ assert results == [True]
+
+ @parameterized.expand([("no_session", False), ("task_session", True)])
+ def test_check_without_a_subject_outside_a_request_raises(self, _name: str, in_session: bool) -> None:
+ resource = resource_for_object(self.dashboard)
+
+ with pytest.raises(ValueError, match="Pass a subject"):
+ if in_session:
+ with authorization.authorization_session():
+ authorization.check(resource=resource, action=Action.VIEW)
+ else:
+ authorization.check(resource=resource, action=Action.VIEW)
+
+ def test_rule_write_clears_the_rules_a_session_loaded(self) -> None:
+ resource = resource_for_object(self.dashboard)
+ subject = Subject(user_id=self.user.id)
+
+ with authorization.authorization_session():
+ before = authorization.check(resource=resource, action=Action.EDIT, subject=subject)
+ self._rule("dashboard", "none", str(self.dashboard.id))
+ after = authorization.check(resource=resource, action=Action.EDIT, subject=subject)
+
+ assert (before, after) == (True, False)
+
+ def test_rolled_back_grant_is_not_kept(self) -> None:
+ self._rule("dashboard", "none", str(self.dashboard.id))
+ resource = resource_for_object(self.dashboard)
+ subject = Subject(user_id=self.user.id)
+
+ with authorization.authorization_session():
+ with pytest.raises(RuntimeError):
+ with transaction.atomic():
+ self._rule("dashboard", "editor", str(self.dashboard.id), member=True)
+ during = authorization.check(resource=resource, action=Action.EDIT, subject=subject)
+ raise RuntimeError
+ after = authorization.check(resource=resource, action=Action.EDIT, subject=subject)
+
+ assert (during, after) == (True, False)
+
+ def test_rolled_back_user_deletion_is_not_kept(self) -> None:
+ user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ resource = resource_for_object(self.dashboard)
+ subject = Subject(user_id=user.id)
+
+ with authorization.authorization_session():
+ with pytest.raises(RuntimeError):
+ with transaction.atomic():
+ self._rule("dashboard", "editor", str(self.dashboard.id))
+ User.objects.filter(pk=user.id).delete()
+ during = authorization.check(resource=resource, action=Action.VIEW, subject=subject)
+ raise RuntimeError
+ after = authorization.check(resource=resource, action=Action.VIEW, subject=subject)
+
+ assert (during, after) == (False, True)
+
+ def test_session_answers_each_team_with_its_own_rules(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_dashboard = Dashboard.objects.create(team=other_team, name="Costs", created_by=self.other_user)
+ create_access_control(
+ team_id=other_team.id, resource="dashboard", access_level="none", resource_id=str(other_dashboard.id)
+ )
+ subject = Subject(user_id=self.user.id)
+
+ with authorization.authorization_session():
+ results = [
+ authorization.check(resource=resource_for_object(dashboard), action=Action.EDIT, subject=subject)
+ for dashboard in (self.dashboard, other_dashboard, self.dashboard)
+ ]
+
+ assert results == [True, False, True]
+
+ def test_project_admin_cannot_manage_a_dashboard_in_another_team(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_dashboard = Dashboard.objects.create(team=other_team, name="Costs", created_by=self.other_user)
+ self._rule("project", "admin", str(self.team.id), member=True)
+ subject = Subject(user_id=self.user.id)
+
+ own_team = authorization.check(
+ resource=resource_for_object(self.dashboard), action=Action.MANAGE_ACCESS, subject=subject
+ )
+ other = authorization.check(
+ resource=resource_for_object(other_dashboard), action=Action.MANAGE_ACCESS, subject=subject
+ )
+ other_with_view_team = authorization.check(
+ resource=resource_for_object(other_dashboard, team=self.team),
+ action=Action.MANAGE_ACCESS,
+ subject=subject,
+ )
+
+ assert (own_team, other, other_with_view_team) == (True, 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(
+ team_id=other_team.pk,
+ source_id="src",
+ connection_id="conn",
+ destination_id="dest",
+ source_type="Stripe",
+ prefix="test",
+ )
+ create_access_control(
+ team_id=other_team.id, resource="external_data_source", access_level="none", resource_id=str(source.id)
+ )
+ subject = Subject(user_id=self.user.id)
+
+ own_team = authorization.check(resource=resource_for_object(source), action=Action.EDIT, subject=subject)
+ view_team = authorization.check(
+ resource=resource_for_object(source, team=self.team), action=Action.EDIT, subject=subject
+ )
+
+ assert (own_team, view_team) == (False, True)
+ assert view_team == UserAccessControl(self.user, self.team).check_access_level_for_object(source, "editor")
+
+ @parameterized.expand(
+ [
+ (
+ "organization",
+ {"resource": Resource(type=ResourceType.ORGANIZATION, id=str(UUID(int=1)))},
+ NotImplementedError,
+ ),
+ ("action_without_a_level", {"action": Action.JOIN}, ValueError),
+ ("no_project", {"resource": Resource(type=ResourceType.DASHBOARD, id="1")}, ValueError),
+ (
+ "warehouse_table_without_parent",
+ {"resource": Resource(type=ResourceType.WAREHOUSE_TABLE, id="1", project_id=1)},
+ ValueError,
+ ),
+ (
+ "parent_of_another_type",
+ {
+ "resource": Resource(
+ type=ResourceType.WAREHOUSE_TABLE,
+ id="1",
+ project_id=1,
+ parent=Parent(type=ResourceType.WAREHOUSE_OBJECTS, id="1"),
+ )
+ },
+ ValueError,
+ ),
+ ("context", {"context": Context(channel="mcp")}, NotImplementedError),
+ ("api_key_subject", {"subject": Subject(api_key_id="key")}, NotImplementedError),
+ ]
+ )
+ def test_unsupported_check_raises(self, _name: str, overrides: dict[str, Any], error: type[Exception]) -> None:
+ kwargs: dict[str, Any] = {
+ "resource": resource_for_object(self.dashboard),
+ "action": Action.VIEW,
+ "subject": Subject(user_id=self.user.id),
+ **overrides,
+ }
+
+ with pytest.raises(error):
+ authorization.check(**kwargs)
diff --git a/products/authorization/backend/tests/test_session.py b/products/authorization/backend/tests/test_session.py
new file mode 100644
index 000000000000..51b9543414d3
--- /dev/null
+++ b/products/authorization/backend/tests/test_session.py
@@ -0,0 +1,17 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.authorization.backend.logic.session import Session
+
+
+class TestSessionCaching(SimpleTestCase):
+ @parameterized.expand([("transaction_still_open", True, False), ("transaction_ended", False, True)])
+ def test_caching_after_an_uncommitted_write(self, _name: str, in_transaction: bool, expected: bool) -> None:
+ session = Session(uncommitted=True)
+
+ with patch("products.authorization.backend.logic.session.connection") as connection:
+ connection.in_atomic_block = in_transaction
+ assert session.can_cache() is expected
diff --git a/tach.toml b/tach.toml
index 1eb8a172edbc..6d97854c4773 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1883,12 +1883,17 @@ from = [
[[modules]]
path = "products.authorization"
-depends_on = []
+depends_on = [
+ "posthog",
+ "products.access_control",
+]
layer = "modules"
[[interfaces]]
expose = [
"backend\\.facade.*",
+ # Django adapters, such as building a Resource from a model. The facade cannot take a model.
+ "backend\\.presentation.*",
]
from = [
"products.authorization",