: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(devex): flag project-wide filters on environment-scoped models (#113813)
Julian Bez0dfd58580337
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex bb8c370d9234..c156d24ee70b 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -10,10 +10,14 @@ CI script that checks two related concerns:don't are checked against `posthog/models/scoping/baseline_unmigrated.txt`— additions fail CI, removals are reported as opportunities toshrink the baseline.+3. Environment-scoped model list: the model regex in the+ `environment-model-scoped-by-project` semgrep rule matches the+ environment-scoped models derived from code.Usage:python check-idor-model-coverage.pypython check-idor-model-coverage.py --regenerate-baseline+ python check-idor-model-coverage.py --regenerate-environment-modelsExit codes:0 - All checks pass@@ -30,6 +34,8 @@ import yamlREPO_ROOT = Path(__file__).resolve().parent.parent.parentBASELINE_FILE = REPO_ROOT / "posthog/models/scoping/baseline_unmigrated.txt"+SEMGREP_RULES_FILE = REPO_ROOT / ".semgrep/rules/security/idor-team-scoped-models.yaml"+ENVIRONMENT_RULE_ID = "environment-model-scoped-by-project"def setup_django() -> None:@@ -517,12 +523,14 @@ def parse_semgrep_models(yaml_path: Path) -> dict[str, set[str]]:# User+team models are treated as team_scoped for comparison"idor-taint-user-input-to-user-team-model": "team_scoped","idor-lookup-without-user-and-team": "team_scoped",+ ENVIRONMENT_RULE_ID: "env_scoped",}result: dict[str, set[str]] = {"team_scoped": set(),"org_scoped": set(),"user_scoped": set(),+ "env_scoped": set(),}for rule in data.get("rules", []):@@ -698,6 +706,95 @@ def check_fail_closed_baseline(return False, False+def get_environment_scoped_models(team_scoped: set[str]) -> set[str]:+ """Team-scoped models whose rows belong to one environment, not to the whole project.++ Project-level models drop out in two ways. RootTeamMixin (and its fail-closed+ TeamScopedRootMixin) and ProductTeamModel rewrite team_id to the project's root+ team on save. Models with a `project` relation to Project (own or inherited) are+ keyed by the project directly.+ """+ from django.apps import apps++ from posthog.models.project import Project+ from posthog.models.scoping.product_mixin import ProductTeamModel+ from posthog.models.utils import RootTeamMixin++ environment_scoped: set[str] = set()+ for model in apps.get_models():+ if model._meta.proxy or model.__name__ not in team_scoped:+ continue+ if issubclass(model, (RootTeamMixin, ProductTeamModel)):+ continue+ # A field named `project` can hold something else, such as a release's application name.+ has_project_relation = any(+ field.name == "project" and field.related_model is Project for field in model._meta.get_fields()+ )+ if has_project_relation:+ continue+ environment_scoped.add(model.__name__)+ return environment_scoped+++def render_environment_model_regex(models: set[str]) -> str:+ """Return the regex block scalar body, indented to sit under `regex: |` in the rule."""+ indent = " " * 20+ names = sorted(models, key=str.lower)+ lines = [f"{indent}(?x)^("]+ lines.append(f"{indent} {names[0]}")+ lines.extend(f"{indent} |{name}" for name in names[1:])+ lines.append(f"{indent})$")+ return "\n".join(lines) + "\n"+++def write_environment_model_regex(models: set[str]) -> None:+ text = SEMGREP_RULES_FILE.read_text()+ rule_start = text.index(f"- id: {ENVIRONMENT_RULE_ID}\n")+ next_rule = text.find("\n - id: ", rule_start + 1)+ rule_end = len(text) if next_rule == -1 else next_rule+ # The first `regex: |` block inside the rule holds the model list. The search stops at the+ # next rule, so a missing block cannot rewrite another rule's list.+ regex_block = re.compile(r"(regex: \|\n)(.*?\)\$\n)", re.DOTALL)+ match = regex_block.search(text, rule_start, rule_end)+ if match is None:+ raise ValueError(f"No `regex: |` block found in rule {ENVIRONMENT_RULE_ID}")+ new_text = text[: match.start(2)] + render_environment_model_regex(models) + text[match.end(2) :]+ SEMGREP_RULES_FILE.write_text(new_text)+++def check_environment_model_list(+ team_scoped: set[str],+ semgrep_environment_models: set[str],+ *,+ regenerate: bool,+) -> bool:+ """Return True when the rule's model list differs from the code."""+ expected = get_environment_scoped_models(team_scoped)++ print(f"\n{'=' * 60}")+ print("Environment-scoped model list check")+ print("=" * 60)++ if regenerate:+ write_environment_model_regex(expected)+ print(f"\n Regenerated the {ENVIRONMENT_RULE_ID} model list ({len(expected)} models).")+ return False++ missing = expected - semgrep_environment_models+ extra = semgrep_environment_models - expected+ if not missing and not extra:+ print(f" ✅ {ENVIRONMENT_RULE_ID} lists all {len(expected)} environment-scoped models.")+ return False++ print(f"::error::The {ENVIRONMENT_RULE_ID} model list is out of date")+ for model in sorted(missing):+ print(f" + {model} (environment-scoped, missing from the rule)")+ for model in sorted(extra):+ print(f" - {model} (in the rule, but not environment-scoped)")+ print(f"\n Run: python {Path(__file__).relative_to(REPO_ROOT)} --regenerate-environment-models")+ return True++def main() -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument(@@ -705,6 +802,11 @@ def main() -> int:action="store_true",help="Rewrite the fail-closed baseline file from the current code state.",)+ parser.add_argument(+ "--regenerate-environment-models",+ action="store_true",+ help=f"Rewrite the model list of the {ENVIRONMENT_RULE_ID} semgrep rule from the current code state.",+ )args = parser.parse_args()setup_django()@@ -713,8 +815,7 @@ def main() -> int:code_models, excluded_models, legitimately_unscoped, needs_team_id = get_scoped_models()# Get models from semgrep rules- semgrep_path = REPO_ROOT / ".semgrep/rules/security/idor-team-scoped-models.yaml"- semgrep_models = parse_semgrep_models(semgrep_path)+ semgrep_models = parse_semgrep_models(SEMGREP_RULES_FILE)# Compare and reporthas_errors = False@@ -811,6 +912,13 @@ def main() -> int:has_errors = has_errors or fail_closed_errorshas_warnings = has_warnings or fail_closed_warnings+ environment_list_errors = check_environment_model_list(+ code_models["team_scoped"],+ semgrep_models["env_scoped"],+ regenerate=args.regenerate_environment_models,+ )+ has_errors = has_errors or environment_list_errors+print("\n" + "=" * 60)if has_errors:diff --git a/.semgrep/rules/security/idor-team-scoped-models.py b/.semgrep/rules/security/idor-team-scoped-models.pyindex 77f08556a92a..2a7f3997ec09 100644--- a/.semgrep/rules/security/idor-team-scoped-models.py+++ b/.semgrep/rules/security/idor-team-scoped-models.py@@ -5,9 +5,11 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.product_analytics.backend.facade.models import Insightfrom products.actions.backend.models.action import Actionfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.integration import Integrationfrom posthog.models.project import Projectfrom posthog.models.id_jag_identity import IdJagIdentityfrom posthog.models.user_scene_personalisation import UserScenePersonalisation+from products.product_tours.backend.models import ProductTourfrom ee.models.rbac.role import Role, RoleMembership@@ -844,3 +846,42 @@ def safe_user_team_aget(request, user, team):settings_id = request.GET.get("settings_id")# ok: idor-lookup-without-user-and-teamreturn UserScenePersonalisation.objects.aget(pk=settings_id, user=user, team=team)+++# ============================================================+# environment-model-scoped-by-project (ERROR - project filter on an environment-scoped model)+# ============================================================+++def env_model_filtered_by_project(team, integration_id, project_ids):+ # ruleid: environment-model-scoped-by-project+ integrations = Integration.objects.filter(kind="slack", team__project_id=team.project_id)++ # ruleid: environment-model-scoped-by-project+ tours = ProductTour.all_objects.filter(team__project_id__in=project_ids)++ # ruleid: environment-model-scoped-by-project+ integration = get_object_or_404(Integration, id=integration_id, team__project_id=team.project_id)++ return integrations, tours, integration+++def project_model_filtered_by_project(team, cohort_id, action_id):+ # ok: environment-model-scoped-by-project+ cohort = Cohort.objects.get(pk=cohort_id, team__project_id=team.project_id)++ # ok: environment-model-scoped-by-project+ action = get_object_or_404(Action, id=action_id, team__project_id=team.project_id)++ return cohort, action+++def env_model_filtered_by_team(team):+ # ok: environment-model-scoped-by-project+ return Integration.objects.filter(kind="slack", team_id=team.id)+++def env_model_project_wide_on_purpose(team):+ # ok: environment-model-scoped-by-project+ # nosemgrep: environment-model-scoped-by-project -- fixture for an intended project-wide read+ return Integration.objects.filter(kind="slack", team__project_id=team.project_id)diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 7b070b892247..9b0a6b93c7b4 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -13,7 +13,10 @@ rules:severity: ERRORmessage: |IDOR: User input flows to team-scoped model lookup without team filter.- Fix: Add team__project_id=team.project_id to the query.+ Fix: Add team_id=team_id to the query.+ Use team__project_id=team.project_id only for project-level models (RootTeamMixin,+ TeamScopedRootMixin), whose rows live on the project's root team. ProductTeamModel has+ no team relation: filter it by its canonical team_id.pattern-sources:- patterns:- pattern-either:@@ -946,7 +949,10 @@ rules:- pattern-not: $M.objects. ... .$METHOD2(id=$X.id, ...)message: |IDOR risk: Lookup on team-scoped model without team filter.- Fix: Add team_id=team_id or team__project_id=team.project_id to the query.+ Fix: Add team_id=team_id to the query.+ Use team__project_id=team.project_id only for project-level models (RootTeamMixin,+ TeamScopedRootMixin), whose rows live on the project's root team. ProductTeamModel has+ no team relation: filter it by its canonical team_id.languages: [python]severity: WARNINGmetadata:@@ -969,6 +975,273 @@ rules:- '**/backend/admin.py'- '**/backend/admin/**'+ # Environment-scoped models keep one set of rows per environment. A project holds+ # several environments, so a team__project_id filter on these models also returns+ # rows of sibling environments.+ - id: environment-model-scoped-by-project+ languages: [python]+ severity: ERROR+ message: |+ $M is environment-scoped, so team__project_id also returns rows of sibling environments in the same project.+ Fix: Filter by team_id (the environment's own id).+ A route under /api/projects/ is still team-scoped unless it is registered with ["project_id"].+ If project-wide access is intended, add `# nosemgrep: environment-model-scoped-by-project -- <why>`.+ patterns:+ - pattern-either:+ - pattern: $M.$MGR. ... .$METHOD(..., team__project_id=$P, ...)+ - pattern: $M.$MGR. ... .$METHOD(..., team__project_id__in=$P, ...)+ - pattern: get_object_or_404($M, ..., team__project_id=$P, ...)+ - pattern: get_object_or_404($M, ..., team__project_id__in=$P, ...)+ # Generated list. Regenerate with:+ # python .github/scripts/check-idor-model-coverage.py --regenerate-environment-models+ - metavariable-regex:+ metavariable: $M+ regex: |+ (?x)^(+ AccessControl+ |ActivityLog+ |AgentArtifact+ |AgentMemory+ |AITrainingDeletionRequest+ |Alert+ |AlertConfiguration+ |Annotation+ |ApprovalPolicy+ |AsyncDeletion+ |BatchExport+ |BatchExportBackfill+ |BatchExportFileDownload+ |BatchImport+ |ButtonTile+ |ChangeRequest+ |ClusteringConfig+ |ClusteringJob+ |ColumnConfiguration+ |Conversation+ |ConversationRestoreToken+ |CoreEvent+ |CoreMemory+ |CustomerJourney+ |CustomerProfileConfig+ |DAG+ |DashboardTile+ |DataDeletionRequest+ |DataModelingJob+ |Dataset+ |DatasetItem+ |DatasetItemVersion+ |DatasetRevision+ |DataWarehouseCredential+ |DataWarehouseJoin+ |DataWarehouseManagedViewSet+ |DataWarehouseModelPath+ |DataWarehouseSavedQuery+ |DataWarehouseSavedQueryDraft+ |DataWarehouseSavedQueryFolder+ |DataWarehouseTable+ |DataWarehouseViewLink+ |Edge+ |ElementGroup+ |EmailChannel+ |EmailMessageMapping+ |EmailOutboxMessage+ |Endpoint+ |EndpointVersion+ |ErrorTrackingAssignmentRule+ |ErrorTrackingAutoCaptureControls+ |ErrorTrackingBypassRule+ |ErrorTrackingGroup+ |ErrorTrackingGroupingRule+ |ErrorTrackingIssue+ |ErrorTrackingIssueAssignment+ |ErrorTrackingIssueFingerprint+ |ErrorTrackingIssueFingerprintV2+ |ErrorTrackingRecommendation+ |ErrorTrackingRelease+ |ErrorTrackingSettings+ |ErrorTrackingSpikeDetectionConfig+ |ErrorTrackingSpikeEvent+ |ErrorTrackingStackFrame+ |ErrorTrackingSuppressionRule+ |ErrorTrackingSymbolSet+ |Evaluation+ |EvaluationConfig+ |EvaluationContext+ |EvaluationReport+ |Event+ |EventFilterConfig+ |ExperimentTimeseriesRecalculation+ |ExplicitTeamMembership+ |ExportedAsset+ |ExportedRecording+ |ExternalDataJob+ |ExternalDataSchema+ |ExternalDataSource+ |FeatureFlagHashKeyOverride+ |FeatureFlagOverride+ |FileSystemShortcut+ |FileSystemViewLog+ |FlatPersonOverride+ |GithubCommentMapping+ |GitHubSyncConfig+ |GitHubSyncedModel+ |GitHubSyncPlan+ |Group+ |GroupUsageMetric+ |HealthIssue+ |HogFlow+ |HogFlowTemplate+ |HogFunction+ |Hook+ |InsightViewed+ |Integration+ |IntegrationRepositoryCacheEntry+ |IntervieweeContext+ |KernelRuntime+ |KnowledgeChunk+ |KnowledgeDocument+ |KnowledgeSource+ |Link+ |LiveDebuggerBreakpoint+ |LLMModelConfiguration+ |LLMPrompt+ |LLMPromptDependency+ |LLMPromptLabel+ |LLMProviderKey+ |LLMSkill+ |LLMSkillOwner+ |LLMTraceSummary+ |LogsAlertConfiguration+ |LogsExclusionRule+ |LogsRetentionRule+ |LogsView+ |MarketingAnalyticsGoalMapping+ |MaterializedColumnSlot+ |MCPAnalyticsSubmission+ |MCPMeasuredStats+ |MCPOAuthState+ |MCPServerInstallation+ |MessageCategory+ |MessageRecipientPreference+ |MessageTemplate+ |Node+ |NotificationEvent+ |ObjectMediaPreview+ |OfflineEvaluationResult+ |OfflineEvaluationResultPayload+ |OfflineExperiment+ |OfflineExperimentItem+ |OfflineExperimentItemPayload+ |OptOutSyncConfig+ |PendingPersonOverride+ |Person+ |PersonalAPIKey+ |PersonDistinctId+ |PersonOverride+ |PersonOverrideMapping+ |PluginAttachment+ |PluginConfig+ |PreaggregationJob+ |ProductTour+ |ProjectSecretAPIKey+ |PropertyAccessControl+ |QueryTabState+ |QueueJob+ |QueueSchedulerDecision+ |QueueSchedulerState+ |QuickFilter+ |QuickFilterContext+ |RemoteConfig+ |ReplayObservation+ |ReplayObservationLabel+ |ReplayObservationUsage+ |ReplayScanner+ |RepoRoutingRule+ |ResourceTransfer+ |ReviewQueue+ |ReviewQueueItem+ |RevokedTeamSecretToken+ |SandboxEnvironment+ |SavedHeatmap+ |ScoreDefinition+ |SessionRecording+ |SessionRecordingEvent+ |SessionRecordingPlaylist+ |SessionRecordingPlaylistViewed+ |SessionRecordingViewed+ |SharingConfiguration+ |SignalEmissionRecord+ |SignalReport+ |SignalReportArtefact+ |SignalReportCheck+ |SignalReportSlackThread+ |SignalReportTask+ |SignalSourceConfig+ |SignalTeamConfig+ |SigningSecret+ |SlackThreadTaskMapping+ |SourceBatch+ |SourceGroupLease+ |Subscription+ |SubscriptionDelivery+ |SurveyResponseArchive+ |TableCertification+ |TaggedItem+ |Tagger+ |Task+ |TaskRun+ |TeamAccessControlConfig+ |TeamBusinessKnowledgeConfig+ |TeamConversationsSlackConfig+ |TeamConversationsTeamsConfig+ |TeamConversationsTicketConfig+ |TeamCustomerAnalyticsConfig+ |TeamDataQualityConfig+ |TeamDataWarehouseConfig+ |TeamDefaultEvaluationContext+ |TeamEventsRetentionConfig+ |TeamEventVolume+ |TeamExperimentsConfig+ |TeamFeatureFlagDefaultsConfig+ |TeamFeatureFlagPolicyConfig+ |TeamFeatureFlagsConfig+ |TeamHeatmapConfig+ |TeamHomeTabDashboardConfig+ |TeamJsSnippetConfig+ |TeamLogsConfig+ |TeamMarketingAnalyticsConfig+ |TeamProvisioningConfig+ |TeamReplayVisionConfig+ |TeamRevenueAnalyticsConfig+ |TeamTasksConfig+ |TeamTracingConfig+ |TeamWorkflowsConfig+ |Text+ |Threshold+ |Ticket+ |TicketView+ |TraceReview+ |TraceReviewScore+ |TracesRetentionRule+ |User+ |UserGroup+ |UserInterview+ |UserInterviewTopic+ |UserProductList+ |UserRepoPreference+ |WarehouseSuggestionTeamConfig+ |WebAnalyticsFilterPreset+ )$+ metadata:+ category: security+ cwe: 'CWE-639: Authorization Bypass Through User-Controlled Key'+ confidence: HIGH+ paths:+ exclude:+ - '**/test*/**'+ - '**/migrations/**'+ - '**/.semgrep/**'+# Organization-scoped model taint rule- id: idor-taint-user-input-to-org-modelmode: taintdiff --git a/posthog/models/file_system/starred_products.py b/posthog/models/file_system/starred_products.pyindex 1d5a898a583d..a25052b5b1a1 100644--- a/posthog/models/file_system/starred_products.py+++ b/posthog/models/file_system/starred_products.py@@ -63,6 +63,7 @@ def star_products(user: User, team: "Team", product_paths: list[str]) -> int:# Concurrent writes for the same user would otherwise both miss the star and add it twice.lock_user_shortcuts(team.pk, user.pk)# The sidebar lists the stars of every environment in the project, so check them all.+ # nosemgrep: environment-model-scoped-by-project -- the shortcut API lists a user's own stars project-wideuser_shortcuts = FileSystemShortcut.objects.filter(surface_q(DEFAULT_SURFACE), team__project_id=team.project_id, user=user)diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 13835adba368..49355e11f5b2 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -702,6 +702,11 @@ class PostHogTestCase(SimpleTestCase):raise ValueError("Test organization must be set before creating a user")return User.objects.create_and_join(self.organization, email, password, first_name, **kwargs)+ def create_sibling_environment(self, name: str = "Sibling env") -> Team:+ # Same row shape as an environment added through the API: same project, no parent_team.+ # It skips create_with_data, so the environment has no default dashboards or insights.+ return Team.objects.create(organization=self.organization, project=self.project, name=name)+@classmethoddef setUpTestData(cls):if cls.CLASS_DATA_LEVEL_SETUP:diff --git a/products/error_tracking/backend/logic/alerts.py b/products/error_tracking/backend/logic/alerts.pyindex 68197e9380d7..ee02b4fda947 100644--- a/products/error_tracking/backend/logic/alerts.py+++ b/products/error_tracking/backend/logic/alerts.py@@ -277,6 +277,7 @@ def _validate_destination(team_id: int, destination: dict[str, Any]) -> None:# Integrations are stored on environment teams while alert rows live on the# canonical team, so accept any integration in the same project.project_id = Team.objects.values_list("project_id", flat=True).get(id=team_id)+ # nosemgrep: environment-model-scoped-by-project -- alert rows live on the canonical team, so a Slack integration from any environment of the project is validif not Integration.objects.filter(team__project_id=project_id, id=integration_id, kind=Integration.IntegrationKind.SLACK).exists():diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.pyindex 9179b9ff74d7..7af01c3110c4 100644--- a/products/exports/backend/facade/api.py+++ b/products/exports/backend/facade/api.py@@ -118,6 +118,7 @@ def save_export_asset_content_from_file(def delete_insight_subscriptions(*, project_id: int, insight_ids: Collection[int]) -> None:+ # nosemgrep: environment-model-scoped-by-project -- insights are project-level, so deleting one removes its subscriptions in every environmentfor subscription in Subscription.objects.filter(team__project_id=project_id, insight_id__in=insight_ids):subscription.delete()diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex a9a97b38020d..21b6a6908548 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -4059,6 +4059,7 @@ class FeatureFlagViewSet()survey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)+ # nosemgrep: environment-model-scoped-by-project -- feature flags live on the project root team and a tour on any environment of the project can own an internal targeting flagproduct_tour_internal_targeting_flags = ProductTour.all_objects.filter(team__project_id=self.project_id, internal_targeting_flag__isnull=False).values_list("internal_targeting_flag_id", flat=True)@@ -4691,6 +4692,7 @@ class FeatureFlagViewSet(# Exclude internal flags (survey targeting and product tour internal flags)# These are auto-generated and not user-editable, same as the main flags listsurvey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)+ # nosemgrep: environment-model-scoped-by-project -- feature flags live on the project root team and a tour on any environment of the project can own an internal targeting flagproduct_tour_internal_targeting_flags = ProductTour.all_objects.filter(team__project_id=self.project_id, internal_targeting_flag__isnull=False).values_list("internal_targeting_flag_id", flat=True)@@ -4843,6 +4845,7 @@ class FeatureFlagViewSet(# Exclude internal flags (same as list endpoint)survey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)+ # nosemgrep: environment-model-scoped-by-project -- feature flags live on the project root team and a tour on any environment of the project can own an internal targeting flagproduct_tour_internal_targeting_flags = ProductTour.all_objects.filter(team__project_id=self.project_id, internal_targeting_flag__isnull=False).values_list("internal_targeting_flag_id", flat=True)@@ -4945,6 +4948,7 @@ class FeatureFlagViewSet(# The stale-flags health check mirrors this guard's reference checks in# products/feature_flags/backend/temporal/health_checks/stale_flags.py. Keep the two in step.survey_flag_ids = Survey.get_internal_flag_ids(project_id=self.project_id)+ # nosemgrep: environment-model-scoped-by-project -- feature flags live on the project root team and a tour on any environment of the project can own an internal targeting flagproduct_tour_internal_targeting_flags = ProductTour.all_objects.filter(team__project_id=self.project_id, internal_targeting_flag__isnull=False).values_list("internal_targeting_flag_id", flat=True)diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.pyindex 87900005afa2..39cdf347a030 100644--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py@@ -355,6 +355,7 @@ def _excluded_flag_ids(candidates: list[FeatureFlag]) -> set[int]:excluded: set[int] = set()excluded |= Survey.get_internal_flag_ids(team_ids=team_ids)excluded |= set(+ # nosemgrep: environment-model-scoped-by-project -- feature flags live on the project root team and a tour on any environment of the project can own an internal targeting flagProductTour.all_objects.filter(team__project_id__in=project_ids, internal_targeting_flag__isnull=False).values_list("internal_targeting_flag_id", flat=True)diff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex 3f2a63b72875..fe404a2183a6 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -912,9 +912,10 @@ class ProductTourViewSet()tour_id = kwargs["pk"]- tour = ProductTour.objects.filter(id=tour_id, team__project_id=self.project_id).first()- if not tour:- return Response(status=status.HTTP_404_NOT_FOUND)+ tour = self.get_object()+ # The viewset queryset includes archived tours, which generation never served.+ if tour.archived:+ raise exceptions.NotFound()user = cast(User, self.request.user)@@ -1123,6 +1124,7 @@ class ProductTourAPISerializer(serializers.ModelSerializer):def get_product_tours_response(team: Team) -> dict:"""Get active product tours for a team."""tours = ProductTourAPISerializer(+ # nosemgrep: environment-model-scoped-by-project -- the project route stores tours on the primary environment, so every environment's SDK reads the project's toursProductTour.objects.filter(team__project_id=team.project_id,archived=False,diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex dba300eb6438..4452a720632d 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -1,6 +1,7 @@from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.test import override_settingsfrom django.utils import timezonefrom parameterized import parameterized@@ -18,6 +19,22 @@ from products.surveys.backend.models import Surveyclass TestProductTour(APIBaseTest):+ @parameterized.expand([("sibling_environment", True, False), ("archived", False, True)])+ @override_settings(DEBUG=True, GEMINI_API_KEY="test-key")+ @patch("products.product_tours.backend.api.product_tour.generate_with_gemini")+ def test_generate_returns_404_for_a_tour_it_cannot_serve(self, _name, in_sibling, archived, mock_generate):+ team = self.create_sibling_environment() if in_sibling else self.team+ tour = ProductTour.objects.create(team=team, name="Tour", content={"steps": []}, archived=archived)++ response = self.client.post(+ f"/api/projects/{self.team.id}/product_tours/{tour.id}/generate/",+ data={"title": "Welcome"},+ format="json",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+ mock_generate.assert_not_called()+@patch("products.product_tours.backend.api.product_tour.report_user_action")def test_can_create_product_tour(self, mock_report):response = self.client.post(diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 2519b136bd48..dcf0a42317b8 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -2961,6 +2961,7 @@ def _validate_output_destinations(value: dict, context: dict) -> dict:raise RuntimeError("Scout config output destination validation requires project_id in its context")integration_id = slack["integration_id"]+ # nosemgrep: environment-model-scoped-by-project -- scout configs are project-level, so a Slack integration from any environment of the project is validintegration = Integration.objects.filter(id=integration_id,team__project_id=project_id,diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex fab00547154a..61ef449a2d76 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -187,6 +187,7 @@ def _prettify_scout_name(skill_name: str) -> str:def _slack_integration_for_project(*, integration_id: int, project_id: int) -> Integration:+ # nosemgrep: environment-model-scoped-by-project -- scout configs are project-level, so a Slack integration from any environment of the project is validintegration = Integration.objects.filter(id=integration_id,team__project_id=project_id,diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex f0553f86f56f..fe64acad1927 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -89,6 +89,7 @@ def search_workflows(if include_archived:statuses.append(HogFlow.State.ARCHIVED)queryset = access_control.filter_queryset_by_access_level(+ # nosemgrep: environment-model-scoped-by-project -- keeps the project-wide scope core /api/search used for workflows before the facade move; owners decide whether search narrows to one environmentHogFlow.objects.filter(team__project_id=project_id, status__in=statuses))