: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(models): add fail-closed TeamScopedManager for tenant isolation (#52408)
Julian Bezf6b2a65026f5
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 4773ac00cd21..f032319ed9f2 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -30,7 +30,7 @@ def setup_django() -> None:django.setup()-def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:+def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[str]]:"""Scan all Django models and categorize by scope.@@ -43,7 +43,8 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:since the team filter is the primary access control mechanism.Returns:- Tuple of (scoped_models_dict, excluded_models_set)+ Tuple of (scoped_models_dict, excluded_models_set,+ legitimately_unscoped_set, needs_team_id_set)."""from django.apps import appsfrom django.db.models import ForeignKey@@ -84,6 +85,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:"PersonlessDistinctId","SessionRecordingEvent",# --- Persons system (managed separately, not looked up by user input) ---+ "FlatPersonOverride","Group","PendingPersonOverride","Person",@@ -192,9 +194,129 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:"ResourceTransfer",}+ # Legitimately unscoped — these models correctly have no team_id.+ # Silent pass in CI. Adding here requires a category comment.+ LEGITIMATELY_UNSCOPED: set[str] = {+ # --- Django/third-party internals ---+ "AccessAttempt",+ "AccessFailureLog",+ "AccessLog",+ "Association",+ "Code",+ "ContentType",+ "Group",+ "LogEntry",+ "Nonce",+ "OAuthAccessToken",+ "OAuthApplication",+ "OAuthGrant",+ "OAuthIDToken",+ "OAuthRefreshToken",+ "Partial",+ "Permission",+ "Session",+ "StaticDevice",+ "StaticToken",+ "TOTPDevice",+ "UserSocialAuth",+ # --- Core identity (are the scope, not scoped themselves) ---+ "Organization",+ "Team",+ "User",+ # --- Instance-level config ---+ "AsyncMigration",+ "AsyncMigrationError",+ "InstanceSetting",+ "License",+ # --- Deprecated ---+ "Prompt",+ "PromptSequence",+ "UserPromptState",+ # --- Global catalogs ---+ "HogFunctionTemplate",+ "MCPServer",+ # --- Special (has source_team + destination_team, not a plain team) ---+ "ResourceTransfer",+ # --- Organization-scoped (correctly above team level) ---+ "OrganizationDomain",+ "OrganizationIntegration",+ "OrganizationInvite",+ "OrganizationMembership",+ "OrganizationResourceAccess",+ "Plugin",+ "PluginSourceFile",+ "Project",+ "ProxyRecord",+ "Role",+ "RoleMembership",+ # --- User-scoped (cross-tenant by design) ---+ "NotificationViewed",+ "SCIMProvisionedUser",+ "SCIMRequestLog",+ "WebauthnCredential",+ # --- Infra / no tenant data ---+ "EventBuffer",+ "EventIngestionRestrictionConfig",+ "MessagingRecord",+ }++ # Baseline violations — these models SHOULD have team_id but don't yet.+ # Emits a warning (not error) in CI. Shrink this list over time.+ # When adding team_id to a model, remove it from here.+ NEEDS_TEAM_ID: set[str] = {+ # --- Through/junction tables (scoped only via parent FK chain) ---+ "ActionStep", # via Action+ "AlertCheck", # via AlertConfiguration+ "AlertSubscription", # via AlertConfiguration+ "Approval", # via ChangeRequest+ "CohortPeople", # via Cohort+ "ConversationCheckpoint", # via Conversation+ "ConversationCheckpointBlob", # via ConversationCheckpoint+ "ConversationCheckpointWrite", # via ConversationCheckpoint+ "DashboardPrivilege", # via Dashboard+ "DashboardTile", # via Dashboard+ "Element", # via Event/ElementGroup+ "ErrorTrackingExternalReference", # via ErrorTrackingIssue+ "ErrorTrackingIssueCohort", # via ErrorTrackingIssue+ "EvaluationReportRun", # via EvaluationReport+ "EventSchema", # via EventDefinition+ "ExperimentMetricResult", # via Experiment+ "ExperimentToSavedMetric", # via Experiment+ "ExternalDataSourceRevenueAnalyticsConfig", # via ExternalDataSource+ "FeatureFlagDashboards", # via FeatureFlag+ "FeatureFlagEvaluationContext", # via FeatureFlag+ "FeatureFlagRoleAccess", # via FeatureFlag+ "HeatmapSnapshot", # via SavedHeatmap+ "LLMSkillFile", # via LLMSkill+ "LogsAlertCheck", # via LogsAlertConfiguration+ "LogsAlertEvent", # via LogsAlertConfiguration+ "NotificationReadState", # via NotificationEvent+ "PluginStorage", # via PluginConfig+ "ResourceNotebook", # via Notebook+ "SchemaPropertyGroupProperty", # via SchemaPropertyGroup+ "ScoreDefinitionVersion", # via ScoreDefinition+ "SessionRecordingExternalReference", # via SessionRecording+ "SessionRecordingPlaylistItem", # via Playlist+ "SharePassword", # via SharingConfiguration+ "SourceBatchStatus", # via SourceBatch+ "StreamlitAppSandbox", # via StreamlitApp+ "TaggedItem", # via Tag/Dashboard/Insight+ "TaskAutomation", # via Task+ "TicketAssignment", # via Ticket+ "UserGroupMembership", # via UserGroup+ # --- Other models missing direct team_id ---+ "BatchExportDestination", # via Integration+ "BatchExportRun", # via BatchExport+ "CodeInvite", # user-scoped but stores team data+ "CodeInviteRedemption", # via CodeInvite+ "SandboxSnapshot", # via Integration+ "SlackUserProfileCache", # via Integration+ }+team_scoped: set[str] = set()org_scoped: set[str] = set()user_scoped: set[str] = set()+ no_scope: set[str] = set()for model in apps.get_models():model_name = model.__name__@@ -207,12 +329,17 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:if model._meta.proxy:continue- # Check for FK fields+ # Check for FK fields and plain team_id (ProductTeamModel uses BigIntegerField)has_team_fk = Falsehas_org_fk = Falsehas_user_fk = Falsefor field in model._meta.get_fields():+ # Plain team_id field (e.g., ProductTeamModel's BigIntegerField)+ if getattr(field, "name", None) == "team_id" and not isinstance(field, ForeignKey):+ has_team_fk = True+ continue+if not isinstance(field, ForeignKey):continue@@ -234,14 +361,19 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str]]:org_scoped.add(model_name)elif has_user_fk:user_scoped.add(model_name)+ else:+ no_scope.add(model_name)return ({"team_scoped": team_scoped,"org_scoped": org_scoped,"user_scoped": user_scoped,+ "no_scope": no_scope,},EXCLUDED_MODELS,+ LEGITIMATELY_UNSCOPED,+ NEEDS_TEAM_ID,)@@ -323,7 +455,7 @@ def main() -> int:setup_django()# Get models from code- code_models, excluded_models = get_scoped_models()+ code_models, excluded_models, legitimately_unscoped, needs_team_id = get_scoped_models()# Get models from semgrep rulessemgrep_path = Path(__file__).parent.parent.parent / ".semgrep/rules/idor-team-scoped-models.yaml"@@ -379,13 +511,49 @@ def main() -> int:if not missing and not stale:print(" ✅ All models covered")+ # Check for models with no team/org/user scope at all+ acknowledged = legitimately_unscoped | needs_team_id+ unacknowledged = code_models["no_scope"] - acknowledged++ print(f"\n{'=' * 60}")+ print("Unscoped model check")+ print("=" * 60)++ baseline_in_code = code_models["no_scope"] & needs_team_id+ if baseline_in_code:+ has_warnings = True+ models_list = ", ".join(sorted(baseline_in_code))+ # GitHub Actions annotation — shows in PR checks tab+ print(f"::warning::{len(baseline_in_code)} models need team_id (baseline debt): {models_list}")+ print(f"\n ⚠️ WARNING: {len(baseline_in_code)} models need team_id (baseline debt):")+ for model in sorted(baseline_in_code):+ print(f" - {model}")++ if unacknowledged:+ has_errors = True+ models_list = ", ".join(sorted(unacknowledged))+ # GitHub Actions annotation+ print(f"::error::New unscoped models without team_id: {models_list}")+ print(f"\n ❌ ERROR: New models with no team_id, org, or user FK:")+ for model in sorted(unacknowledged):+ print(f" - {model}")+ print("\n Every model storing tenant data must have team_id.")+ print(" To fix:")+ print(" - Add team_id to the model (preferred)")+ print(" - Add to LEGITIMATELY_UNSCOPED if correctly unscoped")+ print(" - Add to NEEDS_TEAM_ID as last resort (baseline debt)")++ if not unacknowledged and not baseline_in_code:+ print(" ✅ No unacknowledged unscoped models")+print("\n" + "=" * 60)if has_errors:- print("\n❌ FAILED: Some models are missing from semgrep IDOR rules.")+ print("\n❌ FAILED: Some models need attention.")print("\nTo fix:")print(" 1. Add the missing models to .semgrep/rules/idor-team-scoped-models.yaml")print(" 2. Or add them to EXCLUDED_MODELS in this script if they don't need IDOR protection")+ print(" 3. For unscoped models: add team_id, or add to LEGITIMATELY_UNSCOPED / NEEDS_TEAM_ID")return 1if has_warnings:diff --git a/.semgrep/rules/celery-team-scope.yaml b/.semgrep/rules/celery-team-scope.yamlnew file mode 100644index 000000000000..2d7f1789dc12--- /dev/null+++ b/.semgrep/rules/celery-team-scope.yaml@@ -0,0 +1,97 @@+rules:+ - id: celery-task-team-scope-audit+ patterns:+ # Match tasks declared with or without parens. Semgrep matches the decorator+ # regardless of other decorators stacked around it.+ - pattern-either:+ - pattern-inside: |+ @shared_task(...)+ def $FUNC(...):+ ...+ - pattern-inside: |+ @shared_task+ def $FUNC(...):+ ...+ - pattern-either:+ # Read-shaped+ - pattern: $MODEL.objects.all()+ - pattern: $MODEL.objects.filter(...)+ - pattern: $MODEL.objects.get(...)+ - pattern: $MODEL.objects.exclude(...)+ - pattern: $MODEL.objects.first()+ - pattern: $MODEL.objects.last()+ - pattern: $MODEL.objects.count()+ - pattern: $MODEL.objects.exists()+ - pattern: $MODEL.objects.values(...)+ - pattern: $MODEL.objects.values_list(...)+ - pattern: $MODEL.objects.aggregate(...)+ - pattern: $MODEL.objects.in_bulk(...)+ - pattern: $MODEL.objects.iterator(...)+ # Mutating — top-level (.filter().delete() is incidentally caught by the filter pattern)+ - pattern: $MODEL.objects.create(...)+ - pattern: $MODEL.objects.update(...)+ - pattern: $MODEL.objects.delete()+ - pattern: $MODEL.objects.bulk_create(...)+ - pattern: $MODEL.objects.bulk_update(...)+ - pattern: $MODEL.objects.update_or_create(...)+ - pattern: $MODEL.objects.get_or_create(...)+ # Async variants+ - pattern: $MODEL.objects.aget(...)+ - pattern: $MODEL.objects.aupdate(...)+ - pattern: $MODEL.objects.acount()+ - pattern: $MODEL.objects.aexists()+ - pattern: $MODEL.objects.aiterator(...)+ # Raw SQL via the manager+ - pattern: $MODEL.objects.raw(...)+ - pattern-not-inside: |+ @with_team_scope(...)+ def $FUNC(...):+ ...+ # Tasks that legitimately need to bypass the audit (model still uses+ # RootTeamManager, task is genuinely cross-team, etc.) tag themselves+ # with @skip_team_scope_audit. The marker is a no-op at runtime; its+ # only purpose is to silence this rule for the marked function.+ - pattern-not-inside: |+ @skip_team_scope_audit+ def $FUNC(...):+ ...+ - pattern-not: $MODEL.objects.unscoped()+ - pattern-not: $MODEL.objects.unscoped().$METHOD(...)+ message: |+ Celery task accesses model without explicit team scoping.++ Background tasks don't have request context, so automatic team scoping+ won't work. Either:+ 1. Add @with_team_scope() decorator if the task should be team-scoped+ 2. Use .unscoped() if intentionally querying across teams++ Example with decorator:+ @shared_task+ @with_team_scope()+ def my_task(team_id: int):+ FeatureFlag.objects.all() # Scoped to team_id++ Example with unscoped:+ @shared_task+ def my_task():+ FeatureFlag.objects.unscoped().all() # Explicitly cross-team+ languages: [python]+ severity: WARNING+ paths:+ # Default-on: rule runs across the whole codebase. Pre-existing tasks+ # that query models still using RootTeamManager (or default Manager)+ # are tagged with @skip_team_scope_audit, which is a no-op at runtime+ # and silences this rule. New tasks must either use @with_team_scope,+ # use .unscoped(), or explicitly skip with @skip_team_scope_audit —+ # forcing a deliberate decision per task. See README for guidance.+ exclude:+ - '**/test/**'+ - '**/tests/**'+ - '**/.semgrep/**'+ metadata:+ category: security+ subcategory:+ - audit+ technology:+ - django+ - celerydiff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 5170645392eb..87797bafc9f2 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -165,9 +165,11 @@ rules:|ProductTour|ProjectSecretAPIKey|PropertyAccessControl+ |QuarantinedIdentifier|QueryTabState|QuickFilter|QuickFilterContext+ |Repo|RepoRoutingRule|SandboxEnvironment|ScoreDefinition@@ -185,6 +187,7 @@ rules:|SignalSourceConfig|SingleSessionSummary|SlackThreadTaskMapping+ |SourceBatch|StreamlitApp|Subscription|SubscriptionDelivery@@ -199,6 +202,7 @@ rules:|EvaluationReport|Text|Threshold+ |ToleratedHash|TeamConversationsTeamsConfig|Ticket|TicketView@@ -368,9 +372,11 @@ rules:|ProductTour|ProjectSecretAPIKey|PropertyAccessControl+ |QuarantinedIdentifier|QueryTabState|QuickFilter|QuickFilterContext+ |Repo|RepoRoutingRule|SandboxEnvironment|ScoreDefinition@@ -388,6 +394,7 @@ rules:|SignalSourceConfig|SingleSessionSummary|SlackThreadTaskMapping+ |SourceBatch|StreamlitApp|Subscription|SubscriptionDelivery@@ -402,6 +409,7 @@ rules:|EvaluationReport|Text|Threshold+ |ToleratedHash|TeamConversationsTeamsConfig|Ticket|TicketViewdiff --git a/.semgrep/rules/tests/celery-team-scope.py b/.semgrep/rules/tests/celery-team-scope.pynew file mode 100644index 000000000000..6d582efa9a07--- /dev/null+++ b/.semgrep/rules/tests/celery-team-scope.py@@ -0,0 +1,53 @@+# Test cases for celery-team-scope semgrep rule++from celery import shared_task++from posthog.models.feature_flag import FeatureFlag+from posthog.models.scoping import with_team_scope+++# ruleid: celery-task-team-scope-audit+@shared_task+def bad_task_no_scoping():+ # This should be flagged - no team scoping+ flags = FeatureFlag.objects.all()+ return flags+++# ruleid: celery-task-team-scope-audit+@shared_task(ignore_result=True)+def bad_task_with_filter():+ # This should be flagged - no team scoping+ flags = FeatureFlag.objects.filter(active=True)+ return flags+++# ok: celery-task-team-scope-audit+@shared_task+@with_team_scope()+def good_task_with_decorator(team_id: int):+ # This is OK - has @with_team_scope decorator+ flags = FeatureFlag.objects.all()+ return flags+++# ok: celery-task-team-scope-audit+@shared_task+def good_task_with_unscoped():+ # This is OK - explicitly unscoped+ flags = FeatureFlag.objects.unscoped().all()+ return flags+++# ok: celery-task-team-scope-audit+@shared_task+def good_task_with_unscoped_filter():+ # This is OK - explicitly unscoped+ flags = FeatureFlag.objects.unscoped().filter(active=True)+ return flags+++# Not a celery task - should not be flagged+def regular_function():+ flags = FeatureFlag.objects.all()+ return flagsdiff --git a/AGENTS.md b/AGENTS.mdindex 06b42643def0..2a6808036693 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -103,7 +103,7 @@ See [.agents/security.md](.agents/security.md) for SQL, HogQL, and semgrep secur- MCP UI apps (interactive visualizations for tool results) are defined in `products/*/mcp/tools.yaml` under `ui_apps` and auto-generated — see [services/mcp/CONTRIBUTING.md](services/mcp/CONTRIBUTING.md) or use the `implementing-mcp-ui-apps` skill- When touching a viewset or serializer, ensure schema annotations are present (`@extend_schema` or `@validated_request` on viewset methods, `help_text` on serializer fields) — these flow into generated frontend types and MCP tool schemas- New features should live in `products/` — read [products/README.md](products/README.md) for layout and setup. When _creating a new_ product, follow [products/architecture.md](products/architecture.md) (DTOs, facades, isolation)-- Always filter querysets by `team_id` — in serializers, access the team via `self.context["get_team"]()`+- **Every tenant-data model must have `team_id`** — either as a FK (`models.ForeignKey("posthog.Team", ...)`) or a plain `BigIntegerField` (for multi-DB products). This is the primary tenant isolation boundary. Models without `team_id` must be org-scoped, user-scoped, or instance-global — never silently unscoped. For new products, inherit from `ProductTeamModel` (see `posthog/models/scoping/README.md`). In serializers, access the team via `self.context["get_team"]()`- **Do not add domain-specific fields to the `Team` model.** Use a Team Extension model instead — see `posthog/models/team/README.md` for the pattern and helpers- **PostHog event capture in Celery tasks:** Do not use `posthoganalytics.capture()` in Celery tasks — events are silently lost. Use `ph_scoped_capture` from `posthog.ph_client` instead (see its docstring for why and usage).- **Django admin `ForeignKey` fields need explicit widget config.** When adding a `ForeignKey`/`OneToOneField` to a model that's exposed in Django admin (including via inlines attached to a _related_ admin), list the new field in `autocomplete_fields`, `raw_id_fields`, or `readonly_fields` on **every** admin class that renders the model — otherwise the default `<select>` widget loads the entire target table per row on each change-page render. Prefer declaring the config on a shared base inline so per-parent variants (e.g., subclasses differentiated by `fk_name`) inherit it automatically.diff --git a/ee/api/vercel/tasks.py b/ee/api/vercel/tasks.pyindex 158f3b5643ed..40e1139c570f 100644--- a/ee/api/vercel/tasks.py+++ b/ee/api/vercel/tasks.py@@ -4,11 +4,13 @@ from celery import shared_taskfrom posthog.models.integration import Integrationfrom posthog.models.organization_integration import OrganizationIntegrationfrom posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef backfill_vercel_connectable_resources() -> None:"""One-shot task to create missing Integration resources for connectable Vercel installations."""from ee.vercel.client import VercelAPIClientdiff --git a/ee/tasks/auto_rollback_feature_flag.py b/ee/tasks/auto_rollback_feature_flag.pyindex bafe47a3c485..c3dee9dfdb75 100644--- a/ee/tasks/auto_rollback_feature_flag.py+++ b/ee/tasks/auto_rollback_feature_flag.py@@ -8,6 +8,7 @@ from posthog.models.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Teamfrom posthog.queries.trends.trends import Trends+from posthog.scoping_audit import skip_team_scope_auditfrom ee.api.sentry_stats import get_stats_for_timerange@@ -22,6 +23,7 @@ def check_flags_to_rollback():@shared_task(ignore_result=True, max_retries=2)+@skip_team_scope_auditdef check_feature_flag_rollback_conditions(feature_flag_id: int) -> None:flag: FeatureFlag = FeatureFlag.objects.get(pk=feature_flag_id)diff --git a/ee/tasks/scim_request_log_cleanup.py b/ee/tasks/scim_request_log_cleanup.pyindex bef0102c8b2b..a16121344809 100644--- a/ee/tasks/scim_request_log_cleanup.py+++ b/ee/tasks/scim_request_log_cleanup.py@@ -4,12 +4,15 @@ from django.utils import timezonefrom celery import shared_task+from posthog.scoping_audit import skip_team_scope_audit+from ee.models.scim_request_log import SCIM_REQUEST_LOG_RETENTION_DAYS, SCIMRequestLogCLEANUP_BATCH_SIZE = 1000@shared_task(ignore_result=True)+@skip_team_scope_auditdef cleanup_old_scim_request_logs() -> None:cutoff = timezone.now() - timedelta(days=SCIM_REQUEST_LOG_RETENTION_DAYS)while True:diff --git a/posthog/api/routing.py b/posthog/api/routing.pyindex 6147b43e718d..e62728b7f851 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -23,6 +23,7 @@ from posthog.auth import (from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queriesfrom posthog.models.organization import Organizationfrom posthog.models.project import Project+from posthog.models.scoping import reset_current_team_id, set_current_team_idfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import (@@ -87,6 +88,76 @@ class TeamAndOrgViewSetMixin(_GenericViewSet): # TODO: Rename to include "Env"if method in cls.__dict__:raise Exception(f"Method {method} is protected and should not be overridden. {message}")+ def dispatch(self, request, *args, **kwargs):+ """+ Outermost wrapper for the request lifecycle. The try/finally below+ ensures cleanup across the standard `initial`/`finalize_response`+ override surface — a subclass that customizes either of those without+ calling super() would otherwise leak the token.++ Note: a subclass that overrides `dispatch` itself without super() would+ also bypass this cleanup; in this codebase only `query_coalescer.py`+ overrides dispatch and it does call super().++ ContextVars in sync Django are thread-local and the same worker thread+ is reused across requests, so a leaked token would let scope from one+ request bleed into the next.++ Setting the scope still happens in initial() (where authentication has+ completed and self.team is loaded by permission checks for free).+ """+ try:+ return super().dispatch(request, *args, **kwargs)+ finally:+ token = getattr(self, "_team_scope_token", None)+ if token is not None:+ reset_current_team_id(token)+ self._team_scope_token = None++ def initial(self, request, *args, **kwargs):+ """+ Set team scope context to the canonical team_id (parent if the URL+ team is a child environment, the URL team itself otherwise). This is+ the single source of truth for team scoping in DRF request flows —+ any code path that reads through TeamScopedManager (used by both+ main-DB models and ProductTeamModel-based product models) during+ this request filters by this id.++ Sourcing from the URL (not user.current_team_id) avoids the org-level+ bug from #50899: user.current_team_id is a UI preference that can+ drift from the team being acted on.++ Runs after super().initial() so authentication has completed and+ permission checks have already loaded self.team for free.++ If a subclass overrides initial() without calling super(), context is+ simply never set — scoped queries raise TeamScopeError, which is the+ correct fail-closed behavior. dispatch() above guarantees cleanup+ regardless.+ """+ super().initial(request, *args, **kwargs)+ self._team_scope_token = None+ if self._is_team_view or self._is_project_view:+ try:+ team_id = self.team_id+ except (KeyError, ValidationError, AuthenticationFailed):+ # Resolution failed — leave context unset; downstream code that+ # touches a scoped model will get TeamScopeError, which is the+ # correct fail-closed behavior.+ return+ # Compute canonical team_id. self.team is a @cached_property+ # (line ~297) usually loaded by the permission checks above, so+ # this is free. Reading via __dict__ rather than attribute access+ # avoids triggering the lookup if it hasn't fired yet; if it+ # hasn't, fall back to the raw URL team_id (correct for root+ # teams, which are the common case). If self.team ever stops+ # being a @cached_property this still degrades safely.+ if "team" in self.__dict__:+ canonical_team_id = self.team.parent_team_id or team_id+ else:+ canonical_team_id = team_id+ self._team_scope_token = set_current_team_id(canonical_team_id)+def dangerously_get_permissions(self):"""WARNING: This should be used very carefully. It is only for endpoints with very specific permission needs.diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.pyindex 0332a75cb6ca..adaf1eba83ad 100644--- a/posthog/api/test/test_routing.py+++ b/posthog/api/test/test_routing.py@@ -9,6 +9,8 @@ from django.urls import include, pathfrom django.utils import timezonefrom rest_framework import viewsets+from rest_framework.decorators import action+from rest_framework.response import Responsefrom posthog.api.annotation import AnnotationSerializerfrom posthog.api.oauth.test_dcr import generate_rsa_key@@ -17,6 +19,7 @@ from posthog.models.annotation import Annotationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organizationfrom posthog.models.project import Project+from posthog.models.scoping import get_current_team_idfrom posthog.models.team.team import Team@@ -25,6 +28,10 @@ class FooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = Annotation.objects.all()serializer_class = AnnotationSerializer+ @action(detail=False, methods=["get"])+ def current_scope(self, request, **kwargs):+ return Response({"team_id": get_current_team_id()})+class ScopedFooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "annotation"@@ -95,6 +102,34 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):self.assertEqual(response.status_code, 200)self.assertEqual(response.json()["count"], 3) # All except other_org_annotation+ def test_team_scope_context_set_from_url_team_not_user_current_team(self):+ # User's "current" team is set to self.team, but the URL targets another+ # team in the same org. The team scope context inside the view must reflect+ # the URL's team, not user.current_team_id (otherwise queries would silently+ # mismatch — same class of bug as #50899).+ other_team = Team.objects.create(organization=self.organization, project=self.project)+ self.user.current_team = self.team+ self.user.save()++ # Capture the scope before the request — `dispatch()` resets via+ # ContextVar.reset(token), which restores whatever was in scope before+ # the view fired. Some test runners may have leftover scope from+ # earlier tests on the same thread; we just assert the wrapper+ # restored the pre-request value, not unconditionally None.+ pre_request_scope = get_current_team_id()++ response = self.client.get(f"/api/environments/{other_team.id}/foos/current_scope/")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["team_id"], other_team.id)+ self.assertEqual(get_current_team_id(), pre_request_scope)++ def test_team_scope_context_set_from_url_for_project_view(self):+ response = self.client.get(f"/api/projects/{self.team.id}/foos/current_scope/")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["team_id"], self.team.id)+def test_cannot_override_special_methods(self):with pytest.raises(Exception) as e:diff --git a/posthog/approvals/tasks.py b/posthog/approvals/tasks.pyindex 46e131ce2a35..1795b4983955 100644--- a/posthog/approvals/tasks.py+++ b/posthog/approvals/tasks.py@@ -8,11 +8,13 @@ from structlog import get_loggerfrom posthog.approvals.models import ChangeRequest, ChangeRequestState, ValidationStatusfrom posthog.approvals.notifications import send_approval_expired_notification+from posthog.scoping_audit import skip_team_scope_auditlogger = get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef validate_pending_change_requests() -> dict[str, Any]:"""Periodic staleness check for pending change requests.@@ -82,6 +84,7 @@ def validate_pending_change_requests() -> dict[str, Any]:@shared_task(ignore_result=True)+@skip_team_scope_auditdef expire_old_change_requests() -> dict[str, Any]:"""Scheduled task to expire old pending change requests.diff --git a/posthog/caching/warming.py b/posthog/caching/warming.pyindex 86ad2c1e0c89..ec6ef9701fa6 100644--- a/posthog/caching/warming.py+++ b/posthog/caching/warming.py@@ -24,6 +24,7 @@ from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Insight, Teamfrom posthog.ph_client import ph_scoped_capturefrom posthog.schema_migrations.upgrade_manager import upgrade_query+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuefrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -134,6 +135,7 @@ def insights_to_keep_fresh(team: Team, shared_only: bool = False) -> Generator[t@shared_task(ignore_result=True, expires=60 * 15)+@skip_team_scope_auditdef schedule_warming_for_teams_task():"""Runs every hour and schedule warming for all insights (picked from insights_to_cache)diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex f6cfc27c8001..02e122496f5f 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -19,6 +19,7 @@ from posthog.models.insight import Insightfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import RootTeamMixin, UUIDTModel+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.utils import get_instance_realm, get_safe_cache, safe_cache_delete, safe_cache_set@@ -317,6 +318,7 @@ class ProductIntent(UUIDTModel, RootTeamMixin):@shared_task(ignore_result=True)+@skip_team_scope_auditdef calculate_product_activation(team_id: int, only_calc_if_days_since_last_checked: int = 1) -> None:"""Calculate product activation for a team.diff --git a/posthog/models/scoping/README.md b/posthog/models/scoping/README.mdnew file mode 100644index 000000000000..aa9218ed3312--- /dev/null+++ b/posthog/models/scoping/README.md@@ -0,0 +1,110 @@+# Team Scoping++Fail-closed team scoping for Django models. Queries without team context raise `TeamScopeError` instead of silently returning all rows.++This is a defense-in-depth convenience layer, not a complete security boundary. Django's `_base_manager` bypasses custom managers for related-object access, and raw SQL bypasses the ORM entirely. Use this alongside explicit team checks at the API layer.++Related: [#47073](https://github.com/PostHog/posthog/pull/47073), [#50899](https://github.com/PostHog/posthog/pull/50899)++## The contract++A ContextVar holds the **canonical** team_id — the parent team's id when the team is a child environment, the team's own id otherwise. Reads filter by it. Writes through `ProductTeamModel.save()` rewrite child team_ids to canonical (mirror of `RootTeamMixin.save()` for main-DB models). No context = exception.++`team_scope()` / `with_team_scope()` / `for_team()` auto-resolve to canonical by default — one Team lookup per scope entry, much cheaper than per-query resolution and removes the silent-zero-rows footgun where `with team_scope(child_id):` would scope reads to a child id with no data. Pass `canonical=True` to skip resolution when the caller already has the canonical id (or in tests with synthetic ids).++## Where context gets set++- **DRF nested views** — `TeamAndOrgViewSetMixin.initial()` sets it from the URL `self.team_id` (the team being acted on, not the user's "current" team). Reuses `self.team.parent_team_id` if cached by permission checks for free.+- **Celery tasks** — `@with_team_scope()` decorator extracts a `team_id` parameter from the task signature.+- **Management commands / ad-hoc scripts** — `with team_scope(team_id):` block.++There is no middleware fallback. The original POC (#46874) had one defaulting to `user.current_team_id`, but that value is a UI preference and can drift from the team being acted on — using it as a silent default is exactly the bug class this framework is meant to prevent. Non-DRF code paths must opt in.++## Usage++```python+# DRF view — context set automatically from the URL+Repo.objects.all() # filtered to canonical team++# no context — raises TeamScopeError+Repo.objects.all() # ← boom++# explicit cross-team escape hatch (queryset method)+Repo.objects.unscoped().all() # no filtering, no error++# explicit scope to one team (auto-resolves to canonical)+Repo.objects.for_team(team_id)++# bulk over many teams — pre-resolve once, skip per-call lookup+canonical_ids = [resolve_effective_team_id(t.id) for t in teams]+for cid in canonical_ids:+ Repo.objects.for_team(cid, canonical=True).count()++# background scope block (auto-resolves)+with team_scope(team_id):+ Repo.objects.all()++# celery task — same auto-resolve, applied via decorator+from celery import shared_task+from posthog.models.scoping import with_team_scope++@shared_task+@with_team_scope()+def my_task(team_id: int):+ Repo.objects.all()+```++## Adoption++### New product on a separate database++Use `ProductTeamModel` as the abstract base. It declares `team_id` as a `BigIntegerField` (no FK, since cross-DB FKs aren't supported), wires `objects = TeamScopedManager()`, and overrides `save()` to rewrite to canonical.++```python+from posthog.models.scoping.product_mixin import ProductTeamModel++class Repo(ProductTeamModel):+ repo_name = models.CharField(max_length=255)+ # team_id inherited — BigIntegerField, indexed, no FK+```++### Existing main-DB model++Keep your `RootTeamMixin` (it already declares `team` as `ForeignKey("Team", ...)` and rewrites on save). Swap the manager:++```python+class FeatureFlag(RootTeamMixin): # unchanged — handles save() + FK+ objects = TeamScopedManager() # was RootTeamManager() — adds enforcement+```++The manager is the same class for both worlds — `ProductTeamModel` and `RootTeamMixin` differ only in how `team_id` is stored (FK vs BigInt). Migrating any existing model means swapping its manager and auditing every call site to either be inside team scope or use `.unscoped()`.++### Celery tasks against models still on RootTeamManager++`RootTeamManager`-backed models don't read the ContextVar, so `@with_team_scope` adds nothing — but the semgrep rule `celery-task-team-scope-audit` flags any unscoped `Model.objects.X` in a Celery task. For tasks that legitimately don't need scope (model still on the older manager, or genuinely cross-team), tag the task with the no-op marker:++```python+from posthog.scoping_audit import skip_team_scope_audit++@shared_task+@skip_team_scope_audit # FeatureFlag still uses RootTeamManager+def my_task():+ FeatureFlag.objects.filter(...).delete()+```++Remove the marker once the underlying model migrates to `TeamScopedManager`. The decorator lives at `posthog.scoping_audit` (not `posthog.models.scoping`) so it can be imported at module load by Celery task files without triggering Django's app registry — see the file's docstring for the load-order story.++## Bypass managers++Two surfaces to opt out of scoping, named distinctly to avoid an autocomplete trap:++- `Model.objects.unscoped()` — queryset method on the scoped manager. Returns a fresh `TeamScopedQuerySet` with no filter applied. Use this for "I want to query across teams in this one place" within normal request lifecycle code.+- `Model.all_teams` — second plain `Manager` declared on `ProductTeamModel`. Use this for code that runs _outside_ the request lifecycle (admin classes, migrations, manage.py commands) where setting context with `team_scope(...)` is awkward.++The two are deliberately not the same name. A future contributor autocompleting `Model.unscoped.filter(...)` thinking they're being explicit about scoping would otherwise silently get every team's rows back.++## Known limitations++- **`_base_manager`**: Django uses `_base_manager` (not `objects`) for related-object access like `repo.runs.all()`. This bypasses the scoped manager. Related-object traversal is still safe because the FK constrains the result set — but the `team_id` filter is not applied.+- **Raw SQL**: `cursor.execute()` and `QuerySet.raw()` bypass managers entirely.+- **Django admin**: Uses `_default_manager`. Since `objects` is declared first on `ProductTeamModel`, admin goes through the scoped manager and would raise without context — use `Model.all_teams` in admin classes.diff --git a/posthog/models/scoping/__init__.py b/posthog/models/scoping/__init__.pynew file mode 100644index 000000000000..fd1f20849c03--- /dev/null+++ b/posthog/models/scoping/__init__.py@@ -0,0 +1,189 @@+# Team Scoping Context+#+# Provides automatic team scoping for Django models using Python's ContextVar.+# Models using TeamScopedManager / ProductTeamModel will read this context+# and auto-filter their queries.+#+# Contract: the team_id stored in context is the **canonical** team_id where+# data lives — i.e. the parent team's id when the team is a child environment,+# or the team's own id when it's a root team. Callers (the DRF mixin, Celery+# task helpers, manual `team_scope()` callers) are responsible for resolving+# to the canonical id before setting context. ProductTeamModel.save() also+# rewrites to the canonical id, so writes and reads stay symmetric.+#+# Usage:+# # In DRF nested views — set automatically by TeamAndOrgViewSetMixin:+# FeatureFlag.objects.all() # Auto-filtered to canonical team+#+# # Explicit cross-team query (escape hatch):+# FeatureFlag.objects.unscoped().all() # No team filtering+#+# # In background jobs / management commands (caller passes canonical id):+# with team_scope(canonical_team_id):+# FeatureFlag.objects.all()++import inspect+import functools+from collections.abc import Callable, Generator+from contextlib import contextmanager+from contextvars import ContextVar, Token+from typing import ParamSpec, TypeVar++P = ParamSpec("P")+R = TypeVar("R")+++# The current canonical team_id, or None if no scope is set.+_current_team_id: ContextVar[int | None] = ContextVar("current_team_id", default=None)+++def get_current_team_id() -> int | None:+ """Get the current canonical team_id, or None if no scope is set."""+ return _current_team_id.get()+++def set_current_team_id(team_id: int | None) -> Token[int | None]:+ """Set the current canonical team_id. Returns a token to reset it later.++ Pass `None` to clear context (used by `unscoped()`).+ """+ return _current_team_id.set(team_id)+++def reset_current_team_id(token: Token[int | None]) -> None:+ """Reset the current team_id to its previous value."""+ _current_team_id.reset(token)+++@contextmanager+def team_scope(team_id: int, *, canonical: bool = False) -> Generator[None, None, None]:+ """+ Context manager to set the current team_id for a block of code.++ By default, resolves `team_id` to its canonical id (parent if the team+ is a child environment, the team's own id otherwise) — one Team lookup+ per scope entry. This guarantees the manager's filter finds rows+ regardless of whether the caller passed a parent or a child id.++ Pass `canonical=True` if the caller has already resolved (or is using+ a synthetic id in tests). Skipping resolution silently scopes queries+ to whatever id was passed; if it isn't actually canonical, reads will+ return zero rows from the wrong scope.++ Example:+ # Production: caller may have a child id, framework resolves+ with team_scope(team_id):+ flags = FeatureFlag.objects.all()++ # Test or pre-resolved caller: skip the lookup+ with team_scope(self.team.id, canonical=True):+ flags = FeatureFlag.objects.all()+ """+ if not canonical:+ # Imported here to avoid the manager → __init__ circular dependency+ from posthog.models.scoping.manager import resolve_effective_team_id++ team_id = resolve_effective_team_id(team_id)+ token = set_current_team_id(team_id)+ try:+ yield+ finally:+ reset_current_team_id(token)+++@contextmanager+def unscoped() -> Generator[None, None, None]:+ """+ Context manager to temporarily disable automatic team scoping.++ Useful when you explicitly need to query across teams.++ Example:+ with unscoped():+ all_flags = FeatureFlag.objects.all() # All teams+ """+ token = set_current_team_id(None)+ try:+ yield+ finally:+ reset_current_team_id(token)+++def with_team_scope(+ team_id_param: str = "team_id",+ *,+ canonical: bool = False,+) -> Callable[[Callable[P, R]], Callable[P, R]]:+ """+ Decorator that wraps a function in a team_scope() context.++ Extracts the team_id from the function's arguments and sets it as the+ current team context for the duration of the function call. Auto-resolves+ to canonical via `team_scope()` — callers can pass any team_id (raw or+ canonical) and the framework guarantees the manager's filter finds+ rows.++ Pass `canonical=True` if the wrapped function will only ever be called+ with already-canonical team_ids (or in tests with synthetic ids) to skip+ the per-call Team lookup.++ Args:+ team_id_param: Name of the parameter containing the team_id.+ Defaults to "team_id".++ Example:+ @shared_task+ @with_team_scope()+ def my_task(team_id: int, other_arg: str):+ # team context is automatically set from team_id parameter+ flags = FeatureFlag.objects.all() # Auto-filtered to team_id++ @shared_task+ @with_team_scope(team_id_param="project_team_id")+ def another_task(project_team_id: int):+ # team context set from project_team_id parameter+ pass+ """++ def decorator(func: Callable[P, R]) -> Callable[P, R]:+ # Cache signature inspection at decoration time (not per-call)+ sig = inspect.signature(func)+ params = list(sig.parameters.keys())+ param_index = params.index(team_id_param) if team_id_param in params else None++ @functools.wraps(func)+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:+ # Try to get team_id from kwargs first+ team_id = kwargs.get(team_id_param)++ # If not in kwargs, try to get from positional args using cached index+ if team_id is None and param_index is not None and param_index < len(args):+ team_id = args[param_index]++ if team_id is None:+ raise ValueError(+ f"with_team_scope: Could not find '{team_id_param}' parameter. "+ f"Ensure the function has a '{team_id_param}' parameter or "+ f"specify a different parameter name."+ )++ # `bool` is a subclass of `int` — slips past `isinstance(_, int)`+ if isinstance(team_id, bool) or not isinstance(team_id, int):+ raise TypeError(f"with_team_scope: '{team_id_param}' must be an int, got {type(team_id).__name__}")++ with team_scope(team_id, canonical=canonical):+ return func(*args, **kwargs)++ return wrapper++ return decorator+++__all__ = [+ "get_current_team_id",+ "set_current_team_id",+ "reset_current_team_id",+ "team_scope",+ "unscoped",+ "with_team_scope",+]diff --git a/posthog/models/scoping/manager.py b/posthog/models/scoping/manager.pynew file mode 100644index 000000000000..9a60f6f3a70b--- /dev/null+++ b/posthog/models/scoping/manager.py@@ -0,0 +1,134 @@+"""+Team-scoped manager and queryset for tenant isolation.++Fail-closed: raises TeamScopeError when no team context is set, unless+explicitly opted out via .unscoped(). This forces every code path to+declare its team context — there is no silent "return everything" mode.++This is a defense-in-depth convenience layer, not a complete security+boundary. Django's _base_manager bypasses custom managers for related-+object access, and raw SQL bypasses the ORM entirely. Use this alongside+explicit team checks at the API layer.+"""++from typing import TypeVar, cast++from django.db import models++from posthog.models.scoping import get_current_team_id++T = TypeVar("T", bound=models.Model)+++class TeamScopeError(Exception):+ """Raised when a team-scoped model is queried without team context.++ To fix, either:+ - Set team context: TeamAndOrgViewSetMixin sets it for nested DRF views+ from the URL team_id; use team_scope()/with_team_scope() elsewhere+ (Celery tasks, management commands, admin actions).+ - Opt out explicitly: Model.objects.unscoped().all()+ """++ pass+++def resolve_effective_team_id(team_id: int) -> int:+ """Resolve a team_id to its canonical id (parent if child, else self).++ Used by:+ - TeamAndOrgViewSetMixin to compute the canonical id once per request+ - ProductTeamModel.save() to keep writes symmetric with reads+ - Anyone with a raw team_id who needs to set context++ Raises TeamScopeError if the team doesn't exist on the main DB —+ matches the rest of the fail-closed posture (silent fallback would+ let `team_scope(typo)` quietly scope queries to a non-existent team).+ """+ from posthog.models.team import Team++ try:+ team = Team.objects.using("default").only("parent_team_id").get(id=team_id)+ except Team.DoesNotExist:+ raise TeamScopeError(f"Team {team_id} not found on default DB")+ return team.parent_team_id or team_id+++class TeamScopedQuerySet(models.QuerySet[T]):+ """+ QuerySet that supports automatic team scoping.++ Provides an `unscoped()` method to bypass automatic filtering when you+ need to explicitly query across teams.+ """++ def _apply_team_filter(self, team_id: int) -> "TeamScopedQuerySet[T]":+ """Apply team filtering. Caller passes the canonical team_id; we+ trust it and filter directly. No DB resolution at read time —+ ProductTeamModel.save() and the DRF mixin keep the contract that+ team_ids in scope are always canonical (parent or root)."""+ return self.filter(team_id=team_id)++ def unscoped(self) -> "TeamScopedQuerySet[T]":+ """+ Return a queryset that bypasses automatic team scoping.++ Use this when you explicitly need to query across teams:+ FeatureFlag.objects.unscoped().filter(key="my-flag")++ This creates a fresh queryset without any team filtering applied.+ """+ return cast("TeamScopedQuerySet[T]", TeamScopedQuerySet(self.model, using=self._db)) # type: ignore[attr-defined]+++class TeamScopedManager(models.Manager[T]):+ """+ Fail-closed manager that enforces team scoping.++ When team context is set (via TeamAndOrgViewSetMixin or team_scope()),+ queries are automatically filtered. When no context is set, raises+ TeamScopeError.++ Escape hatches:+ - .unscoped() — returns unfiltered queryset (for intentional cross-team access)+ - .for_team(id) — explicitly scope to a team outside request context+ """++ _queryset_class = TeamScopedQuerySet++ def get_queryset(self) -> TeamScopedQuerySet[T]:+ qs: TeamScopedQuerySet[T] = self._queryset_class(self.model, using=self._db)+ team_id = get_current_team_id()+ if team_id is not None:+ return qs._apply_team_filter(team_id)+ raise TeamScopeError(+ f"No team context set for {self.model.__name__}. "+ f"Use team_scope(), @with_team_scope(), or .unscoped() for cross-team access."+ )++ def unscoped(self) -> TeamScopedQuerySet[T]:+ """Return an unscoped queryset that bypasses automatic team filtering."""+ return self._queryset_class(self.model, using=self._db)++ def for_team(self, team_id: int, *, canonical: bool = False) -> TeamScopedQuerySet[T]:+ """Explicitly scope to a team. Useful outside request context.++ Auto-resolves `team_id` to canonical via `resolve_effective_team_id`+ (one Team lookup per call). Bulk callers iterating over many teams+ can pre-resolve once and pass `canonical=True` to skip the per-call+ lookup.++ Pass `canonical=True` only when the caller has independently+ verified the id is canonical (or is using a synthetic id in tests).+ """+ if not canonical:+ team_id = resolve_effective_team_id(team_id)+ return self._queryset_class(self.model, using=self._db)._apply_team_filter(team_id)+++__all__ = [+ "TeamScopeError",+ "TeamScopedQuerySet",+ "TeamScopedManager",+ "resolve_effective_team_id",+]diff --git a/posthog/models/scoping/product_mixin.py b/posthog/models/scoping/product_mixin.pynew file mode 100644index 000000000000..3545e47ff596--- /dev/null+++ b/posthog/models/scoping/product_mixin.py@@ -0,0 +1,77 @@+"""+Abstract model for product models on separate databases.++Multi-DB counterpart of RootTeamMixin. Provides:+- team_id as a plain BigIntegerField (no FK to Team — can't cross databases)+- save() rewrites team_id to canonical (parent if child env, else self) so+ data always lives at the canonical team_id — symmetric with reads+- Auto-scoping fail-closed manager via `TeamScopedManager` (the same+ manager main-DB models use)++Usage:++ from posthog.models.scoping.product_mixin import ProductTeamModel++ class Repo(ProductTeamModel):+ repo_name = models.CharField(max_length=255)++ # In DRF view (mixin sets canonical team context):+ Repo.objects.all() # Auto-filtered to canonical team++ # Explicit cross-team:+ Repo.objects.unscoped().all() # No filtering++ # Background jobs (auto-resolves to canonical):+ with team_scope(team_id):+ Repo.objects.all()+"""++from __future__ import annotations++from typing import Any++from django.db import models++from posthog.models.scoping.manager import TeamScopedManager, resolve_effective_team_id+++class ProductTeamModel(models.Model):+ """Abstract base for product models that live on a separate database.++ Provides team_id as a plain BigIntegerField (no FK constraint) and a+ fail-closed manager that auto-scopes queries by the current team+ context. save() rewrites team_id to the canonical id (parent if the+ team is a child environment, the team's own id otherwise) so writes+ and reads agree on where data lives — same convention as+ RootTeamMixin for main-DB models.++ Two managers:+ - `objects` (TeamScopedManager): fail-closed, auto-scopes by context.+ Raises TeamScopeError when no context is set. This is the manager+ Django admin / Model.objects / `_default_manager` resolves to.+ - `all_teams` (plain Manager): bypass for admin / migrations / contexts+ that genuinely need cross-team access. Named distinctly from the+ queryset method `Model.objects.unscoped()` to avoid the autocomplete+ footgun where `Model.unscoped.filter(...)` looks like "I'm being+ explicit about scoping" but actually returns every team's rows.+ """++ team_id = models.BigIntegerField(db_index=True)++ objects = TeamScopedManager()+ all_teams = models.Manager() # noqa: DJ012 — both are managers, ruff misclassifies this++ class Meta:+ abstract = True++ def save(self, *args: Any, **kwargs: Any) -> None:+ # Rewrite child team_ids to canonical on insert / when team_id is+ # being written. Updates that don't touch team_id skip the lookup —+ # otherwise every status transition / unrelated field update would+ # pay the Team roundtrip. Mirrors RootTeamMixin.save() for main-DB+ # models.+ update_fields = kwargs.get("update_fields")+ team_id_changed = update_fields is None or "team_id" in update_fields+ if (self._state.adding or team_id_changed) and self.team_id is not None:+ self.team_id = resolve_effective_team_id(self.team_id)+ super().save(*args, **kwargs)diff --git a/posthog/models/scoping/test_manager.py b/posthog/models/scoping/test_manager.pynew file mode 100644index 000000000000..8eb0dfd2d6a3--- /dev/null+++ b/posthog/models/scoping/test_manager.py@@ -0,0 +1,147 @@+import pytest+from posthog.test.base import BaseTest++from posthog.models.feature_flag import FeatureFlag+from posthog.models.scoping import team_scope, unscoped+from posthog.models.scoping.manager import TeamScopedManager, TeamScopeError+from posthog.models.team import Team+++class TestTeamScopedManager(BaseTest):+ def _make_manager(self) -> TeamScopedManager[FeatureFlag]:+ manager: TeamScopedManager[FeatureFlag] = TeamScopedManager()+ manager.model = FeatureFlag+ manager._db = "default"+ return manager++ def test_no_scope_raises_team_scope_error(self):+ with pytest.raises(TeamScopeError, match="No team context set"):+ self._make_manager().get_queryset()++ def test_team_scope_filters_to_team(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ FeatureFlag.objects.create(team=self.team, key="flag-1", created_by=self.user)+ FeatureFlag.objects.create(team=other_team, key="flag-2", created_by=self.user)++ with team_scope(self.team.id):+ qs = self._make_manager().get_queryset()+ assert qs.count() == 1+ flag = qs.first()+ assert flag is not None+ assert flag.key == "flag-1"++ def test_unscoped_bypasses_context(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ FeatureFlag.objects.create(team=self.team, key="flag-1", created_by=self.user)+ FeatureFlag.objects.create(team=other_team, key="flag-2", created_by=self.user)++ with team_scope(self.team.id):+ assert self._make_manager().unscoped().count() >= 2++ def test_unscoped_works_without_context(self):+ FeatureFlag.objects.create(team=self.team, key="flag-1", created_by=self.user)+ assert self._make_manager().unscoped().count() >= 1++ def test_for_team_explicit_scoping(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ FeatureFlag.objects.create(team=self.team, key="flag-1", created_by=self.user)+ FeatureFlag.objects.create(team=other_team, key="flag-2", created_by=self.user)++ qs = self._make_manager().for_team(other_team.id)+ assert qs.count() == 1+ flag = qs.first()+ assert flag is not None+ assert flag.key == "flag-2"++ def test_queryset_chaining_preserves_team_filter(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ FeatureFlag.objects.create(team=self.team, key="active-flag", active=True, created_by=self.user)+ FeatureFlag.objects.create(team=self.team, key="inactive-flag", active=False, created_by=self.user)+ FeatureFlag.objects.create(team=other_team, key="other-active", active=True, created_by=self.user)++ with team_scope(self.team.id):+ qs = self._make_manager().get_queryset().filter(active=True)+ assert qs.count() == 1+ flag = qs.first()+ assert flag is not None+ assert flag.key == "active-flag"++ def test_unscoped_context_clears_team(self):+ with team_scope(self.team.id):+ from posthog.models.scoping import get_current_team_id++ assert get_current_team_id() == self.team.id++ with unscoped():+ assert get_current_team_id() is None++ assert get_current_team_id() == self.team.id+++class TestTeamScopedQuerySet(BaseTest):+ def test_queryset_unscoped_returns_fresh_queryset(self):+ from posthog.models.scoping.manager import TeamScopedQuerySet++ qs: TeamScopedQuerySet[FeatureFlag] = TeamScopedQuerySet(FeatureFlag)+ unscoped_qs = qs.unscoped()+ assert isinstance(unscoped_qs, TeamScopedQuerySet)++ def test_apply_team_filter(self):+ from posthog.models.scoping.manager import TeamScopedQuerySet++ other_team = Team.objects.create(organization=self.organization, name="Other Team")++ FeatureFlag.objects.create(team=self.team, key="flag-1", created_by=self.user)+ FeatureFlag.objects.create(team=other_team, key="flag-2", created_by=self.user)++ qs: TeamScopedQuerySet[FeatureFlag] = TeamScopedQuerySet(FeatureFlag)+ filtered_qs = qs._apply_team_filter(self.team.id)++ assert filtered_qs.count() == 1+ flag = filtered_qs.first()+ assert flag is not None+ assert flag.key == "flag-1"+++class TestApplyTeamFilterAgainstRows(BaseTest):+ """Behavioral coverage for _apply_team_filter against real rows.++ Contract: ctx.team_id is the canonical team_id (parent if the team is+ a child env, the team's own id otherwise). The manager just filters by+ it, no resolution at read time. Callers (DRF mixin, save() rewrite, the+ `resolve_effective_team_id` helper) keep that contract.+ """++ def _make_manager(self) -> TeamScopedManager[FeatureFlag]:+ manager: TeamScopedManager[FeatureFlag] = TeamScopedManager()+ manager.model = FeatureFlag+ manager._db = "default"+ return manager++ def test_filters_by_canonical_team_id_in_context(self):+ # Caller puts canonical (parent) id in context — manager just filters.+ parent = Team.objects.create(organization=self.organization, name="Parent")+ child = Team.objects.create(organization=self.organization, name="Child", parent_team=parent)+ FeatureFlag.objects.create(team=parent, key="parent-flag", created_by=self.user)+ # FeatureFlag.save() (RootTeamMixin) rewrites team→parent on save, so child-team+ # writes land at parent. Force a stray child row to verify the filter excludes it.+ child_flag = FeatureFlag.objects.create(team=child, key="child-flag", created_by=self.user)+ FeatureFlag.objects.filter(pk=child_flag.pk).update(team_id=child.id)++ with team_scope(parent.id):+ keys = set(self._make_manager().get_queryset().values_list("key", flat=True))++ assert keys == {"parent-flag"}++ def test_root_team_filters_to_own_rows(self):+ # Root team: canonical id is the team's own id (no parent).+ FeatureFlag.objects.create(team=self.team, key="root-flag", created_by=self.user)++ with team_scope(self.team.id):+ keys = set(self._make_manager().get_queryset().values_list("key", flat=True))++ assert keys == {"root-flag"}diff --git a/posthog/models/scoping/test_product_mixin.py b/posthog/models/scoping/test_product_mixin.pynew file mode 100644index 000000000000..4247651a0efc--- /dev/null+++ b/posthog/models/scoping/test_product_mixin.py@@ -0,0 +1,36 @@+"""Smoke tests for ProductTeamModel wiring.++Manager mechanics (filtering, raise-on-no-context, unscoped, etc.) are+covered exhaustively in test_manager.py against FeatureFlag. After the+ProductTeamManager → TeamScopedManager consolidation those tests apply+unchanged to ProductTeamModel-based models.++Concrete-model integration tests live inside the consuming product+(e.g. visual_review/backend/tests/) where they can import the model+internally without crossing tach product-isolation boundaries.++This file just verifies the abstract base itself is wired up correctly.+"""++from django.db import models+from django.test import SimpleTestCase++from posthog.models.scoping.manager import TeamScopedManager+from posthog.models.scoping.product_mixin import ProductTeamModel+++class TestProductTeamModelWiring(SimpleTestCase):+ def test_objects_is_team_scoped_manager(self) -> None:+ """The default manager is fail-closed by team scope."""+ self.assertIsInstance(ProductTeamModel._meta.managers_map["objects"], TeamScopedManager)++ def test_all_teams_is_plain_manager(self) -> None:+ """The bypass manager is a plain Django Manager (no scope enforcement)."""+ all_teams_manager = ProductTeamModel._meta.managers_map["all_teams"]+ self.assertIsInstance(all_teams_manager, models.Manager)+ self.assertNotIsInstance(all_teams_manager, TeamScopedManager)++ def test_team_id_field_is_bigint(self) -> None:+ """team_id is a plain BigIntegerField (no FK across DBs)."""+ field = ProductTeamModel._meta.get_field("team_id")+ self.assertIsInstance(field, models.BigIntegerField)diff --git a/posthog/models/scoping/test_scoping.py b/posthog/models/scoping/test_scoping.pynew file mode 100644index 000000000000..171550955ab4--- /dev/null+++ b/posthog/models/scoping/test_scoping.py@@ -0,0 +1,226 @@+import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.scoping import (+ get_current_team_id,+ reset_current_team_id,+ set_current_team_id,+ team_scope,+ unscoped,+ with_team_scope,+)+++class TestContextVar(BaseTest):+ def test_default_is_none(self):+ assert get_current_team_id() is None++ def test_set_and_get(self):+ token = set_current_team_id(42)+ try:+ assert get_current_team_id() == 42+ finally:+ reset_current_team_id(token)++ def test_reset_restores_previous_value(self):+ token1 = set_current_team_id(1)+ try:+ token2 = set_current_team_id(2)+ assert get_current_team_id() == 2+ reset_current_team_id(token2)+ assert get_current_team_id() == 1+ finally:+ reset_current_team_id(token1)++ def test_reset_to_none(self):+ token = set_current_team_id(99)+ reset_current_team_id(token)+ assert get_current_team_id() is None+++class TestTeamScopeContextManager(BaseTest):+ @parameterized.expand(+ [+ (1,),+ (42,),+ (999,),+ ]+ )+ def test_sets_team_id(self, team_id: int):+ assert get_current_team_id() is None+ with team_scope(team_id, canonical=True):+ assert get_current_team_id() == team_id+ assert get_current_team_id() is None++ def test_nested_scopes(self):+ with team_scope(1, canonical=True):+ assert get_current_team_id() == 1+ with team_scope(2, canonical=True):+ assert get_current_team_id() == 2+ with team_scope(3, canonical=True):+ assert get_current_team_id() == 3+ assert get_current_team_id() == 2+ assert get_current_team_id() == 1+ assert get_current_team_id() is None++ def test_cleans_up_on_exception(self):+ try:+ with team_scope(123, canonical=True):+ assert get_current_team_id() == 123+ raise ValueError("test exception")+ except ValueError:+ pass+ assert get_current_team_id() is None++ def test_nested_cleanup_on_exception(self):+ with team_scope(1, canonical=True):+ try:+ with team_scope(2, canonical=True):+ raise ValueError("inner exception")+ except ValueError:+ pass+ # Should restore to outer scope+ assert get_current_team_id() == 1+ assert get_current_team_id() is None+++class TestUnscopedContextManager(BaseTest):+ def test_clears_team_id(self):+ with team_scope(42, canonical=True):+ assert get_current_team_id() == 42+ with unscoped():+ assert get_current_team_id() is None+ assert get_current_team_id() == 42++ def test_works_without_existing_scope(self):+ assert get_current_team_id() is None+ with unscoped():+ assert get_current_team_id() is None+ assert get_current_team_id() is None++ def test_nested_unscoped(self):+ with team_scope(1, canonical=True):+ with unscoped():+ assert get_current_team_id() is None+ with team_scope(2, canonical=True):+ assert get_current_team_id() == 2+ assert get_current_team_id() is None+ assert get_current_team_id() == 1++ def test_cleans_up_on_exception(self):+ with team_scope(99, canonical=True):+ try:+ with unscoped():+ assert get_current_team_id() is None+ raise ValueError("test")+ except ValueError:+ pass+ assert get_current_team_id() == 99+++class TestWithTeamScopeDecorator(BaseTest):+ def test_sets_team_id_from_kwarg(self):+ """Decorator extracts team_id from keyword argument."""+ captured_team_id = None++ @with_team_scope(canonical=True)+ def my_task(team_id: int, other: str):+ nonlocal captured_team_id+ captured_team_id = get_current_team_id()++ my_task(team_id=42, other="test")+ assert captured_team_id == 42+ # Context should be cleaned up after function returns+ assert get_current_team_id() is None++ def test_sets_team_id_from_positional_arg(self):+ """Decorator extracts team_id from positional argument."""+ captured_team_id = None++ @with_team_scope(canonical=True)+ def my_task(team_id: int, other: str):+ nonlocal captured_team_id+ captured_team_id = get_current_team_id()++ my_task(42, "test")+ assert captured_team_id == 42++ def test_custom_param_name(self):+ """Decorator supports custom parameter names."""+ captured_team_id = None++ @with_team_scope(canonical=True, team_id_param="project_team_id")+ def my_task(project_team_id: int, other: str):+ nonlocal captured_team_id+ captured_team_id = get_current_team_id()++ my_task(project_team_id=99, other="test")+ assert captured_team_id == 99++ def test_raises_if_param_not_found(self):+ """Decorator raises ValueError if team_id param is missing."""+ import pytest++ @with_team_scope(canonical=True)+ def my_task(other: str):+ pass++ with pytest.raises(ValueError, match="team_id"):+ my_task(other="test")++ def test_cleans_up_on_exception(self):+ """Decorator cleans up context even if function raises."""++ @with_team_scope(canonical=True)+ def my_task(team_id: int):+ raise ValueError("task error")++ try:+ my_task(team_id=42)+ except ValueError:+ pass++ assert get_current_team_id() is None++ def test_preserves_function_metadata(self):+ """Decorator preserves function name and docstring."""++ @with_team_scope(canonical=True)+ def my_documented_task(team_id: int):+ """This is my docstring."""+ pass++ assert my_documented_task.__name__ == "my_documented_task"+ assert my_documented_task.__doc__ == "This is my docstring."++ def test_returns_function_result(self):+ """Decorator returns the function's return value."""++ @with_team_scope(canonical=True)+ def my_task(team_id: int) -> str:+ return f"result for team {team_id}"++ result = my_task(team_id=42)+ assert result == "result for team 42"++ def test_raises_if_team_id_is_not_int(self):+ """Decorator raises TypeError if team_id is not an int."""++ @with_team_scope(canonical=True)+ def my_task(team_id: int):+ pass++ with pytest.raises(TypeError, match="must be an int"):+ my_task(team_id="not-an-int") # type: ignore[arg-type]++ def test_raises_if_team_id_is_none_explicitly(self):+ """Decorator raises ValueError if team_id is None."""++ @with_team_scope(canonical=True)+ def my_task(team_id: int):+ pass++ with pytest.raises(ValueError, match="Could not find"):+ my_task(team_id=None) # type: ignore[arg-type]diff --git a/posthog/scoping_audit.py b/posthog/scoping_audit.pynew file mode 100644index 000000000000..f7720f427844--- /dev/null+++ b/posthog/scoping_audit.py@@ -0,0 +1,48 @@+"""Module-import-safe marker for the celery-task-team-scope-audit semgrep rule.++Lives at the top of the `posthog` package (not under `posthog.models`)+because Celery task modules import this at module load — and importing+from `posthog.models.*` at that point triggers `posthog.models.__init__`+to load every model in the codebase, which fails before Django's app+registry is ready (e.g. during `posthog.apps.py` initialization for+modules pulled in by the celery app config).++The framework's other scoping helpers (TeamScopedManager,+ProductTeamModel, team_scope, etc.) live in `posthog.models.scoping`+because they're inherently model-tied and only get imported once Django+apps are loaded.+"""++from collections.abc import Callable+from typing import ParamSpec, TypeVar++P = ParamSpec("P")+R = TypeVar("R")+++def skip_team_scope_audit(func: Callable[P, R]) -> Callable[P, R]:+ """No-op marker that silences the celery-task-team-scope-audit semgrep rule.++ Apply this to Celery tasks that query models which don't read the+ scoping ContextVar — i.e. anything still on `RootTeamManager` or the+ default Django manager. Those tasks don't need `@with_team_scope`+ because the model's manager isn't fail-closed; the auto-rewrite on+ save (`RootTeamMixin.save()`) handles the canonical-id concern.++ The decorator does nothing at runtime. Its only purpose is to make+ "this task is intentionally exempt" explicit and reviewable, in+ contrast to `# nosemgrep` comments which carry no semantic content.++ Remove it once the underlying model migrates to `TeamScopedManager` —+ after which the task will need `@with_team_scope` or `.unscoped()`.++ Example:+ @shared_task+ @skip_team_scope_audit # FeatureFlag still uses RootTeamManager+ def my_task():+ FeatureFlag.objects.filter(...).delete()+ """+ return func+++__all__ = ["skip_team_scope_audit"]diff --git a/posthog/tasks/activity_log.py b/posthog/tasks/activity_log.pyindex 563fa4ae871a..2e213929a914 100644--- a/posthog/tasks/activity_log.py+++ b/posthog/tasks/activity_log.py@@ -3,11 +3,13 @@ from celery import shared_taskfrom posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_eventfrom posthog.models import Team+from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef broadcast_activity_log_to_organization(organization_id: str, serialized_data: dict, user_data: dict | None) -> None:"""Broadcast an activity log event to all teams that have opted in to receivediff --git a/posthog/tasks/alerts/checks.py b/posthog/tasks/alerts/checks.pyindex 2345f5709ba4..c4802e4a8c40 100644--- a/posthog/tasks/alerts/checks.py+++ b/posthog/tasks/alerts/checks.py@@ -21,6 +21,7 @@ from posthog.models import AlertConfigurationfrom posthog.models.alert import AlertCheckfrom posthog.ph_client import ph_scoped_capturefrom posthog.schema_migrations.upgrade_manager import upgrade_query+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.slo.context import SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.tasks.alerts.detector import check_trends_alert_with_detector@@ -66,6 +67,7 @@ def checks_cleanup_task() -> None:ignore_result=True,expires=60 * 60,)+@skip_team_scope_auditdef alerts_backlog_task() -> None:"""This runs every 5min to check backlog for alerts@@ -118,6 +120,7 @@ def alerts_backlog_task() -> None:ignore_result=True,expires=60 * 60,)+@skip_team_scope_auditdef reset_stuck_alerts_task() -> None:now = datetime.now(UTC)@@ -146,6 +149,7 @@ def reset_stuck_alerts_task() -> None:ignore_result=True,expires=60 * 60,)+@skip_team_scope_auditdef check_alerts_task() -> None:"""This runs every 2min to check for alerts that are due to recalculatediff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex c8d34dde8668..a79bf64d45dc 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -30,6 +30,7 @@ from posthog.models.cohort.util import ()from posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueueCOHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge(@@ -434,6 +435,7 @@ def _enqueue_single_cohort_calculation(cohort: Cohort, initiating_user: Optionalretry_backoff_max=1800,max_retries=6,)+@skip_team_scope_auditdef calculate_cohort_ch(cohort_id: int, pending_version: int, initiating_user_id: Optional[int] = None) -> None:with posthoganalytics.new_context():posthoganalytics.tag("feature", Feature.COHORT.value)@@ -469,6 +471,7 @@ def calculate_cohort_ch(cohort_id: int, pending_version: int, initiating_user_id@shared_task(ignore_result=True, max_retries=1)+@skip_team_scope_auditdef calculate_cohort_from_list(cohort_id: int,items: list[str],@@ -505,6 +508,7 @@ def calculate_cohort_from_list(max_retries=1,queue=CeleryQueue.LONG_RUNNING.value,)+@skip_team_scope_auditdef insert_cohort_from_query(cohort_id: int, team_id: Optional[int] = None) -> None:"""One-time population task for static cohorts created from a HogQL query@@ -581,6 +585,7 @@ def insert_cohort_from_query(cohort_id: int, team_id: Optional[int] = None) -> Nmax_retries=1,queue=CeleryQueue.LONG_RUNNING.value,)+@skip_team_scope_auditdef insert_cohort_from_filters(cohort_id: int, team_id: Optional[int] = None) -> None:"""One-time population task for static cohorts created from saved cohort criteria.@@ -718,6 +723,7 @@ def _collect_cohort_calculation_metrics(history: CohortCalculationHistory, start@shared_task(ignore_result=True, max_retries=3)+@skip_team_scope_auditdef collect_cohort_query_stats(tag_matcher: str, cohort_id: int, start_time_iso: str, history_id: str, query: str) -> None:diff --git a/posthog/tasks/demo_create_data.py b/posthog/tasks/demo_create_data.pyindex 5b97bf9a2478..6f0dbb7ef48e 100644--- a/posthog/tasks/demo_create_data.py+++ b/posthog/tasks/demo_create_data.py@@ -6,9 +6,11 @@ from posthog.demo.matrix import managerfrom posthog.demo.products.hedgebox.matrix import HedgeboxMatrixfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from posthog.scoping_audit import skip_team_scope_audit@shared_task(ignore_result=True)+@skip_team_scope_auditdef create_data_for_demo_team(team_id: int, user_id: int, cache_key: str) -> None:team = Team.objects.get(pk=team_id)user = User.objects.get(pk=user_id)diff --git a/posthog/tasks/early_access_feature.py b/posthog/tasks/early_access_feature.pyindex 82b2b44ef956..efc1f7efa4bf 100644--- a/posthog/tasks/early_access_feature.py+++ b/posthog/tasks/early_access_feature.py@@ -9,6 +9,7 @@ from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContextfrom posthog.hogql.query import execute_hogql_queryfrom posthog.cloud_utils import is_cloud+from posthog.scoping_audit import skip_team_scope_auditfrom products.early_access_features.backend.models import EarlyAccessFeature@@ -28,6 +29,7 @@ def capture_event(event: str, *, distinct_id: str, properties: dict[str, Any]) -# Note: If the task fails and is retried, events may be sent multiple times. This is handled by Customer.io when consuming the events.@shared_task(ignore_result=True, max_retries=3)+@skip_team_scope_auditdef send_events_for_early_access_feature_stage_change(feature_id: str, from_stage: str, to_stage: str) -> None:instance = EarlyAccessFeature.objects.get(id=feature_id)diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 564c53c2607c..6226dc63555e 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -41,6 +41,7 @@ from posthog.models.hog_functions.hog_function import HogFunctionfrom posthog.models.messaging import MessagingRecord, get_email_hashfrom posthog.models.utils import UUIDTfrom posthog.ph_client import get_client+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.user_permissions import UserPermissionsfrom products.conversations.backend.models import Ticket@@ -218,6 +219,7 @@ def should_send_pipeline_error_notification(@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_invite(invite_id: str) -> None:campaign_key: str = f"invite_email_{invite_id}"invite = OrganizationInvite.objects.select_related("created_by", "organization").filter(id=invite_id).first()@@ -331,6 +333,7 @@ def send_invite(invite_id: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_member_join(invitee_uuid: str, organization_id: str) -> None:invitee: User = User.objects.get(uuid=invitee_uuid)organization: Organization = Organization.objects.get(id=organization_id)@@ -385,6 +388,7 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_provisioning_welcome(user_id: int, token: str, partner_name: str = "") -> None:user = User.objects.get(pk=user_id)message = EmailMessage(@@ -405,6 +409,7 @@ def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "")@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_password_reset(user_id: int, token: str) -> None:user = User.objects.get(pk=user_id)message = EmailMessage(@@ -426,6 +431,7 @@ def send_password_reset(user_id: int, token: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_password_changed_email(user_id: int) -> None:user = User.objects.get(pk=user_id)message = EmailMessage(@@ -444,6 +450,7 @@ def send_password_changed_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_email_verification(user_id: int, token: str, next_url: str | None = None) -> None:user: User = User.objects.get(pk=user_id)next_query = f"?next={quote(next_url, safe='')}" if next_url else ""@@ -469,6 +476,7 @@ def send_email_verification(user_id: int, token: str, next_url: str | None = Non@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_email_mfa_link(user_id: int, token: str) -> None:"""Send email MFA verification link"""user: User = User.objects.get(pk=user_id)@@ -603,6 +611,7 @@ def send_batch_export_run_failure(@shared_task(ignore_result=True)+@skip_team_scope_auditdef send_matview_failure_digest() -> None:from products.data_warehouse.backend.models import DataModelingJob, DataWarehouseSavedQuery@@ -670,6 +679,7 @@ def send_matview_failure_digest() -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_team_matview_failure_digest(team_id: int, failed_query_ids: list[str], paused_query_ids: list[str]) -> None:from products.data_warehouse.backend.models import DataModelingJob, DataWarehouseSavedQuery@@ -843,6 +853,7 @@ def send_async_migration_errored_email(migration_key: str, time: str, error: str@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_two_factor_auth_enabled_email(user_id: int) -> None:user: User = User.objects.get(pk=user_id)message = EmailMessage(@@ -860,6 +871,7 @@ def send_two_factor_auth_enabled_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_two_factor_auth_disabled_email(user_id: int) -> None:user: User = User.objects.get(pk=user_id)message = EmailMessage(@@ -877,6 +889,7 @@ def send_two_factor_auth_disabled_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_passkey_added_email(user_id: int) -> None:user: User = User.objects.get(pk=user_id)message = EmailMessage(@@ -894,6 +907,7 @@ def send_passkey_added_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_passkey_removed_email(user_id: int) -> None:user: User = User.objects.get(pk=user_id)message = EmailMessage(@@ -911,6 +925,7 @@ def send_passkey_removed_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_two_factor_auth_backup_code_used_email(user_id: int) -> None:user: User = User.objects.get(pk=user_id)message = EmailMessage(@@ -928,6 +943,7 @@ def send_two_factor_auth_backup_code_used_email(user_id: int) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_two_factor_reset_email(user_id: int, token: str) -> None:"""Send 2FA reset email to user when an admin initiates a reset."""user: User = User.objects.get(pk=user_id)@@ -953,6 +969,7 @@ def send_two_factor_reset_email(user_id: int, token: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef login_from_new_device_notification(user_id: int, login_time: datetime.datetime, short_user_agent: str, ip_address: str, backend_name: str) -> None:@@ -1039,6 +1056,7 @@ def get_users_for_orgs_with_no_ingested_events(@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_error_tracking_issue_assigned(assignment_id: str | uuid.UUID, assigner_id: int) -> None:assignment = error_tracking_api.get_issue_assignment_for_notification(assignment_id=assignment_id)assigner = User.objects.get(pk=assigner_id)@@ -1140,6 +1158,7 @@ def send_discussions_mentioned(comment_id: str, mentioned_user_ids: list[int], s@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_hog_functions_digest_email(digest_data: dict, test_email_override: str | None = None) -> None:if not is_email_available(with_absolute_urls=True):return@@ -1282,6 +1301,7 @@ def send_hog_functions_daily_digest() -> None:@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_team_hog_functions_digest(team_id: int, hog_function_ids: list[str] | None = None) -> None:"""Send daily digest email for a specific team with their failed HogFunctions.@@ -1442,6 +1462,7 @@ def send_team_hog_functions_digest(team_id: int, hog_function_ids: list[str] | N@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_personal_api_key_exposed(user_id: int, personal_api_key_id: str, old_mask_value: str, more_info: str) -> None:if not is_email_available(with_absolute_urls=True):return@@ -1501,6 +1522,7 @@ def send_project_secret_api_key_exposed(team_id: int, mask_value: str, more_info@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_oauth_token_exposed(user_id: int, token_type: str, mask_value: str, more_info: str) -> None:if not is_email_available(with_absolute_urls=True):return@@ -1526,6 +1548,7 @@ def send_oauth_token_exposed(user_id: int, token_type: str, mask_value: str, mor@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_new_ticket_notification(ticket_id: str, team_id: int, first_message_content: str) -> None:if not is_email_available(with_absolute_urls=True):logger.warning("Skipping new ticket notification: email service not available")@@ -1594,6 +1617,7 @@ def send_new_ticket_notification(ticket_id: str, team_id: int, first_message_con@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_conversation_restore_email(email: str, team_id: int, restore_url: str) -> None:"""Send email with restore link to recover conversation tickets on a new device."""if not is_email_available(with_absolute_urls=True):@@ -1624,6 +1648,7 @@ def send_conversation_restore_email(email: str, team_id: int, restore_url: str)@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_project_deleted_email(user_id: int,project_name: str,@@ -1650,6 +1675,7 @@ def send_project_deleted_email(@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_auditdef send_organization_deleted_email(user_id: int,organization_name: str,@@ -1707,6 +1733,7 @@ def send_error_tracking_weekly_digest() -> None:@shared_task(**EMAIL_TASK_KWARGS, rate_limit="10/s")+@skip_team_scope_auditdef send_error_tracking_weekly_digest_for_org(org_id: str) -> None:"""Send one combined weekly error tracking digest email per user in an org"""from posthog.models.organization import Organizationdiff --git a/posthog/tasks/feature_flags.py b/posthog/tasks/feature_flags.pyindex c2d257527da9..6799945553c5 100644--- a/posthog/tasks/feature_flags.py+++ b/posthog/tasks/feature_flags.py@@ -21,6 +21,7 @@ from posthog.models.feature_flag.local_evaluation import (update_flag_caches,)from posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.tasks.utils import CeleryQueue, PushGatewayTask@@ -28,6 +29,7 @@ logger = structlog.get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)+@skip_team_scope_auditdef update_team_flags_cache(team_id: int) -> None:try:team = Team.objects.get(id=team_id)@@ -39,6 +41,7 @@ def update_team_flags_cache(team_id: int) -> None:@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)+@skip_team_scope_auditdef update_team_service_flags_cache(team_id: int) -> None:"""Update the service flags cache for a specific team.@@ -159,6 +162,7 @@ def _set_ranked_team_gauge(gauge: Gauge, rows: list[dict], value_key: str) -> No@shared_task(bind=True, base=PushGatewayTask, ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)+@skip_team_scope_auditdef compute_feature_flag_metrics(self: PushGatewayTask) -> None:"""Compute and push feature flag metrics for Grafana dashboards.diff --git a/posthog/tasks/hog_flows.py b/posthog/tasks/hog_flows.pyindex 6bcc174e07eb..23414efeeccf 100644--- a/posthog/tasks/hog_flows.py+++ b/posthog/tasks/hog_flows.py@@ -7,12 +7,14 @@ from structlog import get_loggerfrom posthog.models.action.action import Actionfrom posthog.plugins.plugin_server_api import reload_hog_flows_on_workers+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuelogger = get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef refresh_affected_hog_flows(team_id: Optional[int] = None, action_id: Optional[int] = None) -> int:from posthog.models.hog_flow.hog_flow import HogFlowdiff --git a/posthog/tasks/hog_functions.py b/posthog/tasks/hog_functions.pyindex 22431a710e69..b784ce44b7c4 100644--- a/posthog/tasks/hog_functions.py+++ b/posthog/tasks/hog_functions.py@@ -10,12 +10,14 @@ from posthog.cdp.filters import compile_filters_bytecodefrom posthog.models.action.action import Actionfrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workersfrom posthog.redis import get_client+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuelogger = get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef refresh_affected_hog_functions(team_id: Optional[int] = None, action_id: Optional[int] = None, cohort_id: Optional[int] = None) -> int:diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.pyindex df3a1980ed2b..37890bc5c08f 100644--- a/posthog/tasks/integrations.py+++ b/posthog/tasks/integrations.py@@ -6,10 +6,12 @@ from posthog.models.integration import (GoogleCloudIntegration,defer_repository_cache_fields,)+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)+@skip_team_scope_auditdef refresh_integrations() -> int:from posthog.models.integration import Integration, OauthIntegration@@ -53,6 +55,7 @@ def refresh_integrations() -> int:@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)+@skip_team_scope_auditdef refresh_integration(id: int) -> int:from posthog.models.integration import Integration, OauthIntegration@@ -75,6 +78,7 @@ def refresh_integration(id: int) -> int:@shared_task(ignore_result=True, queue=CeleryQueue.INTEGRATIONS.value)+@skip_team_scope_auditdef push_vercel_secrets(team_id: int) -> None:from posthog.models.team import Teamdiff --git a/posthog/tasks/remote_config.py b/posthog/tasks/remote_config.pyindex 91208a0d9908..08857a9c00ef 100644--- a/posthog/tasks/remote_config.py+++ b/posthog/tasks/remote_config.py@@ -3,12 +3,14 @@ from celery import shared_taskfrom posthog.models.remote_config import RemoteConfigfrom posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuelogger = structlog.get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef update_team_remote_config(team_id: int) -> None:try:team = Team.objects.get(id=team_id)@@ -25,6 +27,7 @@ def update_team_remote_config(team_id: int) -> None:@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef sync_all_remote_configs() -> None:# Meant to ensure we have all configs in sync in case something faileddiff --git a/posthog/tasks/split_person.py b/posthog/tasks/split_person.pyindex 569019c3cbff..ea122c106e45 100644--- a/posthog/tasks/split_person.py+++ b/posthog/tasks/split_person.py@@ -4,11 +4,13 @@ import structlogfrom celery import shared_taskfrom posthog.models import Person+from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@shared_task(ignore_result=True, max_retries=1)+@skip_team_scope_auditdef split_person(person_id: int,team_id: Union[int, str, None] = None,diff --git a/posthog/tasks/surveys.py b/posthog/tasks/surveys.pyindex 7491904596e2..059a945b3ac8 100644--- a/posthog/tasks/surveys.py+++ b/posthog/tasks/surveys.py@@ -2,6 +2,7 @@ import structlogfrom celery import shared_taskfrom posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuefrom products.surveys.backend.models import surveys_hypercache@@ -10,6 +11,7 @@ logger = structlog.get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef update_team_surveys_cache(team_id: int) -> None:try:team = Team.objects.get(id=team_id)@@ -21,6 +23,7 @@ def update_team_surveys_cache(team_id: int) -> None:@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef sync_all_surveys_cache() -> None:# Meant to ensure we have all flags cache in sync in case something faileddiff --git a/posthog/tasks/sync_billing.py b/posthog/tasks/sync_billing.pyindex cbfd45499eed..4ee30b2dffdf 100644--- a/posthog/tasks/sync_billing.py+++ b/posthog/tasks/sync_billing.py@@ -1,9 +1,11 @@from celery import shared_taskfrom posthog.exceptions_capture import capture_exception+from posthog.scoping_audit import skip_team_scope_audit@shared_task(ignore_result=True, rate_limit="5/s")+@skip_team_scope_auditdef sync_members_to_billing(organization_id: str) -> None:from posthog.models import Organization, OrganizationMembership@@ -21,6 +23,7 @@ def sync_members_to_billing(organization_id: str) -> None:@shared_task(ignore_result=True, rate_limit="5/s")+@skip_team_scope_auditdef sync_from_billing(organization_id: str) -> None:from posthog.cloud_utils import get_cached_instance_licensefrom posthog.models import Organizationdiff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 2c774d3e3ec3..5198f177a3ea 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -26,6 +26,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.metrics import pushed_metrics_registryfrom posthog.ph_client import get_regional_ph_clientfrom posthog.redis import get_client+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.settings import CLICKHOUSE_CLUSTERfrom posthog.tasks.utils import CeleryQueue, PushGatewayTask@@ -62,6 +63,7 @@ def delete_expired_exported_assets() -> None:@shared_task(ignore_result=True, soft_time_limit=300, time_limit=360)+@skip_team_scope_auditdef delete_expired_delegation_invites() -> None:"""Delete delegation invites that have passed their expiry.@@ -111,6 +113,7 @@ def delete_expired_delegation_invites() -> None:@shared_task(ignore_result=True)+@skip_team_scope_auditdef clear_expired_sessions() -> None:from django.contrib.sessions.models import Session@@ -294,6 +297,7 @@ HEARTBEAT_EVENT_TO_INGESTION_LAG_METRIC = {"$heartbeat": "ingestion_api"}@shared_task(ignore_result=True)+@skip_team_scope_auditdef ingestion_lag() -> None:from statshog.defaults.django import statsd@@ -537,6 +541,7 @@ _TASKS_RUN_TERMINAL_STATUSES = ("completed", "failed", "cancelled")@shared_task(ignore_result=True, queue=CeleryQueue.STATS.value)+@skip_team_scope_auditdef capture_task_run_state_metrics() -> None:"""Emit gauges describing the current state of the Tasks product's TaskRun table"""from django.db.models import Count, Min@@ -641,6 +646,7 @@ def update_event_partitions() -> None:@shared_task(ignore_result=True)+@skip_team_scope_auditdef clean_stale_partials() -> None:"""Clean stale (meaning older than 7 days) partial social auth sessions."""from social_django.models import Partial@@ -1150,6 +1156,7 @@ def delete_project_data_and_notify_task(retry_backoff=60,retry_backoff_max=300,)+@skip_team_scope_auditdef delete_organization_data_and_notify_task(team_ids: list[int],organization_id: str,@@ -1224,6 +1231,7 @@ def delete_organization_data_and_notify_task(retry_backoff_max=120,max_retries=3,)+@skip_team_scope_auditdef sync_feature_flag_last_called(self: PushGatewayTask) -> None:"""Sync last_called_at timestamps from ClickHouse $feature_flag_called events to PostgreSQL.@@ -1521,6 +1529,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:@shared_task(ignore_result=True, time_limit=7200)+@skip_team_scope_auditdef refresh_activity_log_fields_cache(flush: bool = False, hours_back: int = 14) -> None:"""Refresh fields cache for large organizations.@@ -1629,6 +1638,7 @@ def refresh_activity_log_fields_cache(flush: bool = False, hours_back: int = 14)@shared_task(ignore_result=True)+@skip_team_scope_auditdef sync_user_product_lists_for_new_team(team_id: int) -> None:"""Sync UserProductList for all users who have access to a new team.diff --git a/posthog/tasks/team_metadata.py b/posthog/tasks/team_metadata.pyindex 8ef4482a3b9e..524ba9f74d72 100644--- a/posthog/tasks/team_metadata.py+++ b/posthog/tasks/team_metadata.py@@ -16,6 +16,7 @@ import structlogfrom celery import shared_taskfrom posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.storage.team_metadata_cache import (cleanup_stale_expiry_tracking,@@ -30,6 +31,7 @@ logger = structlog.get_logger(__name__)@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@skip_team_scope_auditdef update_team_metadata_cache_task(team_id: int) -> None:"""Update the metadata cache for a specific team.diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex ffdc623bc6e8..df9b21ed4672 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -41,6 +41,7 @@ from posthog.models.plugin import PluginConfigfrom posthog.models.property.util import get_property_string_exprfrom posthog.models.team.team import Teamfrom posthog.models.utils import namedtuplefetchall+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.settings import CLICKHOUSE_CLUSTER, INSTANCE_TAGfrom posthog.tasks.report_utils import capture_eventfrom posthog.tasks.utils import CeleryQueue@@ -382,6 +383,7 @@ def get_ph_client(*args: Any, **kwargs: Any) -> PostHogClient:@shared_task(**USAGE_REPORT_TASK_KWARGS, max_retries=3, rate_limit="5/s")+@skip_team_scope_auditdef send_report_to_billing_service(org_id: str, report: dict[str, Any]) -> None:if not settings.EE_AVAILABLE:return@@ -1698,6 +1700,7 @@ def get_teams_with_logs_records_in_period(@shared_task(**USAGE_REPORT_TASK_KWARGS, max_retries=3)+@skip_team_scope_auditdef capture_report(*,organization_id: Optional[str] = None,diff --git a/posthog/tasks/verify_persons_data_in_sync.py b/posthog/tasks/verify_persons_data_in_sync.pyindex 1d375e4ab2f5..d85ad44fe48a 100644--- a/posthog/tasks/verify_persons_data_in_sync.py+++ b/posthog/tasks/verify_persons_data_in_sync.py@@ -11,6 +11,7 @@ from celery import shared_taskfrom posthog.clickhouse.client import sync_executefrom posthog.models.person import Person, PersonDistinctId+from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@@ -43,6 +44,7 @@ HAVING argMax(is_deleted, version) = 0 AND person_id IN (%(person_ids)s)@shared_task(max_retries=1, ignore_result=True)+@skip_team_scope_auditdef verify_persons_data_in_sync(period_start: timedelta = PERIOD_START,period_end: timedelta = PERIOD_END,diff --git a/posthog/tasks/warehouse.py b/posthog/tasks/warehouse.pyindex 9a0c5995d37b..74b55f9840e5 100644--- a/posthog/tasks/warehouse.py+++ b/posthog/tasks/warehouse.py@@ -2,11 +2,13 @@ import structlogfrom celery import shared_taskfrom posthog.ph_client import get_client+from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef validate_data_warehouse_table_columns(team_id: int, table_id: str) -> None:from products.data_warehouse.backend.models import DataWarehouseTablediff --git a/products/README.md b/products/README.mdindex 30295d9c06fa..9940b15cf585 100644--- a/products/README.md+++ b/products/README.md@@ -211,6 +211,20 @@ Locally (`DEBUG=1`), it auto-connects to `posthog_visual_review` on localhost. I1. Add a route in `products/db_routing.yaml` (this repo)2. Ask `#team-infrastructure` to provision the database — they'll handle the cluster, credentials, and connection plumbing+### Team scoping (required)++Every model that stores tenant data **must** have a `team_id` field. This is PostHog's primary tenant isolation boundary — without it, there's no way to enforce that one team can't see another's data.++For product databases, use `ProductTeamModel` as your base class. It provides `team_id` plus a fail-closed manager that raises `TeamScopeError` when queries run without team context. See `posthog/models/scoping/README.md` for the full API.++```python+from posthog.models.scoping.product_mixin import ProductTeamModel++class MyModel(ProductTeamModel):+ name = models.CharField(max_length=255)+ # team_id inherited — BigIntegerField, indexed, no FK+```+### Cross-database constraintsPostgres doesn't support foreign keys across databases. Models on a product database **must not** use `ForeignKey` to models in the main database (Team, User, etc.). Use plain integer fields instead:diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex 651430e48616..abca07603604 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -19,6 +19,7 @@ from posthog.models.comment import Comment as CommentModelfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team import Teamfrom posthog.models.uploaded_media import UploadedMedia+from posthog.scoping_audit import skip_team_scope_auditfrom posthog.storage import object_storagefrom products.conversations.backend.events import capture_ticket_status_changed@@ -92,6 +93,7 @@ def is_duplicate_teams_event(activity_id: str) -> bool:@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef process_supporthog_event(event: dict[str, Any], slack_team_id: str, event_id: str | None = None) -> None:if event_id and _is_duplicate_supporthog_event(event_id):logger.info("supporthog_event_duplicate_skipped", event_id=event_id)@@ -134,6 +136,7 @@ def process_supporthog_event(event: dict[str, Any], slack_team_id: str, event_id@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef post_reply_to_slack(ticket_id: str,team_id: int,@@ -420,6 +423,7 @@ def _read_image_bytes_for_slack_upload(team_id: int, image_url: str) -> bytes |@shared_task(ignore_result=True, max_retries=3, default_retry_delay=10)+@skip_team_scope_auditdef send_email_reply(ticket_id: str,team_id: int,@@ -565,6 +569,7 @@ def send_teams_help(self, activity: dict[str, Any], reply: bool = False) -> None@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef process_teams_event(activity: dict[str, Any], tenant_id: str, activity_id: str = "") -> None:"""Process an inbound Teams Bot Framework activity."""@@ -598,6 +603,7 @@ def process_teams_event(activity: dict[str, Any], tenant_id: str, activity_id: s@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef post_reply_to_teams(ticket_id: str,team_id: int,@@ -783,6 +789,7 @@ def _get_or_create_github_ticket(team: Team, repo: str, issue_number: int, paylo@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef process_github_event(event_type: str,action: str,@@ -961,6 +968,7 @@ def _handle_github_comment_event(team: Team, repo: str, action: str, payload: di@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef post_reply_to_github(ticket_id: str,team_id: int,@@ -1036,6 +1044,7 @@ def post_reply_to_github(@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_auditdef create_github_issue(team_id: int,integration_id: int,diff --git a/products/data_modeling/backend/tasks/cleanup_test_saved_queries.py b/products/data_modeling/backend/tasks/cleanup_test_saved_queries.pyindex ed51b970e31b..f88db9f5044d 100644--- a/products/data_modeling/backend/tasks/cleanup_test_saved_queries.py+++ b/products/data_modeling/backend/tasks/cleanup_test_saved_queries.py@@ -6,6 +6,8 @@ from django.utils import timezonefrom celery import shared_taskfrom structlog import get_logger+from posthog.scoping_audit import skip_team_scope_audit+if TYPE_CHECKING:from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -13,6 +15,7 @@ logger = get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef cleanup_expired_test_saved_queries() -> None:"""Hard-delete test saved queries whose expires_at has passed, along with downstream objects.diff --git a/products/endpoints/backend/tasks.py b/products/endpoints/backend/tasks.pyindex 7915d6a12653..456edf183200 100644--- a/products/endpoints/backend/tasks.py+++ b/products/endpoints/backend/tasks.py@@ -5,6 +5,8 @@ from django.utils import timezonefrom celery import shared_taskfrom structlog import get_logger+from posthog.scoping_audit import skip_team_scope_audit+from products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTALfrom products.endpoints.backend.models import EndpointVersion@@ -14,6 +16,7 @@ STALE_THRESHOLD_DAYS = 30@shared_task(ignore_result=True)+@skip_team_scope_auditdef deactivate_stale_materializations() -> None:"""Deactivate materializations for endpoint versions that haven't been executed in over 30 days.diff --git a/products/mcp_store/backend/tasks/tasks.py b/products/mcp_store/backend/tasks/tasks.pyindex 1f3636329bb3..5c1353197cdf 100644--- a/products/mcp_store/backend/tasks/tasks.py+++ b/products/mcp_store/backend/tasks/tasks.py@@ -1,6 +1,8 @@import structlogfrom celery import shared_task+from posthog.scoping_audit import skip_team_scope_audit+from ..models import MCPServerInstallationfrom ..tools import ToolsFetchError, sync_installation_tools@@ -8,6 +10,7 @@ logger = structlog.get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef sync_installation_tools_task(installation_id: str) -> None:try:installation = MCPServerInstallation.objects.get(id=installation_id)diff --git a/products/notifications/backend/tasks/tasks.py b/products/notifications/backend/tasks/tasks.pyindex 999c0a67951d..898859ba0a3c 100644--- a/products/notifications/backend/tasks/tasks.py+++ b/products/notifications/backend/tasks/tasks.py@@ -5,12 +5,15 @@ from django.utils import timezoneimport structlogfrom celery import shared_task+from posthog.scoping_audit import skip_team_scope_audit+from products.notifications.backend.models import NotificationEventlogger = structlog.get_logger(__name__)@shared_task(ignore_result=True)+@skip_team_scope_auditdef cleanup_old_notifications() -> None:cutoff = timezone.now() - timedelta(days=90)batch_size = 10000diff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.pyindex 1fa393de40cb..cfb24f28c2aa 100644--- a/products/visual_review/backend/diffing.py+++ b/products/visual_review/backend/diffing.py@@ -185,14 +185,17 @@ def _diff_snapshot(snapshot: RunSnapshot) -> None:ssim_score=result.ssim_score,)- # Auto-populate tolerance cache so future runs skip diffing for this hash+ # Auto-populate tolerance cache so future runs skip diffing for this hash.+ # Explicit team_id in the lookup (not just defaults) so the IDOR audit+ # rule sees the scope; ProductTeamManager also auto-filters by canonical+ # team — both belt and suspenders.ToleratedHash.objects.get_or_create(+ team_id=snapshot.team_id,repo_id=snapshot.run.repo_id,identifier=snapshot.identifier,baseline_hash=snapshot.baseline_hash,alternate_hash=snapshot.current_hash,defaults={- "team_id": snapshot.team_id,"reason": ToleratedReason.AUTO_THRESHOLD,"source_run": snapshot.run,"diff_percentage": result.diff_percentage,diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex 92a64ff2630f..3e92007e9f5b 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -864,7 +864,7 @@ def complete_run(run_id: UUID) -> Run:mark_run_processing(run_id)from .tasks.tasks import process_run_diffs- process_run_diffs.delay(str(run_id))+ process_run_diffs.delay(run.team_id, str(run_id))return get_run(run_id)@@ -2256,13 +2256,16 @@ def mark_snapshot_as_tolerated(run_id: UUID, snapshot_id: UUID, user_id: int, teif not snapshot.current_hash:raise ValueError("Snapshot has no current hash")+ # Explicit team_id in the lookup (not just defaults) so the IDOR audit+ # rule sees the scope; ProductTeamManager also auto-filters by canonical+ # team — both belt and suspenders.tolerated, _ = ToleratedHash.objects.get_or_create(+ team_id=team_id,repo_id=run.repo_id,identifier=snapshot.identifier,baseline_hash=snapshot.baseline_hash,alternate_hash=snapshot.current_hash,defaults={- "team_id": team_id,"reason": ToleratedReason.HUMAN,"source_run": run,"created_by_id": user_id,diff --git a/products/visual_review/backend/management/commands/seed_dummy_runs.py b/products/visual_review/backend/management/commands/seed_dummy_runs.pyindex c419b0032fd8..674047018399 100644--- a/products/visual_review/backend/management/commands/seed_dummy_runs.py+++ b/products/visual_review/backend/management/commands/seed_dummy_runs.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom blake3 import blake3+from posthog.models.scoping import team_scopefrom posthog.models.team import Teamfrom products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResult@@ -57,6 +58,10 @@ class Command(BaseCommand):self.stderr.write(f"Team {team_id} not found")return+ with team_scope(team_id):+ self._seed(team, num_runs, snapshots_per_run, repo_name)++ def _seed(self, team, num_runs, snapshots_per_run, repo_name):# Get or create reporepo, created = Repo.objects.get_or_create(team_id=team.id,diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.pyindex ec2edd465503..ad17e0f820bc 100644--- a/products/visual_review/backend/models.py+++ b/products/visual_review/backend/models.py@@ -6,6 +6,8 @@ import uuidfrom django.db import models+from posthog.models.scoping.product_mixin import ProductTeamModel+from .facade.enums import (ActorType,ClassificationReason,@@ -19,7 +21,7 @@ from .facade.enums import ()-class Repo(models.Model):+class Repo(ProductTeamModel):"""A visual review repo tied to a GitHub repository.@@ -28,9 +30,6 @@ class Repo(models.Model):"""id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)- # References posthog.Team in the main database — no FK constraint because- # this model lives in a separate product database.- team_id = models.BigIntegerField(db_index=True)# GitHub identity: numeric ID is stable, full_name is for API calls + displayrepo_external_id = models.BigIntegerField()@@ -79,7 +78,7 @@ class Repo(models.Model):return kid, secret_hex-class Artifact(models.Model):+class Artifact(ProductTeamModel):"""Content-addressed image storage.@@ -88,8 +87,6 @@ class Artifact(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)repo = models.ForeignKey(Repo, on_delete=models.CASCADE, related_name="artifacts")- # Denormalized from repo.team_id for direct team scoping.- team_id = models.BigIntegerField(db_index=True)content_hash = models.CharField(max_length=128, db_index=True)storage_path = models.CharField(max_length=1024)@@ -111,7 +108,7 @@ class Artifact(models.Model):return f"{self.content_hash[:12]}..."-class Run(models.Model):+class Run(ProductTeamModel):"""A visual test run from CI.@@ -120,8 +117,6 @@ class Run(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)repo = models.ForeignKey(Repo, on_delete=models.CASCADE, related_name="runs")- # Denormalized from repo.team_id for direct team scoping.- team_id = models.BigIntegerField(db_index=True)status = models.CharField(max_length=20, choices=[(s.value, s.value) for s in RunStatus], default=RunStatus.PENDING)run_type = models.CharField(max_length=64, default=RunType.OTHER)@@ -185,7 +180,7 @@ class Run(models.Model):return f"Run {self.id} ({self.status})"-class RunSnapshot(models.Model):+class RunSnapshot(ProductTeamModel):"""A single snapshot within a run.@@ -194,8 +189,6 @@ class RunSnapshot(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name="snapshots")- # Denormalized from run.team_id for direct team scoping.- team_id = models.BigIntegerField(db_index=True)identifier = models.CharField(max_length=512)@@ -300,7 +293,7 @@ class RunSnapshot(models.Model):return f"{self.identifier} ({self.result})"-class ToleratedHash(models.Model):+class ToleratedHash(ProductTeamModel):"""Previously seen alternate hashes that were determined acceptable for aspecific baseline and snapshot identifier, allowing future runs to skip@@ -313,7 +306,6 @@ class ToleratedHash(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)repo = models.ForeignKey(Repo, on_delete=models.CASCADE, related_name="tolerated_hashes")- team_id = models.BigIntegerField(db_index=True)identifier = models.CharField(max_length=512)baseline_hash = models.CharField(max_length=128)@@ -348,7 +340,7 @@ class ToleratedHash(models.Model):return f"{self.identifier} {self.alternate_hash[:12]}... ({self.reason})"-class QuarantinedIdentifier(models.Model):+class QuarantinedIdentifier(ProductTeamModel):"""Tracks quarantine events for snapshot identifiers.@@ -365,7 +357,6 @@ class QuarantinedIdentifier(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)repo = models.ForeignKey(Repo, on_delete=models.CASCADE, related_name="quarantined_identifiers")- team_id = models.BigIntegerField(db_index=True)identifier = models.CharField(max_length=512)run_type = models.CharField(max_length=64)diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex 627b8ed5068c..8157e59b068e 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -13,6 +13,8 @@ from uuid import UUIDimport structlogfrom celery import shared_task+from posthog.models.scoping import with_team_scope+from ..logic import HashIntegrityErrorlogger = structlog.get_logger(__name__)@@ -26,7 +28,8 @@ logger = structlog.get_logger(__name__)reject_on_worker_lost=True,max_retries=3,)-def process_run_diffs(self, run_id: str) -> None:+@with_team_scope()+def process_run_diffs(self, team_id: int, run_id: str) -> None:"""Verify uploads, create artifacts, and process diffs for a run.@@ -42,11 +45,11 @@ def process_run_diffs(self, run_id: str) -> None:run_uuid = UUID(run_id)try:- logger.info("visual_review.diff_processing_started", run_id=run_id)+ logger.info("visual_review.diff_processing_started", run_id=run_id, team_id=team_id)logic.verify_uploads_and_create_artifacts(run_uuid)process_diffs(run_uuid)logic.finish_processing(run_uuid)- logger.info("visual_review.diff_processing_completed", run_id=run_id)+ logger.info("visual_review.diff_processing_completed", run_id=run_id, team_id=team_id)except HashIntegrityError as e:logger.warning("visual_review.hash_integrity_failed", run_id=run_id, error=str(e))logic.finish_processing(run_uuid, error_message=str(e))@@ -63,6 +66,6 @@ def process_run_diffs(self, run_id: str) -> None:except self.MaxRetriesExceededError:logic.finish_processing(run_uuid, error_message="GitHub API rate limit exceeded after retries")except Exception as e:- logger.exception("visual_review.diff_processing_failed", run_id=run_id, error=str(e))+ logger.exception("visual_review.diff_processing_failed", run_id=run_id, team_id=team_id, error=str(e))logic.finish_processing(run_uuid, error_message=str(e))raisediff --git a/products/visual_review/backend/tests/conftest.py b/products/visual_review/backend/tests/conftest.pyindex 208c0d697243..ec5c7daccba4 100644--- a/products/visual_review/backend/tests/conftest.py+++ b/products/visual_review/backend/tests/conftest.py@@ -10,6 +10,7 @@ import jsonimport base64import hashlibimport subprocess+from contextlib import AbstractContextManagerfrom pathlib import Pathimport pytest@@ -17,11 +18,77 @@ from unittest.mock import MagicMockimport responses+from posthog.models.scoping import team_scope+from products.visual_review.backend.models import RepoPRODUCT_DATABASES = {"default", "visual_review_db_writer", "visual_review_db_reader"}[email protected](autouse=True)+def _set_team_scope(request):+ """Set team context for raw pytest tests that use the database.++ ProductTeamModel is fail-closed — queries without context raise+ TeamScopeError. Only activates for tests marked with @pytest.mark.django_db.++ TestCase / APIBaseTest subclasses are skipped here even when the+ marker is present, because they create their own team in setUp()+ and `getfixturevalue("team")` would duplicate-create with the same+ api_token (collision on `posthog_team_api_token_a9a1df8a_uniq`).+ Those tests use VisualReviewTeamScopedTestMixin (below) which+ wraps setUp/tearDown with team_scope using the test's own+ self.team — no extra team creation.+ """+ if request.node.get_closest_marker("django_db") is None:+ yield+ return++ is_django_testcase = request.cls is not None and any(cls.__name__ == "TestCase" for cls in request.cls.__mro__)+ if is_django_testcase:+ yield+ return++ team = request.getfixturevalue("team")+ with team_scope(team.id):+ yield+++class VisualReviewTeamScopedTestMixin:+ """Mixin for TestCase / APIBaseTest tests that use ProductTeamModel.++ Wraps setUp/tearDown with team_scope so the test body's queries to+ Repo, Run, RunSnapshot etc. find a scope. Place this BEFORE+ APIBaseTest in the MRO so its setUp runs first (creating self.team)+ and our setUp can use it:++ class TestFoo(VisualReviewTeamScopedTestMixin, APIBaseTest):+ def test_thing(self):+ Repo.objects.create(...) # auto-scoped++ The `_team_scope_cm` attribute is initialized to None up front so a+ partial-init failure in setUp (e.g. team_scope() raising during+ resolve, or super().setUp() raising) doesn't leave tearDown trying+ to __exit__ an unentered context manager.+ """++ _team_scope_cm: AbstractContextManager[None] | None = None++ def setUp(self) -> None:+ super().setUp() # type: ignore[misc]+ cm = team_scope(self.team.id) # type: ignore[attr-defined]+ cm.__enter__()+ self._team_scope_cm = cm++ def tearDown(self) -> None:+ if self._team_scope_cm is not None:+ try:+ self._team_scope_cm.__exit__(None, None, None)+ finally:+ self._team_scope_cm = None+ super().tearDown() # type: ignore[misc]++# --- Local Git Repo Fixtures ---diff --git a/products/visual_review/backend/tests/test_api.py b/products/visual_review/backend/tests/test_api.pyindex d0a66d2ed0c0..b8db321634f9 100644--- a/products/visual_review/backend/tests/test_api.py+++ b/products/visual_review/backend/tests/test_api.py@@ -225,7 +225,7 @@ class TestRunAPI:result = api.complete_run(create_result.run_id)assert result.status == "processing"- mock_delay.assert_called_once_with(str(create_result.run_id))+ mock_delay.assert_called_once_with(repo.team_id, str(create_result.run_id))@pytest.mark.django_db(databases=PRODUCT_DATABASES)diff --git a/products/visual_review/backend/tests/test_baselines.py b/products/visual_review/backend/tests/test_baselines.pyindex 239ae592090d..9854c307bc22 100644--- a/products/visual_review/backend/tests/test_baselines.py+++ b/products/visual_review/backend/tests/test_baselines.py@@ -22,7 +22,7 @@ from products.visual_review.backend.facade import api as vr_apifrom products.visual_review.backend.facade.contracts import BASELINE_OVERVIEW_MAX_ENTRIESfrom products.visual_review.backend.facade.enums import RunStatus, RunType, SnapshotResult, ToleratedReasonfrom products.visual_review.backend.models import Artifact, QuarantinedIdentifier, Repo, Run, RunSnapshot, ToleratedHash-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixindef _mk_artifact(repo: Repo, content_hash: str, *, with_thumbnail: str | None = None) -> Artifact:@@ -103,7 +103,7 @@ def _mk_snapshot(return snap-class TestBaselinesOverview(APIBaseTest):+class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):databases = PRODUCT_DATABASESdef setUp(self):diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.pyindex 814b9df57416..4d69c4cdb7fe 100644--- a/products/visual_review/backend/tests/test_presentation.py+++ b/products/visual_review/backend/tests/test_presentation.py@@ -13,10 +13,10 @@ from products.visual_review.backend.facade import apifrom products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItemfrom products.visual_review.backend.facade.enums import RunStatus, RunType, SnapshotResultfrom products.visual_review.backend.models import Run, RunSnapshot-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin-class TestRepoViewSet(APIBaseTest):+class TestRepoViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):databases = PRODUCT_DATABASESdef test_create_repo(self):@@ -59,7 +59,7 @@ class TestRepoViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)-class TestRunViewSet(APIBaseTest):+class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):databases = PRODUCT_DATABASESdef setUp(self):diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.pyindex 9b4ece0c075b..0278cdfdcd41 100644--- a/products/visual_review/backend/tests/test_tasks.py+++ b/products/visual_review/backend/tests/test_tasks.py@@ -32,7 +32,7 @@ class TestProcessRunDiffs:)# Process (should complete immediately since no changed snapshots need diffing)- process_run_diffs(str(create_result.run_id))+ process_run_diffs(repo.team_id, str(create_result.run_id))# Check run is completedrun = api.get_run(create_result.run_id)@@ -55,7 +55,7 @@ class TestProcessRunDiffs:mock.side_effect = Exception("Something went wrong")with pytest.raises(Exception):- process_run_diffs(str(create_result.run_id))+ process_run_diffs(repo.team_id, str(create_result.run_id))# Check run is marked as failedrun = api.get_run(create_result.run_id)diff --git a/products/visual_review/backend/tests/test_thumbnails.py b/products/visual_review/backend/tests/test_thumbnails.pyindex 6167ca1b0c50..5f0c489cd859 100644--- a/products/visual_review/backend/tests/test_thumbnails.py+++ b/products/visual_review/backend/tests/test_thumbnails.py@@ -10,7 +10,7 @@ from products.visual_review.backend.diff import THUMB_HEIGHT, THUMB_WIDTH, Compafrom products.visual_review.backend.diffing import _store_thumbnailfrom products.visual_review.backend.facade.enums import RunType, SnapshotResultfrom products.visual_review.backend.models import Artifact, Repo, Run, RunSnapshot-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixindef _make_png(width: int = 800, height: int = 600, color: tuple[int, ...] = (200, 100, 50, 255)) -> bytes:@@ -153,7 +153,7 @@ class TestStoreThumbnail:@pytest.mark.django_db(databases=list(PRODUCT_DATABASES))-class TestThumbnailEndpoint(APIBaseTest):+class TestThumbnailEndpoint(VisualReviewTeamScopedTestMixin, APIBaseTest):databases = PRODUCT_DATABASESTHUMB_HASH = "thumb_hash_abc"IDENTIFIER = "button--primary"