Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): enforce copy_flags target-project cap and add throttling (#70916)

Phil Haackdba9319274d8
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.md
index d92cc3380e74..50bbc5584641 100644
--- a/docs/internal/feature-flags/django-api-endpoints.md
+++ b/docs/internal/feature-flags/django-api-endpoints.md
@@ -70,6 +70,7 @@ Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked
`copy_flags` requires editor access to `feature_flag` in each target project, not just visibility.
A caller who can see a project but can't edit flags there gets a `failed` entry for that target instead of a copy.
+`target_project_ids` is capped at `MAX_COPY_FLAGS_TARGET_PROJECTS` (50) per call, and the endpoint has its own burst/sustained throttles since each target project can create cohorts and a flag.
## Key actions in detail
diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
index b1fead9dbfcc..c51b2bf82c27 100644
--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
@@ -31,6 +31,8 @@ export interface BulkDeleteResult {
}
export const BULK_COPY_MAX_FLAGS = 100
+// Mirrors MAX_COPY_FLAGS_TARGET_PROJECTS in
+// products/feature_flags/backend/api/organization_feature_flag.py, which rejects more. Keep in sync.
export const BULK_COPY_MAX_TARGET_PROJECTS = 50
export interface BulkCopyParams {
@@ -115,7 +117,9 @@ function aggregateCopyResponse(
): { copied: BulkCopyResult['copied'][number] | null; failed: BulkCopyFailure[]; warnings: string[] } {
// Copied targets are inferred as requested-minus-failed (robust to success items
// missing team_id during deploy skew); overwrites come from the per-item flag.
- const failedProjectIds = new Set(response.failed.map((entry) => entry.project_id))
+ const failedProjectIds = new Set(
+ response.failed.map((entry) => entry.project_id).filter((id): id is number => id != null)
+ )
const copiedProjectIds = targetProjectIds.filter((id) => !failedProjectIds.has(id))
const updatedProjectIds = response.success
.filter((item) => item.updated_existing && item.team_id != null)
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 6b27b7fdaa3f..3dd82fbfbbce 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -448,6 +448,29 @@ class ClickHouseSustainedRateThrottle(PersonalApiKeyRateThrottle):
rate = "1200/hour"
+# copy_flags fans out to up to 50 target projects per call, creating a feature flag (and any
+# missing cohorts) in each one, a much heavier write than most endpoints, so it gets its own
+# tighter budget instead of the general per-project Burst/SustainedRateThrottle. It's a plain
+# Postgres write path (no ClickHouse), so it doesn't need the ClickHouse*RateThrottle pair.
+# PersonalApiKeyOrUserRateThrottle applies regardless of auth method, covering the
+# session-authenticated bulk-copy UI too. That UI (frontend/src/scenes/feature-flags/
+# flagSelectionLogic.ts) awaits one copy_flags call per flag, sequentially, for up to 100 flags
+# in one operation, and does not retry on 429, so the burst rate has to clear a full legitimate
+# session (which can complete in well under a minute when each call is fast) without tripping.
+class CopyFlagsBurstRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ # 120/minute clears a full 100-call session with headroom even if every call returns quickly,
+ # while still catching a tight scripted loop well beyond normal bulk-copy usage.
+ scope = "copy_flags_burst"
+ rate = "120/minute"
+
+
+class CopyFlagsSustainedRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ # Bounds an hour to a couple of full bulk-copy sessions plus retries, well short of what
+ # sustained abuse could rack up unthrottled.
+ scope = "copy_flags_sustained"
+ rate = "300/hour"
+
+
class _AIThrottleBase(UserRateThrottle):
action_name: str
diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.py
index 41b05c085999..6304a4460064 100644
--- a/products/feature_flags/backend/api/organization_feature_flag.py
+++ b/products/feature_flags/backend/api/organization_feature_flag.py
@@ -22,6 +22,7 @@ from posthog.api.utils import ErrorResponseSerializer, action
from posthog.constants import AvailableFeature
from posthog.models import Team, User
from posthog.models.filters.filter import Filter
+from posthog.rate_limit import CopyFlagsBurstRateThrottle, CopyFlagsSustainedRateThrottle
from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
from posthog.user_permissions import UserPermissions
from posthog.utils import safe_int
@@ -100,13 +101,20 @@ class FeatureFlagCopySourceContext:
schedule_dependency_contexts_by_id: dict[int, ScheduledChangeDependencyContext]
+# Each target project can create cohorts and a feature flag, so this bounds how much work a
+# single copy_flags call can fan out to. Enforced by CopyFlagsRequestSerializer's max_length
+# (checked via serializer.is_valid()); shared with the frontend's BULK_COPY_MAX_TARGET_PROJECTS
+# in frontend/src/scenes/feature-flags/flagSelectionLogic.ts so the two can't drift apart.
+MAX_COPY_FLAGS_TARGET_PROJECTS = 50
+
+
class CopyFlagsRequestSerializer(serializers.Serializer):
feature_flag_key = serializers.CharField(required=True, help_text="Key of the feature flag to copy")
from_project = serializers.IntegerField(required=True, help_text="Source project ID to copy the flag from")
target_project_ids = serializers.ListField(
child=serializers.IntegerField(),
required=True,
- max_length=50,
+ max_length=MAX_COPY_FLAGS_TARGET_PROJECTS,
min_length=1,
help_text="List of target project IDs to copy the flag to",
)
@@ -181,7 +189,7 @@ class CopyFlagsDependencyRequirementsRequestSerializer(serializers.Serializer):
target_project_ids = serializers.ListField(
child=serializers.IntegerField(),
required=True,
- max_length=50,
+ max_length=MAX_COPY_FLAGS_TARGET_PROJECTS,
min_length=1,
help_text="List of target project IDs to check dependency copy eligibility for",
)
@@ -437,7 +445,17 @@ class OrganizationFeatureFlagView(
403: OpenApiResponse(response=ErrorResponseSerializer),
},
)
- @action(detail=False, methods=["post"], url_path="copy_flags", required_scopes=["feature_flag:write"])
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="copy_flags",
+ required_scopes=["feature_flag:write"],
+ # See CopyFlagsBurstRateThrottle in posthog/rate_limit.py for why this needs its own throttle pair.
+ throttle_classes=[
+ CopyFlagsBurstRateThrottle,
+ CopyFlagsSustainedRateThrottle,
+ ],
+ )
def copy_flags(self, request, *args, **kwargs):
serializer = CopyFlagsRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
@@ -452,6 +470,7 @@ class OrganizationFeatureFlagView(
user_permissions = UserPermissions(user=user)
accessible_team_ids = set(user_permissions.team_ids_visible_for_user)
+ # Fetch the flag to copy
try:
flag_to_copy = self._get_source_flag(feature_flag_key, from_project, accessible_team_ids)
except FeatureFlag.DoesNotExist:
@@ -494,7 +513,6 @@ class OrganizationFeatureFlagView(
}
)
continue
-
try:
with transaction.atomic():
target_flag_access_context = (
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.py
index 9cab7c8c9780..1c29c016075d 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
@@ -30,6 +30,7 @@ from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.api.organization_feature_flag import (
EXISTING_TARGET_SCHEDULE_DEPENDENCY_WARNING,
+ MAX_COPY_FLAGS_TARGET_PROJECTS,
TARGET_COPY_PERMISSION_ERROR,
OrganizationFeatureFlagView,
)
@@ -2844,6 +2845,97 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):
self.assertNotIn("hidden-child-dependency", response.content.decode())
self.assertFalse(FeatureFlag.objects.filter(team=self.team_2, key=flag_to_copy.key).exists())
+ def test_copy_feature_flag_too_many_target_projects(self):
+ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"
+ # One more than the cap. team_2 is a real, writable target, included to prove it gets
+ # nothing even though it would otherwise succeed on its own.
+ target_project_ids = [*range(10_000, 10_000 + MAX_COPY_FLAGS_TARGET_PROJECTS), self.team_2.id]
+ data = {
+ "feature_flag_key": self.feature_flag_key,
+ "from_project": self.team_1.id,
+ "target_project_ids": target_project_ids,
+ }
+ response = self.client.post(url, data)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "target_project_ids")
+ self.assertEqual(response.json()["code"], "max_length")
+ self.assertFalse(FeatureFlag.objects.filter(key=self.feature_flag_key, team_id=self.team_2.id).exists())
+
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("posthog.rate_limit.CopyFlagsBurstRateThrottle.rate", new="1/minute")
+ def test_copy_feature_flag_throttles_session_authenticated_requests(self, *_args):
+ # CopyFlagsBurstRateThrottle subclasses PersonalApiKeyOrUserRateThrottle, which applies
+ # regardless of auth method, so it must catch the test client's session-authenticated
+ # calls too. The patched rate makes the second request trip it deterministically.
+ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"
+ data = {
+ "feature_flag_key": self.feature_flag_key,
+ "from_project": self.team_1.id,
+ "target_project_ids": [self.team_2.id],
+ }
+
+ first = self.client.post(url, data)
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+
+ second = self.client.post(url, data)
+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_copy_feature_flag_overwrite_denied_by_object_level_access_control_fails(self):
+ from posthog.constants import AvailableFeature
+
+ from ee.models.rbac.access_control import AccessControl
+
+ self.organization.available_product_features = [
+ {
+ "name": AvailableFeature.ACCESS_CONTROL,
+ "key": AvailableFeature.ACCESS_CONTROL,
+ }
+ ]
+ self.organization.save()
+
+ # A flag with this key already exists in team_2, created by a different user so the
+ # creator-always-visible exception doesn't grant self.user access to it.
+ other_user = self._create_user("[email protected]")
+ existing_flag = FeatureFlag.objects.create(
+ team=self.team_2,
+ created_by=other_user,
+ key=self.feature_flag_key,
+ filters={"groups": [{"rollout_percentage": 10}]},
+ )
+
+ # Deny editor access to this specific flag at the object level (team_2 stays visible).
+ AccessControl.objects.create(
+ team=self.team_2,
+ resource="feature_flag",
+ resource_id=str(existing_flag.id),
+ organization_member=None,
+ role=None,
+ access_level="viewer",
+ )
+
+ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"
+ data = {
+ "feature_flag_key": self.feature_flag_key,
+ "from_project": self.team_1.id,
+ "target_project_ids": [self.team_2.id],
+ }
+ response = self.client.post(url, data)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["success"]), 0)
+ self.assertEqual(
+ response.json()["failed"],
+ [
+ {
+ "project_id": self.team_2.id,
+ "error_message": TARGET_COPY_PERMISSION_ERROR,
+ }
+ ],
+ )
+ existing_flag.refresh_from_db()
+ self.assertEqual(existing_flag.filters, {"groups": [{"rollout_percentage": 10}]})
+
class TestOrganizationFeatureFlagCopyPersonalAPIKey(APIBaseTest):
"""Verify the `copy_flags` action accepts personal API keys with `feature_flag:write` scope.