: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
chore(feature-flags): copy flags between projects through the facade (#102767)
Yasencc13220c3e6e
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txtindex e8f1bbe3370d..2e58121e2b0b 100644--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt@@ -12,8 +12,6 @@ products/demo/backend/logic/matrix/matrix.py::Matrix.set_project_up::FeatureFlagproducts/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up.create_experiment_flag::FeatureFlag.objects.create()products/demo/backend/logic/products/hedgebox/matrix.py::HedgeboxMatrix.set_project_up::FeatureFlag.objects.create()products/early_access_features/backend/api.py::clear_feature_enrollment::feature_flag.filters =-products/feature_flags/backend/api/organization_feature_flag.py::OrganizationFeatureFlagView._copy_feature_flag_to_target::FeatureFlagSerializer()-products/feature_flags/backend/api/organization_feature_flag.py::OrganizationFeatureFlagView._copy_feature_flag_to_target::FeatureFlagSerializer(existing_flag)products/feature_flags/evals/seeders.py::_create_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_full_rollout_flag::FeatureFlag.objects.create()products/feature_flags/evals/seeders.py::seed_stale_partial_rollout_flag::FeatureFlag.objects.create()diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.pyindex 383a5fdcbabd..4bfde85c454d 100644--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py@@ -23,7 +23,6 @@ GATED_PATH = {# Shrink-only. Move a write to the facade, then regenerate the baseline and drop its entry here.ALLOWED_REASONS: dict[str, str] = {- "products/feature_flags/backend/api/organization_feature_flag.py": "copy a flag to other projects","products/surveys/backend/api/survey.py": "targeting flag writes and the start/stop mirror of active","posthog/api/file_system/registrations.py": "file-system trash and restore flip active","products/early_access_features/backend/api.py": "never-fail cleanup when stored filters fail validation",diff --git a/products/approvals/backend/tests/test_transactions.py b/products/approvals/backend/tests/test_transactions.pynew file mode 100644index 000000000000..5ab2c98195d4--- /dev/null+++ b/products/approvals/backend/tests/test_transactions.py@@ -0,0 +1,63 @@+from datetime import timedelta++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.utils import timezone++from products.approvals.backend.exceptions import ApprovalRequired+from products.approvals.backend.models import ChangeRequest, ChangeRequestState+from products.approvals.backend.transactions import gated_atomic, restore_rolled_back_change_request+++class TestGatedAtomic(APIBaseTest):+ def _build_pending_change_request(self, resource_id: str = "1") -> ChangeRequest:+ return ChangeRequest.objects.create(+ action_key="feature_flag.enable",+ action_version=1,+ team=self.team,+ organization=self.organization,+ resource_type="feature_flag",+ resource_id=resource_id,+ intent={},+ intent_display={},+ policy_snapshot={},+ created_by=self.user,+ state=ChangeRequestState.PENDING,+ expires_at=timezone.now() + timedelta(days=1),+ )++ def _raise_approval_required(self) -> None:+ raise ApprovalRequired(+ change_request=self._build_pending_change_request(resource_id="gated"),+ message="Approval required",+ required_approvers={},+ )++ def test_the_gates_change_request_survives_while_the_blocks_other_writes_roll_back(self):+ with patch("products.approvals.backend.transactions.send_approval_requested_notification") as notify:+ with self.assertRaises(ApprovalRequired) as caught:+ with gated_atomic():+ self._build_pending_change_request(resource_id="copied-alongside")+ self._raise_approval_required()++ restored = ChangeRequest.objects.get(pk=caught.exception.change_request.id)+ assert restored.resource_id == "gated"+ assert restored.state == ChangeRequestState.PENDING+ assert not ChangeRequest.objects.filter(resource_id="copied-alongside").exists()+ notify.assert_called_once_with(caught.exception.change_request)++ def test_a_block_that_does_not_raise_commits_normally(self):+ with gated_atomic():+ change_request = self._build_pending_change_request()++ assert ChangeRequest.objects.filter(pk=change_request.pk).exists()++ def test_restoring_a_change_request_that_was_never_rolled_back_is_a_no_op(self):+ change_request = self._build_pending_change_request()++ with patch("products.approvals.backend.transactions.send_approval_requested_notification") as notify:+ restore_rolled_back_change_request(change_request)++ assert ChangeRequest.objects.filter(pk=change_request.pk).count() == 1+ notify.assert_not_called()diff --git a/products/approvals/backend/transactions.py b/products/approvals/backend/transactions.pynew file mode 100644index 000000000000..d922baabcdb2--- /dev/null+++ b/products/approvals/backend/transactions.py@@ -0,0 +1,56 @@+import logging+from collections.abc import Iterator+from contextlib import contextmanager++from django.db import transaction++from products.approvals.backend.exceptions import ApprovalRequired+from products.approvals.backend.models import ChangeRequest+from products.approvals.backend.notifications import send_approval_requested_notification++logger = logging.getLogger(__name__)+++def restore_rolled_back_change_request(change_request: ChangeRequest) -> None:+ """Re-insert a pending ChangeRequest that the caller's transaction rolled back.++ The gate writes the row and then raises, so an exception leaving an atomic block takes+ the row with it while the exception still carries the object. Re-inserting keeps the id+ the caller has already handed to its user.++ The duplicate branch of the gate raises with a change request an earlier request+ committed, so a row that is still there is left alone.+ """+ if ChangeRequest.objects.filter(pk=change_request.pk).exists():+ return++ change_request.save(force_insert=True)+ # The gate queues this notification with `transaction.on_commit`, and Django drops those+ # callbacks when the transaction rolls back. Send it here instead.+ send_approval_requested_notification(change_request)+++@contextmanager+def gated_atomic() -> Iterator[None]:+ """``transaction.atomic()`` for a block that can make a gated write.++ A gate raising inside an atomic block rolls its own pending ChangeRequest back, which+ leaves the caller reporting an approval that nobody can act on. This restores the row+ once the block has rolled back and the connection is in autocommit again.++ Use it as the outermost block. Nested inside another atomic block, the restore joins+ that transaction and rolls back with it, so it warns rather than claiming success.+ """+ try:+ with transaction.atomic():+ yield+ except ApprovalRequired as e:+ if e.change_request is not None:+ restore_rolled_back_change_request(e.change_request)+ if transaction.get_connection().in_atomic_block:+ logger.warning(+ "gated_atomic ran inside another atomic block, so the restored change request "+ "rolls back again if that block does",+ extra={"change_request_id": str(e.change_request.id)},+ )+ raisediff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex c69a0e58df6f..fca577c7b3cd 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1508,6 +1508,11 @@ class FeatureFlagSerializer(if not team:return attrs+ # A copy between projects carries the source flag's fields only, so the target's own+ # requirements cannot be met by the payload. The copy endpoint has always skipped them.+ if self.context.get("skip_team_flag_requirements"):+ return attrs+self._validate_evaluation_contexts_requirement(attrs, request, team, creation_context)self._validate_tags_requirement(attrs, team, creation_context)diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex f593cd57ca45..03fa6bfdfb76 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -10,6 +10,7 @@ import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponsefrom rest_framework import mixins, serializers, status, viewsets+from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.utils.urls import replace_query_param@@ -32,13 +33,14 @@ from products.access_control.backend.facade.user_access_control import ()from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflictfrom products.approvals.backend.scheduled_changes import gate_scheduled_change+from products.approvals.backend.transactions import gated_atomicfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads,get_decrypted_flag_payloads_protected,)+from products.feature_flags.backend.facade.api import create_flag, serialize_flags, update_flagfrom products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -517,7 +519,7 @@ class OrganizationFeatureFlagView()continuetry:- with transaction.atomic():+ with gated_atomic():target_flag_access_context = (self._get_accessible_target_flags_by_key([source_flag.key for source_flag in copy_source_flags],@@ -1346,26 +1348,27 @@ class OrganizationFeatureFlagView("is_remote_configuration": source_flag.is_remote_configuration,"has_encrypted_payloads": source_flag.has_encrypted_payloads,}- context = {- "request": request,- "team_id": target_project_id,- "project_id": target_project_id,- }-original_request_method = request.methodtry:# FeatureFlagSerializer validates create/update semantics from the request method.request.method = "PATCH" if existing_flag else "POST"- if existing_flag:- feature_flag_serializer = FeatureFlagSerializer(- existing_flag, data=flag_data, partial=True, context=context- )- else:- feature_flag_serializer = FeatureFlagSerializer(data=flag_data, context=context)-try:- feature_flag_serializer.is_valid(raise_exception=True)- saved_flag = feature_flag_serializer.save(team_id=target_project_id)+ # The copied payload holds the source flag's fields, so the target project's own+ # tag and evaluation context requirements cannot apply to it.+ copy_exemption = {"skip_team_flag_requirements": True}+ if existing_flag:+ saved_flag = update_flag(+ existing_flag,+ flag_data,+ team=target_team,+ user=user,+ request=request,+ serializer_context=copy_exemption,+ )+ else:+ saved_flag = create_flag(+ flag_data, team=target_team, user=user, request=request, serializer_context=copy_exemption+ )if target_flag_access_context is not None:target_flag_access_context.flags_by_key[source_flag.key] = saved_flagexcept IntegrityError as e:@@ -1375,10 +1378,8 @@ class OrganizationFeatureFlagView("It was left unchanged.") from eraise- except Exception as e:- if feature_flag_serializer.errors:- raise ValueError(feature_flag_serializer.errors) from e- raise+ except DRFValidationError as e:+ raise ValueError(e.detail) from efinally:request.method = original_request_method@@ -1421,7 +1422,12 @@ class OrganizationFeatureFlagView()schedule_copy_error = str(e)- result = dict(feature_flag_serializer.data)+ # Neither branch reaches here redacted: FeatureFlagSerializer.create() never redacts, and+ # update_flag reloads the stored ciphertext over the redaction update() did. Redact both the+ # way every other flag read path does, so only a personal API key sees the payloads.+ self._redact_encrypted_payloads(request, saved_flag)+ copy_context = {"request": request, "team_id": target_team.id, "project_id": target_project_id}+ result = dict(serialize_flags([saved_flag], context=copy_context)[0])result["team_id"] = saved_flag.team_idresult["updated_existing"] = existing_flag is not Noneif schedule_copy_error:diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex fed6c6f24b54..04097447e97e 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -167,106 +167,6 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."event_retention_months",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."llm_gateway_overspend_allowance_usd",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- ORDER BY "posthog_team"."id" ASC- LIMIT 1- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -311,7 +211,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -341,7 +241,7 @@AND "posthog_team"."project_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -440,7 +340,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -465,6 +365,25 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19+ '''+ SELECT "posthog_integration"."id",+ "posthog_integration"."team_id",+ "posthog_integration"."kind",+ "posthog_integration"."integration_id",+ "posthog_integration"."config",+ "posthog_integration"."sensitive_config",+ "posthog_integration"."repository_cache",+ "posthog_integration"."repository_cache_updated_at",+ "posthog_integration"."errors",+ "posthog_integration"."created_at",+ "posthog_integration"."created_by_id"+ FROM "posthog_integration"+ WHERE ("posthog_integration"."kind" = 'vercel'+ AND "posthog_integration"."team_id" = 99999)+ LIMIT 21+ '''+# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2'''SELECT "posthog_organization"."id",@@ -511,25 +430,6 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.20- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."repository_cache",- "posthog_integration"."repository_cache_updated_at",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -574,7 +474,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21'''SELECT "posthog_organizationintegration"."id","posthog_organizationintegration"."organization_id",@@ -591,7 +491,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -636,7 +536,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -681,7 +581,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -726,7 +626,7 @@WHERE "posthog_survey"."linked_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25'''SELECT "posthog_earlyaccessfeature"."id","posthog_earlyaccessfeature"."team_id",@@ -744,7 +644,7 @@WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -798,7 +698,96 @@LIMIT 21'''# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27+ '''+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at",+ "ee_accesscontrol"."updated_at",+ "posthog_team"."organization_id" AS "_team_organization_id"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")+ WHERE (("ee_accesscontrol"."organization_member_id" IS NULL+ AND "ee_accesscontrol"."resource" = 'feature_flag'+ AND "ee_accesscontrol"."resource_id" = '99999'+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" IN+ (SELECT U0."id" AS "id"+ FROM "posthog_team" U0+ WHERE U0."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid))+ OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999+ AND "ee_accesscontrol"."resource" = 'feature_flag'+ AND "ee_accesscontrol"."resource_id" = '99999'+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" IN+ (SELECT U0."id" AS "id"+ FROM "posthog_team" U0+ WHERE U0."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)))+ '''+# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."uses_most_specific_access_resolution",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."read_only_mcp_access",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."has_active_subscription",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -828,7 +817,7 @@AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -882,7 +871,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -936,7 +925,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31'''SELECT 1 AS "a"FROM "posthog_team"@@ -948,7 +937,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32'''SELECT "posthog_featureflagevaluationcontext"."id","posthog_featureflagevaluationcontext"."feature_flag_id",@@ -964,7 +953,7 @@WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 5aa386d24a1f..780f331f7c81 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -23,6 +23,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.approvals.backend.models import ChangeRequestfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import sort_cohorts_topologicallyfrom products.dashboards.backend.api.dashboard import Dashboard@@ -34,7 +35,11 @@ from products.feature_flags.backend.api.organization_feature_flag import (TARGET_COPY_PERMISSION_ERROR,OrganizationFeatureFlagView,)-from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE+from products.feature_flags.backend.encrypted_flag_payloads import (+ REDACTED_PAYLOAD_VALUE,+ encrypt_flag_payloads,+ get_decrypted_flag_payload,+)from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChangefrom products.surveys.backend.models import Survey@@ -445,6 +450,32 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):]self.organization.save()+ @parameterized.expand(["evaluation_contexts", "tags"])+ def test_copy_succeeds_when_target_requires_flag_metadata(self, requirement):+ from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig++ if requirement == "evaluation_contexts":+ self.team_2.require_evaluation_contexts = True+ self.team_2.save()+ else:+ TeamFeatureFlagPolicyConfig.objects.update_or_create(team=self.team_2, defaults={"require_tags": True})++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": self.feature_flag_to_copy.key,+ "from_project": self.feature_flag_to_copy.team_id,+ "target_project_ids": [self.team_2.id],+ }++ # The evaluation contexts requirement sits behind FLAG_EVALUATION_TAGS, so without this+ # the contexts case would pass whether or not the copy is exempt.+ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self.client.post(url, data)++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["failed"] == []+ assert FeatureFlag.objects.filter(team=self.team_2, key=self.feature_flag_key).exists()+@snapshot_postgres_queriesdef test_copy_feature_flag_create_new(self):url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"@@ -1219,7 +1250,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):real_save = FeatureFlagSerializer.savedef gated_save(serializer_self, **kwargs):- if kwargs.get("team_id") == self.team_2.id:+ if serializer_self.context.get("team_id") == self.team_2.id:raise ApprovalRequired(change_request=change_request,message="Approval required",@@ -1925,17 +1956,59 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):self.assertEqual(flag_response["has_encrypted_payloads"], True)self.assertEqual(flag_response["key"], encrypted_flag.key)+ self.assertEqual(flag_response["filters"]["payloads"]["true"], REDACTED_PAYLOAD_VALUE)+# Verify the flag in the database has encrypted payloadscopied_flag = FeatureFlag.objects.get(key=encrypted_flag.key, team=target_project)self.assertTrue(copied_flag.is_remote_configuration)self.assertTrue(copied_flag.has_encrypted_payloads)# Verify the encrypted payload can be decrypted back to the original value- from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payload-decrypted_payload = get_decrypted_flag_payload(copied_flag.filters["payloads"]["true"], should_decrypt=True)self.assertEqual(decrypted_payload, '{"key": "secret_value"}')+ def test_copy_encrypted_payloads_flag_over_existing_flag_redacts_the_response(self):+ target_project = self.team_2++ source_filters = {+ "groups": [{"rollout_percentage": 100}],+ "payloads": {"true": '{"key": "secret_value"}'},+ }+ encrypt_flag_payloads({"has_encrypted_payloads": True, "filters": source_filters})+ encrypted_flag = FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="encrypted-flag",+ filters=source_filters,+ is_remote_configuration=True,+ has_encrypted_payloads=True,+ )++ target_filters = {+ "groups": [{"rollout_percentage": 100}],+ "payloads": {"true": '{"key": "target_value"}'},+ }+ encrypt_flag_payloads({"has_encrypted_payloads": True, "filters": target_filters})+ FeatureFlag.objects.create(+ team=target_project,+ created_by=self.user,+ key=encrypted_flag.key,+ filters=target_filters,+ is_remote_configuration=True,+ has_encrypted_payloads=True,+ )++ response = self._post_copy_flag(encrypted_flag, [target_project.id])++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ flag_response = response.json()["success"][0]+ self.assertEqual(flag_response["updated_existing"], True)+ self.assertEqual(flag_response["filters"]["payloads"]["true"], REDACTED_PAYLOAD_VALUE)++ copied_flag = FeatureFlag.objects.get(key=encrypted_flag.key, team=target_project)+ stored_payload = get_decrypted_flag_payload(copied_flag.filters["payloads"]["true"], should_decrypt=True)+ self.assertEqual(stored_payload, '{"key": "secret_value"}')+def test_copy_encrypted_payloads_flag_to_multiple_projects(self):"""Test that copying a flag with encrypted payloads to multiple projects works correctly."""from products.feature_flags.backend.encrypted_flag_payloads import (@@ -3061,6 +3134,25 @@ class TestOrganizationFeatureFlagCopyPersonalAPIKey(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN+ def test_personal_api_key_receives_the_decrypted_payloads(self):+ filters = {"groups": [{"rollout_percentage": 100}], "payloads": {"true": '{"key": "secret_value"}'}}+ encrypt_flag_payloads({"has_encrypted_payloads": True, "filters": filters})+ FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="encrypted-key-to-copy",+ filters=filters,+ is_remote_configuration=True,+ has_encrypted_payloads=True,+ )+ self.body["feature_flag_key"] = "encrypted-key-to-copy"+ value = self._create_key(scopes=["feature_flag:write"])++ response = self._post_with_key(value)++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["success"][0]["filters"]["payloads"]["true"] == '{"key": "secret_value"}'+class TestOrganizationFeatureFlagCopySchedules(APIBaseTest):def setUp(self):@@ -3909,6 +4001,10 @@ class TestOrganizationFeatureFlagCopyApprovalGate(APIBaseTest):assert body["failed"][0]["project_id"] == self.team_2.idassert not FeatureFlag.objects.filter(team=self.team_2, key=self.source_flag.key).exists()+ # The reported change request has to be one an approver can still act on.+ assert body["failed"][0]["approval_pending"] is True+ assert ChangeRequest.objects.filter(pk=body["failed"][0]["change_request_id"]).exists()+def test_copy_active_flag_onto_existing_active_target_is_gated(self, _mock_enabled):# Existing destination flag is enabled via update() — covered by Task 2; assert it here too.existing = FeatureFlag.objects.create(