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.

chore: cache membership lookups for access control (#91753)

Reece Jonesd84458da880f
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index 13cebe1da88a..c9f5d4283e2b 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -516,8 +516,12 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
@cached_property
def organization(self) -> Organization:
+ if self._is_team_view:
+ return self.team.organization
try:
- return Organization.objects.get(id=self.organization_id)
+ return Organization.objects.get(
+ id=self.project.organization_id if self._is_project_view else self.organization_id
+ )
except (Organization.DoesNotExist, ValueError):
raise NotFound(detail="Organization not found.")
diff --git a/posthog/apps.py b/posthog/apps.py
index 846b93c851eb..bb4881c2e8ba 100644
--- a/posthog/apps.py
+++ b/posthog/apps.py
@@ -9,6 +9,7 @@ from asgiref.sync import async_to_sync
from posthoganalytics.client import Client
from posthog.git import get_git_branch, get_git_commit_short
+from posthog.organization_caching import connect_signal_handlers as connect_organization_cache_signal_handlers
from posthog.utils import (
_build_flag_provider,
get_available_timezones_with_offsets,
@@ -40,6 +41,7 @@ class PostHogConfig(AppConfig):
connect_signal_handlers()
connect_gateway_credential_signal_handlers()
+ connect_organization_cache_signal_handlers()
# Connect core signal receivers at app-population. They used to wire in as an import
# side effect of viewset modules; with the lazy API router those no longer load at
diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.py
index 76411ae8d812..20eced9fc512 100644
--- a/posthog/models/test/test_organization_model.py
+++ b/posthog/models/test/test_organization_model.py
@@ -11,6 +11,12 @@ from parameterized import parameterized
from posthog.models import Organization, OrganizationInvite
from posthog.models.organization import BillingPeriod, OrganizationMembership
+from posthog.models.user import User
+from posthog.organization_caching import (
+ get_cached_organization,
+ get_cached_organization_membership,
+ get_cached_organization_memberships,
+)
from posthog.plugins.test.mock import mocked_plugin_requests_get
from posthog.plugins.test.plugin_archives import HELLO_WORLD_PLUGIN_GITHUB_ZIP
from posthog.redis import get_client
@@ -175,6 +181,65 @@ class TestOrganization(BaseTest):
self.organization.save()
self.assertEqual(cache.get(f"org_session_age:{self.organization.id}"), 7200)
+ def test_access_cache_reuses_organization_and_membership_details(self):
+ with self.settings(ORGANIZATION_ACCESS_CACHE_ENABLED=True):
+ with self.assertNumQueries(1):
+ membership = get_cached_organization_membership(self.organization.id, self.user)
+ assert membership is not None
+ assert membership.organization == self.organization
+ assert membership.user == self.user
+
+ with self.assertNumQueries(1):
+ assert get_cached_organization_memberships(self.user)[0].organization == self.organization
+
+ with self.assertNumQueries(0):
+ assert get_cached_organization(self.organization.id) == self.organization
+ assert get_cached_organization_membership(self.organization.id, self.user) == membership
+ assert get_cached_organization_memberships(self.user)[0] == membership
+
+ def test_access_cache_is_invalidated_when_organization_or_membership_changes(self):
+ with self.settings(ORGANIZATION_ACCESS_CACHE_ENABLED=True):
+ membership = get_cached_organization_membership(self.organization.id, self.user)
+ assert membership is not None
+ get_cached_organization_memberships(self.user)
+
+ membership.level = OrganizationMembership.Level.ADMIN
+ with self.captureOnCommitCallbacks(execute=True):
+ membership.save()
+ updated_membership = get_cached_organization_membership(self.organization.id, self.user)
+ assert updated_membership is not None
+ assert updated_membership.level == OrganizationMembership.Level.ADMIN
+ assert get_cached_organization_memberships(self.user)[0].level == OrganizationMembership.Level.ADMIN
+
+ self.organization.name = "Updated organization"
+ self.organization.save()
+ updated_organization = get_cached_organization(self.organization.id)
+ assert updated_organization is not None
+ assert updated_organization.name == "Updated organization"
+
+ with self.captureOnCommitCallbacks(execute=True):
+ membership.delete()
+ assert get_cached_organization_membership(self.organization.id, self.user) is None
+ assert get_cached_organization_memberships(self.user) == []
+
+ def test_access_cache_is_invalidated_when_membership_is_created(self):
+ with self.settings(ORGANIZATION_ACCESS_CACHE_ENABLED=True):
+ new_user = User.objects.create_user(
+ email="[email protected]", password="password", first_name="Cache"
+ )
+
+ # Cache both the missing individual membership and the user's empty membership list.
+ assert get_cached_organization_membership(self.organization.id, new_user) is None
+ assert get_cached_organization_memberships(new_user) == []
+
+ with self.captureOnCommitCallbacks(execute=True):
+ OrganizationMembership.objects.create(organization=self.organization, user=new_user)
+
+ membership = get_cached_organization_membership(self.organization.id, new_user)
+ assert membership is not None
+ assert membership.user_id == new_user.id
+ assert [item.id for item in get_cached_organization_memberships(new_user)] == [membership.id]
+
@parameterized.expand(
[
("valid_period", {"period": ["2024-01-01T00:00:00Z", "2024-02-01T00:00:00Z"]}, True),
diff --git a/posthog/organization_caching.py b/posthog/organization_caching.py
new file mode 100644
index 000000000000..7550d4d70c68
--- /dev/null
+++ b/posthog/organization_caching.py
@@ -0,0 +1,234 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID, uuid4
+
+from django.apps import apps
+from django.conf import settings
+from django.core.cache import caches
+from django.db import transaction
+from django.db.models.signals import post_delete, post_save
+
+import structlog
+
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization, OrganizationMembership
+ from posthog.models.user import User
+
+
+logger = structlog.get_logger(__name__)
+
+access_cache = caches["organization_access"]
+
+ORGANIZATION_ACCESS_CACHE_TTL_SECONDS = 60
+_ORGANIZATION_ACCESS_CACHE_MISS = "missing"
+
+
+def _organization_model() -> type[Organization]:
+ return cast("type[Organization]", apps.get_model("posthog", "Organization"))
+
+
+def _organization_membership_model() -> type[OrganizationMembership]:
+ return cast("type[OrganizationMembership]", apps.get_model("posthog", "OrganizationMembership"))
+
+
+def _organization_cache_key(organization_id: str | UUID) -> str:
+ return f"organization_access:organization:{organization_id}"
+
+
+def _organization_membership_cache_key(organization_id: str | UUID, user_id: int) -> str:
+ return f"organization_access:membership:{organization_id}:{user_id}"
+
+
+def _user_organization_memberships_cache_key(user_id: int) -> str:
+ return f"organization_access:user_memberships:{user_id}"
+
+
+def _access_cache_version_key(key: str) -> str:
+ return f"{key}:version"
+
+
+def _get_access_cache_value(key: str) -> Any:
+ try:
+ return access_cache.get(key)
+ except Exception:
+ logger.warning("organization_access_cache_get_failure", cache_key=key, exc_info=True)
+ return None
+
+
+def _set_access_cache_value(key: str, value: Any) -> None:
+ try:
+ access_cache.set(key, value, timeout=ORGANIZATION_ACCESS_CACHE_TTL_SECONDS)
+ except Exception:
+ logger.warning("organization_access_cache_set_failure", cache_key=key, exc_info=True)
+
+
+def _delete_access_cache_value(key: str) -> None:
+ try:
+ access_cache.delete(key)
+ except Exception:
+ logger.warning("organization_access_cache_delete_failure", cache_key=key, exc_info=True)
+
+
+def _get_cache_version(key: str) -> str | None:
+ value = _get_access_cache_value(_access_cache_version_key(key))
+ return value if isinstance(value, str) else None
+
+
+def _set_versioned_access_cache_value(key: str, value: Any, version: str | None) -> None:
+ _set_access_cache_value(key, (version, value))
+
+
+def _get_versioned_access_cache_value(key: str, version: str | None = None) -> Any | None:
+ cached = _get_access_cache_value(key)
+ if not isinstance(cached, tuple) or len(cached) != 2:
+ return None
+ cached_version, value = cached
+ if cached_version != _get_cache_version(key) or (version is not None and cached_version != version):
+ return None
+ return value
+
+
+def _cache_organization(organization: Organization, version: str | None) -> None:
+ _set_versioned_access_cache_value(_organization_cache_key(organization.id), organization, version)
+
+
+def get_cached_organization(organization_id: str | UUID) -> Organization | None:
+ organization_model = _organization_model()
+ if not settings.ORGANIZATION_ACCESS_CACHE_ENABLED:
+ try:
+ return organization_model.objects.get(id=organization_id)
+ except (organization_model.DoesNotExist, ValueError):
+ return None
+
+ key = _organization_cache_key(organization_id)
+ version = _get_cache_version(key)
+ cached = _get_versioned_access_cache_value(key, version)
+ if cached == _ORGANIZATION_ACCESS_CACHE_MISS:
+ return None
+ if isinstance(cached, organization_model):
+ return cached
+
+ try:
+ organization = organization_model.objects.get(id=organization_id)
+ except (organization_model.DoesNotExist, ValueError):
+ _set_versioned_access_cache_value(key, _ORGANIZATION_ACCESS_CACHE_MISS, version)
+ return None
+
+ _set_versioned_access_cache_value(key, organization, version)
+ return organization
+
+
+def _prepare_cached_membership(membership: OrganizationMembership, user: User) -> OrganizationMembership:
+ membership._state.fields_cache["user"] = user
+ organization = membership._state.fields_cache.get("organization") or get_cached_organization(
+ membership.organization_id
+ )
+ if organization is not None:
+ membership._state.fields_cache["organization"] = organization
+ return membership
+
+
+def _cache_membership(membership: OrganizationMembership, version: str | None = None) -> None:
+ organization = membership._state.fields_cache.pop("organization", None)
+ user = membership._state.fields_cache.pop("user", None)
+ key = _organization_membership_cache_key(membership.organization_id, membership.user_id)
+ _set_versioned_access_cache_value(key, membership, _get_cache_version(key) if version is None else version)
+ if organization is not None:
+ membership._state.fields_cache["organization"] = organization
+ if user is not None:
+ membership._state.fields_cache["user"] = user
+
+
+def get_cached_organization_membership(organization_id: str | UUID, user: User) -> OrganizationMembership | None:
+ organization_membership_model = _organization_membership_model()
+ if not settings.ORGANIZATION_ACCESS_CACHE_ENABLED:
+ try:
+ return organization_membership_model.objects.select_related("organization").get(
+ organization_id=organization_id, user_id=user.id
+ )
+ except (organization_membership_model.DoesNotExist, ValueError):
+ return None
+
+ key = _organization_membership_cache_key(organization_id, user.id)
+ version = _get_cache_version(key)
+ organization_version = _get_cache_version(_organization_cache_key(organization_id))
+ cached = _get_versioned_access_cache_value(key, version)
+ if cached == _ORGANIZATION_ACCESS_CACHE_MISS:
+ return None
+ if isinstance(cached, organization_membership_model):
+ return _prepare_cached_membership(cached, user)
+
+ try:
+ membership = organization_membership_model.objects.select_related("organization").get(
+ organization_id=organization_id, user_id=user.id
+ )
+ except (organization_membership_model.DoesNotExist, ValueError):
+ _set_versioned_access_cache_value(key, _ORGANIZATION_ACCESS_CACHE_MISS, version)
+ return None
+
+ _cache_organization(membership.organization, organization_version)
+ _cache_membership(membership, version)
+ return _prepare_cached_membership(membership, user)
+
+
+def get_cached_organization_memberships(user: User) -> list[OrganizationMembership]:
+ organization_membership_model = _organization_membership_model()
+ if not settings.ORGANIZATION_ACCESS_CACHE_ENABLED:
+ return list(organization_membership_model.objects.filter(user_id=user.id).select_related("organization"))
+
+ key = _user_organization_memberships_cache_key(user.id)
+ version = _get_cache_version(key)
+ cached = _get_versioned_access_cache_value(key, version)
+ if isinstance(cached, list):
+ return [_prepare_cached_membership(membership, user) for membership in cached]
+
+ memberships = list(organization_membership_model.objects.filter(user_id=user.id).select_related("organization"))
+ for membership in memberships:
+ get_cached_organization(membership.organization_id)
+ membership._state.fields_cache.pop("organization", None)
+ membership._state.fields_cache.pop("user", None)
+ _set_versioned_access_cache_value(key, memberships, version)
+ return [_prepare_cached_membership(membership, user) for membership in memberships]
+
+
+def invalidate_organization_access_cache(organization_id: str | UUID) -> None:
+ if not settings.ORGANIZATION_ACCESS_CACHE_ENABLED:
+ return
+
+ key = _organization_cache_key(organization_id)
+ _set_access_cache_value(_access_cache_version_key(key), uuid4().hex)
+ _delete_access_cache_value(key)
+
+
+def invalidate_organization_membership_access_cache(organization_id: str | UUID, user_id: int) -> None:
+ if not settings.ORGANIZATION_ACCESS_CACHE_ENABLED:
+ return
+
+ keys = (
+ _organization_membership_cache_key(organization_id, user_id),
+ _user_organization_memberships_cache_key(user_id),
+ )
+
+ def invalidate_after_commit() -> None:
+ for key in keys:
+ _set_access_cache_value(_access_cache_version_key(key), uuid4().hex)
+ _delete_access_cache_value(key)
+
+ transaction.on_commit(invalidate_after_commit)
+
+
+def clear_organization_access_cache(sender: Any, instance: Organization, **kwargs: Any) -> None:
+ invalidate_organization_access_cache(instance.id)
+ transaction.on_commit(lambda: invalidate_organization_access_cache(instance.id))
+
+
+def clear_organization_membership_access_cache(sender: Any, instance: OrganizationMembership, **kwargs: Any) -> None:
+ invalidate_organization_membership_access_cache(instance.organization_id, instance.user_id)
+
+
+def connect_signal_handlers() -> None:
+ post_save.connect(clear_organization_access_cache, sender=_organization_model())
+ post_delete.connect(clear_organization_access_cache, sender=_organization_model())
+ post_save.connect(clear_organization_membership_access_cache, sender=_organization_membership_model())
+ post_delete.connect(clear_organization_membership_access_cache, sender=_organization_membership_model())
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 495d1db6887f..86e89a9d88cd 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -35,6 +35,7 @@ from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED
from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Project, Team, User
from posthog.models.oauth import OAuthAccessToken
from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.organization_caching import get_cached_organization_membership
from posthog.scopes import (
INTERNAL_API_SCOPE_OBJECTS,
MCP_BUILT_IN_AGENT_SCOPE,
@@ -99,6 +100,13 @@ def get_organization_from_view(view) -> Organization:
raise ValueError("View not compatible with organization-based permissions!")
+def get_required_organization_membership(request: Request, organization: Organization) -> OrganizationMembership:
+ membership = get_cached_organization_membership(organization.id, cast(User, request.user))
+ if membership is None:
+ raise NotFound("Organization not found.")
+ return membership
+
+
class CanCreateOrg(BasePermission):
"""Whether new organizations can be created in this instances."""
@@ -132,15 +140,11 @@ class OrganizationMemberPermissions(BasePermission):
return True
organization = get_organization_from_view(view)
-
- # TODO: Optimize this - we can get it from view.user_access_control
- return OrganizationMembership.objects.filter(user=cast(User, request.user), organization=organization).exists()
+ return get_cached_organization_membership(organization.id, cast(User, request.user)) is not None
def has_object_permission(self, request: Request, view, object: Model) -> bool:
organization = extract_organization(object, view)
-
- # TODO: Optimize this - we can get it from view.user_access_control
- return OrganizationMembership.objects.filter(user=cast(User, request.user), organization=organization).exists()
+ return get_cached_organization_membership(organization.id, cast(User, request.user)) is not None
class UserNoOrgMembershipDeletePermission(BasePermission):
@@ -173,28 +177,16 @@ class OrganizationAdminWritePermissions(BasePermission):
if view.basename == "organizations" and view.action not in ["create"]:
return True
- # TODO: Optimize so that this computation is only done once, on `OrganizationMemberPermissions`
organization = get_organization_from_view(view)
-
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
-
+ membership = get_required_organization_membership(request, organization)
return membership.level >= OrganizationMembership.Level.ADMIN
def has_object_permission(self, request: Request, view, object: Model) -> bool:
if request.method in SAFE_METHODS:
return True
- # TODO: Optimize so that this computation is only done once, on `OrganizationMemberPermissions`
organization = extract_organization(object, view)
-
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
-
+ membership = get_required_organization_membership(request, organization)
return membership.level >= OrganizationMembership.Level.ADMIN
@@ -209,22 +201,12 @@ class OrganizationAdminReadPermissions(BasePermission):
def has_permission(self, request: Request, view) -> bool:
organization = get_organization_from_view(view)
-
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
-
+ membership = get_required_organization_membership(request, organization)
return membership.level >= OrganizationMembership.Level.ADMIN
def has_object_permission(self, request: Request, view, object: Model) -> bool:
organization = extract_organization(object, view)
-
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
-
+ membership = get_required_organization_membership(request, organization)
return membership.level >= OrganizationMembership.Level.ADMIN
@@ -858,17 +840,16 @@ class APIScopePermission(ScopeBasePermission):
if not org.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS):
return
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=org)
-
- if not org.members_can_use_personal_api_keys and membership.level < OrganizationMembership.Level.ADMIN:
- raise PermissionDenied(
- f"Organization '{org.name}' does not allow using personal API keys. "
- f"Contact an admin to enable personal API keys for this organization."
- )
- except OrganizationMembership.DoesNotExist:
+ membership = get_cached_organization_membership(org.id, cast(User, request.user))
+ if membership is None:
return
+ if not org.members_can_use_personal_api_keys and membership.level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied(
+ f"Organization '{org.name}' does not allow using personal API keys. "
+ f"Contact an admin to enable personal API keys for this organization."
+ )
+
class MCPAccessPermission(ScopeBasePermission):
"""Denies write actions through the MCP server when the organization restricts it.
@@ -1217,10 +1198,7 @@ class UserCanInvitePermission(BasePermission):
if not org_invite_settings_available:
return True
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
+ membership = get_required_organization_membership(request, organization)
members_can_invite = bool(organization.members_can_invite)
user_is_admin = membership.level >= OrganizationMembership.Level.ADMIN
@@ -1246,10 +1224,7 @@ class UserCanCreateProjectPermission(BasePermission):
except ValueError:
return True
- try:
- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)
- except OrganizationMembership.DoesNotExist:
- raise NotFound("Organization not found.")
+ membership = get_required_organization_membership(request, organization)
if membership.level >= OrganizationMembership.Level.ADMIN:
return True
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index dd942907904b..ec7d6ac8e3c5 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -26,6 +26,9 @@ TEST = get_from_env(
# `dbshell` there is no Python REPL (it execs the DB client), so nothing to restore.
IS_INTERACTIVE_SHELL: bool = len(sys.argv) > 1 and sys.argv[1] in ("shell", "dbshell")
COMMAND_EXEC_AUDIT_ENABLED: bool = get_from_env("COMMAND_EXEC_AUDIT_ENABLED", not TEST, type_cast=str_to_bool)
+ORGANIZATION_ACCESS_CACHE_ENABLED: bool = get_from_env(
+ "ORGANIZATION_ACCESS_CACHE_ENABLED", not TEST, type_cast=str_to_bool
+)
# Kill-switch for routing JSONField (jsonb) decode through orjson (see posthog/helpers/orjson_jsonfield.py).
# Process-wide once applied in ready(), so keep it disable-able via env without a code revert.
JSONFIELD_ORJSON_DECODE: bool = get_from_env("JSONFIELD_ORJSON_DECODE", True, type_cast=str_to_bool)
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 5e62e06d12e2..f2260916aec7 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -679,6 +679,13 @@ CACHES = {
}
}
+# Authorization cache reads must use the writer. Reading membership versions and values from
+# different replicas can otherwise make a revoked membership appear valid after invalidation.
+CACHES["organization_access"] = {
+ **CACHES["default"],
+ "LOCATION": REDIS_URL,
+}
+
# Dedicated cache for the feature flags service (if configured)
# Django only writes to this cache (never reads), so no reader URL needed
if FLAGS_REDIS_URL:
@@ -741,6 +748,7 @@ else:
if TEST:
CACHES["default"] = {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}
CACHES["query_cache"] = CACHES["default"]
+ CACHES["organization_access"] = CACHES["default"]
# Cache timeout for materialized columns metadata (in seconds)
MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 796c84832977..1befc3202237 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -58,6 +58,8 @@ post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membersh
post_delete:posthog.models.organization.clean_up_event_streams_on_membership_removal
post_delete:posthog.models.organization.pause_loops_on_membership_removal
post_delete:posthog.models.organization.sync_billing_on_membership_removal
+post_delete:posthog.organization_caching.clear_organization_access_cache
+post_delete:posthog.organization_caching.clear_organization_membership_access_cache
post_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_delete
post_delete:posthog.models.remote_config.product_tour_deleted
post_delete:posthog.models.remote_config.push_integration_changed
@@ -121,6 +123,8 @@ post_save:posthog.models.global_rate_limit_threshold_config.update_redis_thresho
post_save:posthog.models.organization.cache_organization_session_age
post_save:posthog.models.organization.invalidate_llm_gateway_quota_cache_on_active_state_change
post_save:posthog.models.organization.sync_billing_on_membership_save
+post_save:posthog.organization_caching.clear_organization_access_cache
+post_save:posthog.organization_caching.clear_organization_membership_access_cache
post_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_save
post_save:posthog.models.remote_config.error_tracking_suppression_rule_saved
post_save:posthog.models.remote_config.feature_flag_saved
diff --git a/posthog/user_permissions.py b/posthog/user_permissions.py
index 242d635eef19..21c24697176f 100644
--- a/posthog/user_permissions.py
+++ b/posthog/user_permissions.py
@@ -4,6 +4,7 @@ from uuid import UUID
from posthog.constants import AvailableFeature
from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.organization_caching import get_cached_organization_memberships
from products.dashboards.backend.facade.enums import PrivilegeLevel, RestrictionLevel
from products.dashboards.backend.models.dashboard import Dashboard
@@ -96,7 +97,7 @@ class UserPermissions:
@cached_property
def organization_memberships(self) -> dict[UUID, OrganizationMembership]:
- memberships = OrganizationMembership.objects.filter(user=self.user).select_related("organization")
+ memberships = get_cached_organization_memberships(self.user)
return {membership.organization_id: membership for membership in memberships}
@cached_property
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 1ea349ef6fa4..c6f571721208 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -16,6 +16,7 @@ from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.organization_caching import get_cached_organization_membership
from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
from posthog.settings import EE_AVAILABLE
@@ -467,15 +468,9 @@ class UserAccessControl:
@cached_property
def _organization_membership(self) -> Optional[OrganizationMembership]:
- # NOTE: This is optimized to reduce queries - we get the users membership _with_ the organization
- try:
- if not self._organization_id:
- return None
- return OrganizationMembership.objects.select_related("organization").get(
- organization_id=self._organization_id, user=self._user
- )
- except OrganizationMembership.DoesNotExist:
+ if not self._organization_id:
return None
+ return get_cached_organization_membership(self._organization_id, self._user)
@cached_property
def _organization(self) -> Optional[Organization]:
diff --git a/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr b/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
index 28cf23ac9ae9..705476e20e0e 100644
--- a/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
+++ b/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
@@ -93,11 +93,57 @@
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.10
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.11
@@ -434,11 +480,57 @@
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.18
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.19
@@ -821,11 +913,57 @@
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.26
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.27
@@ -945,11 +1083,57 @@
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.3
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestPluginAPI.test_listing_plugins_is_not_nplus1.30
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index 12fcc23eb4a4..bd0e27585b2e 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -941,11 +941,57 @@
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30
@@ -1794,11 +1840,57 @@
# ---
# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.3
'''
- SELECT 1 AS "a"
+ SELECT "posthog_organizationmembership"."id",
+ "posthog_organizationmembership"."organization_id",
+ "posthog_organizationmembership"."user_id",
+ "posthog_organizationmembership"."level",
+ "posthog_organizationmembership"."joined_at",
+ "posthog_organizationmembership"."updated_at",
+ "posthog_organizationmembership"."invited_by_id",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."enforce_verified_domains",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."members_can_see_org_members",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."read_only_mcp_access",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."has_active_subscription",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_organizationmembership"
+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")
WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
+ LIMIT 21
'''
# ---
# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.4