: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(scoping): enforce fail-closed team scoping for new models (#57934)
Julian Bezd4c829c442c8
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex be76c16cdc3e..916f4450843d 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -1,29 +1,40 @@#!/usr/bin/env python3# ruff: noqa: T201 allow print statements"""-CI script to verify all Django models with team/org/user FKs-are listed in the semgrep IDOR rule regex patterns.+CI script that checks two related concerns:++1. IDOR semgrep coverage: every Django model with a team/org/user FK+ appears in the semgrep IDOR rule regex patterns.+2. Fail-closed manager coverage: every team-scoped model uses+ `TeamScopedManager` (directly or via a base class). New models that+ don't are checked against `posthog/models/scoping/baseline_unmigrated.txt`+ — additions fail CI, removals are reported as opportunities to+ shrink the baseline.Usage:- python scripts/check_idor_model_coverage.py+ python check-idor-model-coverage.py+ python check-idor-model-coverage.py --regenerate-baselineExit codes:- 0 - All models covered- 1 - Missing models found (ERROR)+ 0 - All checks pass+ 1 - Missing models, new fail-closed gaps, or other errors"""import osimport reimport sys+import argparsefrom pathlib import Pathimport yaml+REPO_ROOT = Path(__file__).resolve().parent.parent.parent+BASELINE_FILE = REPO_ROOT / "posthog/models/scoping/baseline_unmigrated.txt"+def setup_django() -> None:"""Initialize Django settings for model introspection."""- repo_root = str(Path(__file__).resolve().parent.parent.parent)- sys.path.insert(0, repo_root)+ sys.path.insert(0, str(REPO_ROOT))os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")import django@@ -348,7 +359,13 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[stif not isinstance(field, ForeignKey):continue- related_model_name = field.related_model.__name__+ # ForeignKey.related_model can be the string "self" for+ # self-referencing relations; we only care about Team / Organization+ # / User FKs, so treat self-references as a non-match and skip.+ related_model = field.related_model+ if isinstance(related_model, str):+ continue+ related_model_name = related_model.__name__if related_model_name == "Team":has_team_fk = True@@ -456,14 +473,150 @@ def parse_semgrep_models(yaml_path: Path) -> dict[str, set[str]]:return result+def compute_unmigrated_to_fail_closed(+ team_scoped: set[str],+ excluded: set[str],+ legitimately_unscoped: set[str],+ needs_team_id: set[str],+) -> set[str]:+ """Models that are team-scoped but still on a non-fail-closed manager.++ Derived from the same model registry the IDOR check uses. The baseline+ is the algebraic result of:++ team_scoped+ - excluded # already off the IDOR coverage hook+ # (through tables, accessed-via-parent FK, etc.)+ # — same reasons exempt them from fail-closed+ - legitimately_unscoped # no team_id by design+ - needs_team_id # no team_id yet (future opt-in)+ - models on TeamScopedManager (introspected, not listed)+ = unmigrated baseline++ Introspection means migrating a model is enough to drop it from the+ set — there's no parallel list to keep in sync.+ """+ from django.apps import apps++ from posthog.models.scoping.manager import TeamScopedManager++ fail_closed: set[str] = set()+ for model in apps.get_models():+ if model._meta.proxy:+ continue+ # Look up the manager that `Model.objects.X` resolves to.+ # Reviewers (codex, copilot) flagged a `any(...)` scan as bypassable:+ # a new model could keep `objects = RootTeamManager()` and add a+ # secondary scoped manager just to satisfy CI — call sites would+ # still be unscoped. Anchoring on `objects` (the manager app code+ # actually reaches for) closes that loophole. This stays correct+ # after PR #57879 sets `default_manager_name = "all_teams"` on+ # ProductTeamModel, since that change moves the *framework*-default+ # manager (`_default_manager`, used by admin / related queries)+ # without touching `objects`.+ objects_manager = model._meta.managers_map.get("objects")+ if isinstance(objects_manager, TeamScopedManager):+ fail_closed.add(model.__name__)++ candidates = team_scoped - excluded - legitimately_unscoped - needs_team_id+ return candidates - fail_closed+++def read_baseline() -> set[str]:+ if not BASELINE_FILE.exists():+ return set()+ return {+ line.strip() for line in BASELINE_FILE.read_text().splitlines() if line.strip() and not line.startswith("#")+ }+++def write_baseline(unmigrated: set[str]) -> None:+ header = (+ "# Models that are team-scoped but still on a non-fail-closed manager.\n"+ "#\n"+ "# DO NOT EDIT BY HAND. This file is the mechanical output of\n"+ "# `--regenerate-baseline` — adding entries by hand defeats the algebra and\n"+ "# turns this back into a hand-curated allowlist (the IDOR-list problem).\n"+ "#\n"+ "# Auto-generated by .github/scripts/check-idor-model-coverage.py\n"+ "# Regenerate with: python .github/scripts/check-idor-model-coverage.py --regenerate-baseline\n"+ "#\n"+ "# Adopting fail-closed: change the model's base from RootTeamMixin to\n"+ "# TeamScopedRootMixin (main DB) or ProductTeamModel (separate DB), then\n"+ "# audit every call site to either be inside team scope or use .unscoped().\n"+ "# Once that's done, regenerate this file and the model drops out.\n"+ )+ body = "\n".join(sorted(unmigrated)) + ("\n" if unmigrated else "")+ BASELINE_FILE.write_text(header + body)+++def check_fail_closed_baseline(+ team_scoped: set[str],+ excluded: set[str],+ legitimately_unscoped: set[str],+ needs_team_id: set[str],+ *,+ regenerate: bool,+) -> tuple[bool, bool]:+ """Return (has_errors, has_warnings) for the fail-closed baseline check."""+ current = compute_unmigrated_to_fail_closed(team_scoped, excluded, legitimately_unscoped, needs_team_id)++ print(f"\n{'=' * 60}")+ print("Fail-closed manager baseline check")+ print("=" * 60)++ if regenerate:+ write_baseline(current)+ print(f"\n Regenerated {BASELINE_FILE.relative_to(REPO_ROOT)}")+ print(f" {len(current)} models still on a non-fail-closed manager.")+ return False, False++ baseline = read_baseline()+ new_violations = current - baseline+ migrated = baseline - current++ print(f"\n Baseline: {len(baseline)} models")+ print(f" Current: {len(current)} models")++ if new_violations:+ sorted_violations = sorted(new_violations)+ models_list = ", ".join(sorted_violations)+ print(f"::error::New team-scoped models without TeamScopedManager: {models_list}")+ print(f"\n ❌ ERROR: {len(new_violations)} new model(s) with team_id but not fail-closed:")+ for model in sorted_violations:+ print(f" - {model}")+ print("\n New main-DB models should inherit TeamScopedRootMixin.")+ print(" New separate-DB models should inherit ProductTeamModel.")+ print(" See posthog/models/scoping/README.md for the contract.")+ return True, False++ if migrated:+ print(f"\n ✅ {len(migrated)} model(s) migrated since baseline (regenerate to shrink):")+ for model in sorted(migrated):+ print(f" - {model}")+ print(f"\n Run: python {Path(__file__).relative_to(REPO_ROOT)} --regenerate-baseline")+ return False, True++ print(" ✅ Fail-closed baseline matches.")+ return False, False++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--regenerate-baseline",+ action="store_true",+ help="Rewrite the fail-closed baseline file from the current code state.",+ )+ args = parser.parse_args()+setup_django()# Get models from codecode_models, excluded_models, legitimately_unscoped, needs_team_id = get_scoped_models()# Get models from semgrep rules- semgrep_path = Path(__file__).parent.parent.parent / ".semgrep/rules/idor-team-scoped-models.yaml"+ semgrep_path = REPO_ROOT / ".semgrep/rules/idor-team-scoped-models.yaml"semgrep_models = parse_semgrep_models(semgrep_path)# Compare and report@@ -551,20 +704,34 @@ def main() -> int:if not unacknowledged and not baseline_in_code:print(" ✅ No unacknowledged unscoped models")+ fail_closed_errors, fail_closed_warnings = check_fail_closed_baseline(+ code_models["team_scoped"],+ excluded_models,+ legitimately_unscoped,+ needs_team_id,+ regenerate=args.regenerate_baseline,+ )+ has_errors = has_errors or fail_closed_errors+ has_warnings = has_warnings or fail_closed_warnings+print("\n" + "=" * 60)if has_errors:print("\n❌ FAILED: Some models need attention.")- print("\nTo fix:")+ print("\nTo fix IDOR semgrep gaps:")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")+ print("To fix fail-closed manager gaps:")+ print(" 4. New main-DB models: inherit TeamScopedRootMixin")+ print(" 5. New separate-DB models: inherit ProductTeamModel")+ print(" See posthog/models/scoping/README.md for the contract.")return 1if has_warnings:- print("\n⚠️ PASSED with warnings: Some models in semgrep may be stale.")+ print("\n⚠️ PASSED with warnings.")- print("\n✅ All scoped models are covered by semgrep IDOR rules.")+ print("\n✅ All checks passed.")return 0diff --git a/.github/scripts/compare-ci-runners.py b/.github/scripts/compare-ci-runners.pyindex 517195acd7be..50c89d90c173 100755--- a/.github/scripts/compare-ci-runners.py+++ b/.github/scripts/compare-ci-runners.py@@ -471,19 +471,23 @@ def main() -> None:bs = [p[1] for p in s["success_pairs"]]dm = statistics.median(depot)bm = statistics.median(bs)- speedup = dm / bm if bm > 0 else float("inf")+ # Renamed from `speedup` to avoid shadowing the str-typed `speedup` used+ # in the CSV loop above — mypy unifies the type of repeated names in+ # the same function scope and rejects the float here as `Any | float`+ # vs `str`.+ speedup_factor = dm / bm if bm > 0 else float("inf")dp95 = sorted(depot)[max(0, int(len(depot) * 0.95) - 1)]bp95 = sorted(bs)[max(0, int(len(bs) * 0.95) - 1)]dfail = f"{s['depot_fail']}/{s['depot_total']}"bfail = f"{s['bs_fail']}/{s['bs_total']}"summary_rows.append(- (speedup, wf, base, len(s["success_pairs"]), dm, bm, dp95, bp95, dfail, bfail, s["mixed_pairs"])+ (speedup_factor, wf, base, len(s["success_pairs"]), dm, bm, dp95, bp95, dfail, bfail, s["mixed_pairs"]))# Sort by speedup descending — biggest wins at the top- for speedup, wf, base, n, dm, bm, dp95, bp95, dfail, bfail, mixed in sorted(summary_rows, reverse=True):+ for speedup_factor, wf, base, n, dm, bm, dp95, bp95, dfail, bfail, mixed in sorted(summary_rows, reverse=True):print(- f"| `{wf}` | {base} | {n} | {dm:.0f}s | {bm:.0f}s | **{speedup:.2f}x** | "+ f"| `{wf}` | {base} | {n} | {dm:.0f}s | {bm:.0f}s | **{speedup_factor:.2f}x** | "f"{dp95:.0f}s | {bp95:.0f}s | {dfail} | {bfail} | {mixed} |")diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex 11e93b4b6c5e..85481c19aa4e 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -27,7 +27,7 @@ def _testcase(duration: float = 1.0,start: datetime | None = None,name: str = "t",-) -> report_test_timings.TestCase:+) -> report_test_timings.TestCase: # type: ignore[name-defined]test_start = start if start is not None else datetime(2026, 5, 4, 10, 0, 0, tzinfo=UTC)return report_test_timings.TestCase(nodeid=f"m::{name}",diff --git a/AGENTS.md b/AGENTS.mdindex e9e26d7c8538..295212664df8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -104,7 +104,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)-- **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"]()`+- **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. New models should inherit from `TeamScopedRootMixin` (main DB) or `ProductTeamModel` (separate DB) so they start fail-closed — see `posthog/models/scoping/README.md`. CI enforces this via `posthog/models/scoping/baseline_unmigrated.txt`: any new team-scoped model not on a fail-closed manager fails the IDOR coverage check. 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/posthog/models/scoping/README.md b/posthog/models/scoping/README.mdindex bf9a0b6b7fa0..de13bf3e3147 100644--- a/posthog/models/scoping/README.md+++ b/posthog/models/scoping/README.md@@ -56,6 +56,20 @@ def my_task(team_id: int):## Adoption+### New main-DB model++Use `TeamScopedRootMixin` as the abstract base. It bundles `RootTeamMixin` (canonical-team save() rewrite) with `objects = TeamScopedManager()`. Subclasses still declare their own `team` FK so cascade behavior stays per-model.++```python+from posthog.models.scoping.root_mixin import TeamScopedRootMixin++class Campaign(TeamScopedRootMixin):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ name = models.CharField(max_length=255)+```++`hogli product:bootstrap` scaffolds new products with the correct fail-closed base automatically — `ProductTeamModel` for separate-DB products, `TeamScopedRootMixin` for main-DB products. CI enforces it: any new team-scoped model on a non-fail-closed manager (i.e., not in `posthog/models/scoping/baseline_unmigrated.txt`) fails `check-idor-model-coverage.py`.+### New product on a separate databaseUse `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.@@ -68,16 +82,22 @@ class Repo(ProductTeamModel):# team_id inherited — BigIntegerField, indexed, no FK```-### Existing main-DB model+### Migrating an existing main-DB model-Keep your `RootTeamMixin` (it already declares `team` as `ForeignKey("Team", ...)` and rewrites on save). Swap the manager:+Existing models on plain `RootTeamMixin` are tracked in `baseline_unmigrated.txt`. To migrate one:```python-class FeatureFlag(RootTeamMixin): # unchanged — handles save() + FK- objects = TeamScopedManager() # was RootTeamManager() — adds enforcement+class FeatureFlag(TeamScopedRootMixin): # was RootTeamMixin — adds enforcement+ team = models.ForeignKey("posthog.Team", ...)+```++Then audit every call site to either be inside team scope or use `.unscoped()`, and regenerate the baseline:++```bash+python .github/scripts/check-idor-model-coverage.py --regenerate-baseline```-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()`.+The migrated model drops out of `baseline_unmigrated.txt` automatically (introspection sees the new manager). The manager class is the same for both worlds — `TeamScopedRootMixin`, `ProductTeamModel`, and ad-hoc `objects = TeamScopedManager()` declarations all read the same ContextVar.### Celery tasks against models still on RootTeamManagerdiff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txtnew file mode 100644index 000000000000..12f72d2fc589--- /dev/null+++ b/posthog/models/scoping/baseline_unmigrated.txt@@ -0,0 +1,183 @@+# Models that are team-scoped but still on a non-fail-closed manager.+#+# DO NOT EDIT BY HAND. This file is the mechanical output of+# `--regenerate-baseline` — adding entries by hand defeats the algebra and+# turns this back into a hand-curated allowlist (the IDOR-list problem).+#+# Auto-generated by .github/scripts/check-idor-model-coverage.py+# Regenerate with: python .github/scripts/check-idor-model-coverage.py --regenerate-baseline+#+# Adopting fail-closed: change the model's base from RootTeamMixin to+# TeamScopedRootMixin (main DB) or ProductTeamModel (separate DB), then+# audit every call site to either be inside team scope or use .unscoped().+# Once that's done, regenerate this file and the model drops out.+AccessControl+Action+AgentArtifact+AgentMemory+Alert+AlertConfiguration+Annotation+ApprovalPolicy+BatchExport+BatchExportBackfill+BatchExportFileDownload+BatchImport+ButtonTile+ChangeRequest+ClusteringConfig+ClusteringJob+Cohort+Comment+Conversation+ConversationRestoreToken+CoreMemory+CustomerJourney+CustomerProfileConfig+DAG+Dashboard+DashboardTemplate+DataColorTheme+DataModelingJob+DataWarehouseCredential+DataWarehouseJoin+DataWarehouseManagedViewSet+DataWarehouseModelPath+DataWarehouseSavedQuery+DataWarehouseSavedQueryDraft+DataWarehouseSavedQueryFolder+DataWarehouseTable+Dataset+DatasetItem+DesktopRecording+EarlyAccessFeature+Edge+EmailChannel+EmailMessageMapping+Endpoint+EnterpriseEventDefinition+EnterprisePropertyDefinition+ErrorTrackingAssignmentRule+ErrorTrackingGroupingRule+ErrorTrackingIssue+ErrorTrackingIssueFingerprintV2+ErrorTrackingRecommendation+ErrorTrackingRelease+ErrorTrackingSettings+ErrorTrackingSpikeDetectionConfig+ErrorTrackingSpikeEvent+ErrorTrackingStackFrame+ErrorTrackingSuppressionRule+ErrorTrackingSymbolSet+Evaluation+EvaluationContext+EvaluationReport+EventFilterConfig+Experiment+ExperimentHoldout+ExperimentSavedMetric+ExportedAsset+ExportedRecording+ExternalDataJob+ExternalDataSchema+ExternalDataSource+FeatureFlag+FileSystem+FileSystemShortcut+FileSystemViewLog+GitHubSyncConfig+GitHubSyncPlan+GitHubSyncedModel+GithubCommentMapping+HealthIssue+HogFlow+HogFlowBatchJob+HogFlowSchedule+HogFlowTemplate+HogFunction+Hook+Insight+InsightVariable+InsightViewed+Integration+IntegrationRepositoryCacheEntry+IntervieweeContext+KernelRuntime+LLMModelConfiguration+LLMPrompt+LLMProviderKey+LLMSkill+LLMTraceSummary+Link+LiveDebuggerBreakpoint+LogsAlertConfiguration+LogsExclusionRule+LogsView+MCPAnalyticsSubmission+MCPServerInstallation+MarketingAnalyticsGoalMapping+MessageCategory+MessageRecipientPreference+MessageTemplate+Node+Notebook+NotificationEvent+ObjectMediaPreview+OptOutSyncConfig+PersistedFolder+PluginConfig+ProductTour+ProjectSecretAPIKey+PropertyAccessControl+QueryTabState+QuickFilter+QuickFilterContext+ReplayLens+ReplayObservation+RepoRoutingRule+ReviewQueue+ReviewQueueItem+SandboxEnvironment+SavedHeatmap+ScheduledChange+ScoreDefinition+SessionGroupSummary+SessionRecording+SessionRecordingPlaylist+SessionRecordingViewed+SharingConfiguration+SignalEmissionRecord+SignalReport+SignalReportArtefact+SignalReportTask+SignalSourceConfig+SignalTeamConfig+SingleSessionSummary+SlackThreadTaskMapping+SourceBatch+StreamlitApp+Subscription+SubscriptionDelivery+Survey+SurveyResponseArchive+Tag+Tagger+Task+TaskRun+TeamConversationsTeamsConfig+TeamFeatureFlagDefaultsConfig+TeamSessionSummariesConfig+Text+Threshold+Ticket+TicketView+TraceReview+TraceReviewScore+UploadedMedia+UserHomeSettings+UserInterview+UserInterviewTopic+UserProductList+UserRepoPreference+UserScenePersonalisation+WebAnalyticsFilterPresetdiff --git a/posthog/models/scoping/root_mixin.py b/posthog/models/scoping/root_mixin.pynew file mode 100644index 000000000000..bca8d38d9226--- /dev/null+++ b/posthog/models/scoping/root_mixin.py@@ -0,0 +1,58 @@+"""+Abstract model for main-DB models that should be team-scoped fail-closed.++Main-DB counterpart of `ProductTeamModel`. Bundles the canonical-team+save() rewrite from `RootTeamMixin` with the fail-closed `TeamScopedManager`,+so new main-DB models opt into both with a single base class.++Usage:++ from posthog.models.scoping.root_mixin import TeamScopedRootMixin++ class Campaign(TeamScopedRootMixin):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ name = models.CharField(max_length=255)++ # In DRF view (mixin sets canonical team context):+ Campaign.objects.all() # Auto-filtered to canonical team++ # Explicit cross-team:+ Campaign.objects.unscoped().all() # No filtering++ # Background jobs (auto-resolves to canonical):+ with team_scope(team_id):+ Campaign.objects.all()++The pre-existing `RootTeamMixin` stays in place for the ~263 legacy main-DB+models that haven't audited their call sites yet — adopting fail-closed+requires walking every read path. `TeamScopedRootMixin` is the prescribed+default for *new* main-DB models so they start fail-closed.+"""++from __future__ import annotations++from posthog.models.scoping.manager import TeamScopedManager+from posthog.models.utils import RootTeamMixin+++class TeamScopedRootMixin(RootTeamMixin):+ """Abstract base for main-DB models that want fail-closed team scoping.++ Inherits the canonical-team save() rewrite from `RootTeamMixin` and+ overrides `objects` to use the fail-closed `TeamScopedManager`.+ Subclasses still declare their own `team = models.ForeignKey(...)` —+ `RootTeamMixin` does not declare the FK so cascade behavior remains+ a per-model decision.+ """++ # Override of `RootTeamMixin.objects` (RootTeamManager) — mypy can't+ # infer that the parent's narrower manager is intentionally being+ # widened, so the assignment looks incompatible. The override is the+ # whole point of this mixin.+ objects = TeamScopedManager() # type: ignore[assignment]++ class Meta:+ abstract = True+++__all__ = ["TeamScopedRootMixin"]diff --git a/posthog/models/scoping/test_root_mixin.py b/posthog/models/scoping/test_root_mixin.pynew file mode 100644index 000000000000..53b563d7e1d2--- /dev/null+++ b/posthog/models/scoping/test_root_mixin.py@@ -0,0 +1,87 @@+"""Smoke tests for TeamScopedRootMixin wiring.++Manager mechanics (filtering, raise-on-no-context, unscoped, etc.) are+covered exhaustively in test_manager.py against FeatureFlag — those tests+apply unchanged to any TeamScopedManager-backed model. This file just+verifies that inheriting `TeamScopedRootMixin` swaps the manager from+`RootTeamManager` to `TeamScopedManager` while keeping the canonical-team+save() rewrite from the parent — and that the CI introspection (which is+an isinstance check on the manager named `objects` in `_meta.managers_map`)+recognises all three adoption styles: the two mixins and an ad-hoc+`objects = TeamScopedManager()`.+"""++from types import SimpleNamespace++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+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import RootTeamManager, RootTeamMixin+++class TestTeamScopedRootMixinWiring(SimpleTestCase):+ def test_objects_is_team_scoped_manager(self) -> None:+ """The default manager is fail-closed by team scope, overriding RootTeamManager."""+ manager = TeamScopedRootMixin._meta.managers_map["objects"]+ self.assertIsInstance(manager, TeamScopedManager)+ self.assertNotIsInstance(manager, RootTeamManager)++ def test_inherits_from_root_team_mixin(self) -> None:+ """Inherits the canonical-team save() rewrite via RootTeamMixin."""+ self.assertTrue(issubclass(TeamScopedRootMixin, RootTeamMixin))++ def test_is_abstract(self) -> None:+ """The mixin itself does not create a table."""+ self.assertTrue(TeamScopedRootMixin._meta.abstract)+++class TestFailClosedIntrospection(SimpleTestCase):+ """The CI baseline check (compute_unmigrated_to_fail_closed) verifies+ that the manager accessible as `Model.objects` is a `TeamScopedManager`.+ Confirm that contract holds for all three adoption styles.++ Anchoring on `objects` (rather than scanning all managers) closes the+ loophole reviewers flagged: a model could keep `objects =+ RootTeamManager()` and add a secondary scoped manager just to satisfy+ CI, while call sites like `Model.objects.X` stayed unscoped. Anchoring+ on `objects` also stays correct once #57879 sets+ `Meta.default_manager_name = "all_teams"` on ProductTeamModel —+ `_default_manager` will then resolve to the unscoped sibling for+ Django framework code (admin, related queries), but `Model.objects`+ will still resolve to the TeamScopedManager declared on the model.+ """++ @staticmethod+ def _objects_is_team_scoped(model: type[models.Model]) -> bool:+ return isinstance(model._meta.managers_map.get("objects"), TeamScopedManager)++ def test_product_team_model_is_detected(self) -> None:+ self.assertTrue(self._objects_is_team_scoped(ProductTeamModel))++ def test_team_scoped_root_mixin_is_detected(self) -> None:+ self.assertTrue(self._objects_is_team_scoped(TeamScopedRootMixin))++ def test_adhoc_declaration_is_detected(self) -> None:+ """A bare `objects = TeamScopedManager()` on a model that doesn't inherit+ either mixin still satisfies the check. We use a SimpleNamespace stub+ rather than a real `models.Model` subclass to avoid registering an+ abstract test model in the live `posthog` app registry."""+ stub = SimpleNamespace(_meta=SimpleNamespace(managers_map={"objects": TeamScopedManager()}))+ self.assertTrue(self._objects_is_team_scoped(stub)) # type: ignore[arg-type]++ def test_bypass_via_secondary_manager_is_not_detected(self) -> None:+ """A model with `objects = RootTeamManager()` and a secondary+ TeamScopedManager should NOT count as migrated — call sites+ still use Model.objects, which is unscoped."""+ stub = SimpleNamespace(+ _meta=SimpleNamespace(+ managers_map={+ "objects": RootTeamManager(),+ "scoped": TeamScopedManager(),+ }+ )+ )+ self.assertFalse(self._objects_is_team_scoped(stub)) # type: ignore[arg-type]diff --git a/tools/hogli-commands/hogli_commands/product/scaffold.py b/tools/hogli-commands/hogli_commands/product/scaffold.pyindex 4dc2a228a6e4..c1ca0b9c44a9 100644--- a/tools/hogli-commands/hogli_commands/product/scaffold.py+++ b/tools/hogli-commands/hogli_commands/product/scaffold.py@@ -27,9 +27,32 @@ def flatten_structure(files: dict, prefix: str = "", result: dict | None = None)return result-def _render_template(template: str, product_name: str) -> str:+def _team_scope_template_vars(*, separate_db: bool) -> dict[str, str]:+ """Pick the right team-scoped base class for the chosen DB layout.++ Separate-DB products can't FK to Team across databases, so they use+ `ProductTeamModel` (team_id as BigIntegerField). Main-DB products use+ `TeamScopedRootMixin` and declare a regular FK on the subclass. Both+ bundle `TeamScopedManager` so models start fail-closed.+ """+ if separate_db:+ return {+ "team_base_mixin": "ProductTeamModel",+ "team_base_import": "from posthog.models.scoping.product_mixin import ProductTeamModel",+ }+ return {+ "team_base_mixin": "TeamScopedRootMixin",+ "team_base_import": "from posthog.models.scoping.root_mixin import TeamScopedRootMixin",+ }+++def _render_template(template: str, product_name: str, *, separate_db: bool) -> str:pascal_name = "".join(word.capitalize() for word in product_name.split("_"))- return template.format(product=product_name, Product=pascal_name)+ return template.format(+ product=product_name,+ Product=pascal_name,+ **_team_scope_template_vars(separate_db=separate_db),+ )def _register_in_file(@@ -148,6 +171,38 @@ def _write_product_yaml(product_dir: Path, display_name: str, owners: list[str],click.echo(f"\n Created product.yaml (name={display_name!r}, owners={owners})")+def _prompt_for_separate_db(name: str) -> tuple[bool, str | None]:+ """Ask the operator whether the new product gets its own database.++ Returns (separate_db, db_name). `db_name` is None when the operator+ opts to share the main DB. Asked up front (before file generation)+ so the model template can branch on the answer — separate-DB needs+ `ProductTeamModel`, main-DB needs `TeamScopedRootMixin`.+ """+ click.echo(+ "\n Products get their own database by default — this isolates locks, "+ "connections, and migrations so one product can't bring down the app. "+ "This is new but fully working. Reach out in #team-devex with questions."+ )+ click.secho(+ " ⚠ Adding a route here is only the Django side. The database must also "+ "be provisioned by #team-infrastructure (Terraform + charts).",+ fg="yellow",+ )+ existing_dbs = _get_existing_databases()+ if existing_dbs:+ click.echo(f" Existing databases: {', '.join(existing_dbs)}")+ click.echo(" You can share a database with another product from the same team.")++ if click.confirm(" Skip separate database?", default=False):+ click.echo(" Using the main database. Models will inherit TeamScopedRootMixin.")+ return False, None++ db_name = click.prompt(" Database name", default=name, show_default=True)+ click.echo(f" Using separate database '{db_name}'. Models will inherit ProductTeamModel.")+ return True, db_name++def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive: bool = False) -> None:if not _VALID_PRODUCT_NAME_RE.match(name):raise click.ClickException(@@ -158,6 +213,14 @@ def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive:if product_dir.exists() and not force:raise click.ClickException(f"Product '{name}' already exists at {product_dir}. Use --force to overwrite.")+ # Resolve the DB layout up front so file rendering can branch on it.+ # Dry-run and non-interactive both default to separate-DB to match the+ # previous preview / automation behavior.+ if dry_run or non_interactive:+ separate_db, db_name = True, name+ else:+ separate_db, db_name = _prompt_for_separate_db(name)+structure = load_structure()created: list[str] = []skipped: list[str] = []@@ -171,7 +234,7 @@ def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive:if file_path.exists() and not force:skipped.append(path)continue- file_path.write_text(_render_template(config.get("template", ""), name))+ file_path.write_text(_render_template(config.get("template", ""), name, separate_db=separate_db))created.append(path)for path, config in flatten_structure(structure.get("backend_files", {})).items():@@ -184,7 +247,7 @@ def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive:if file_path.exists() and not force:skipped.append(label)continue- file_path.write_text(_render_template(config.get("template", ""), name))+ file_path.write_text(_render_template(config.get("template", ""), name, separate_db=separate_db))created.append(label)for folder_name in structure.get("frontend_files", {}).keys():@@ -227,32 +290,15 @@ def bootstrap_product(name: str, dry_run: bool, force: bool, *, non_interactive:_add_to_frontend_package_json(name, dry_run=dry_run)_add_to_django_settings(name, dry_run=dry_run)- if dry_run:- _add_to_db_routing(name, name, dry_run=True)- elif non_interactive:- _add_to_db_routing(name, name, dry_run=False)- else:- click.echo(- "\n Products get their own database by default — this isolates locks, "- "connections, and migrations so one product can't bring down the app. "- "This is new but fully working. Reach out in #team-devex with questions."- )+ if separate_db and db_name is not None:+ _add_to_db_routing(name, db_name, dry_run=dry_run)+ elif not dry_run:+ click.echo(" Skipped db_routing entry. Models live in the main database.")++ if not dry_run:+ mixin = "ProductTeamModel" if separate_db else "TeamScopedRootMixin"click.secho(- " ⚠ Adding a route here is only the Django side. The database must also "- "be provisioned by #team-infrastructure (Terraform + charts).",- fg="yellow",+ f"\n Models inherit `{mixin}` (fail-closed team scoping). "+ "Read posthog/models/scoping/README.md for the contract before writing your first model.",+ fg="cyan",)- existing_dbs = _get_existing_databases()- if existing_dbs:- click.echo(f" Existing databases: {', '.join(existing_dbs)}")- click.echo(" You can share a database with another product from the same team.")-- if click.confirm(" Skip separate database?", default=False):- click.echo(" Skipped. You can add it later in products/db_routing.yaml.")- else:- db_name = click.prompt(- " Database name",- default=name,- show_default=True,- )- _add_to_db_routing(name, db_name, dry_run=False)diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yamlindex fcb00e8e7e8c..8bf629816d3c 100644--- a/tools/hogli-commands/hogli_commands/product_structure.yaml+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml@@ -118,12 +118,17 @@ backend_files:from django.db import models- from posthog.models.scoping.product_mixin import ProductTeamModel+ {team_base_import}from .facade.enums import SplineStatus- class SplineReticulator(ProductTeamModel):+ # Inherits {team_base_mixin} so models opt into fail-closed team scoping —+ # queries without team context raise TeamScopeError instead of silently+ # returning every team's rows. See posthog/models/scoping/README.md.+ # Main-DB products (TeamScopedRootMixin): add `team = models.ForeignKey(+ # "posthog.Team", on_delete=models.CASCADE)` to the subclass.+ class SplineReticulator({team_base_mixin}):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)name = models.CharField(max_length=255)status = models.CharField(