: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(flags): store a request blocklist of hosts and IPs per project (#121647)
Gustavo H. Strassburgerc4e006e9b1cd
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 748eca53ef20..5a655be148bd 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -1841,6 +1841,18 @@ export interface TeamWorkflowsConfigApi {export interface TeamFeatureFlagPolicyConfigApi {/** When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag. */require_tags?: boolean+ /**+ * Domains to block from feature flag requests (/flags and /decide), up to 100. A domain also covers its subdomains. It is compared with the Origin header, or with the Referer header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is reduced to its domain, and an internationalized domain is stored as punycode.+ * @maxItems 1000+ * @items.maxLength 2000+ */+ blocked_hosts?: string[]+ /**+ * IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (/flags and /decide), up to 100. Ranges can be /8 or narrower for IPv4 and /16 or narrower for IPv6. Entries are stored in canonical form without duplicates, and an IPv4-mapped IPv6 address is stored as IPv4.+ * @maxItems 1000+ * @items.maxLength 2000+ */+ blocked_ips?: string[]}/**diff --git a/posthog/api/team/team_config.py b/posthog/api/team/team_config.pyindex 4dc308f91d24..6074134a1b18 100644--- a/posthog/api/team/team_config.py+++ b/posthog/api/team/team_config.py@@ -17,6 +17,16 @@ from products.customer_analytics.backend.facade.account_property_pins import (from products.customer_analytics.backend.facade.contracts import PinnedAccountPropertyfrom products.customer_analytics.backend.facade.enums import AccountPropertyPinKindfrom products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig+from products.feature_flags.backend.facade.request_blocklist import (+ MAX_BLOCKED_HOSTS,+ MAX_BLOCKED_IPS,+ MAX_BLOCKLIST_INPUT_ENTRIES,+ MIN_BLOCKED_IPV4_PREFIX,+ MIN_BLOCKED_IPV6_PREFIX,+ BlocklistEntryError,+ normalize_blocked_hosts,+ normalize_blocked_ips,+)from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.replay_vision.backend.facade.workflow_scan_limits import (MAX_SELF_SERVE_WORKFLOW_SCAN_RATE_CAP_PER_DAY,@@ -452,9 +462,46 @@ class TeamFeatureFlagPolicyConfigSerializer(serializers.ModelSerializer, UserAcc),)+ # allow_blank lets a client send a list split from pasted lines, because the normalizers drop blank entries.+ # The normalizers own the MAX_BLOCKED_* caps, because they count entries after dropping blanks and duplicates.+ blocked_hosts = serializers.ListField(+ child=serializers.CharField(max_length=2000, allow_blank=True),+ max_length=MAX_BLOCKLIST_INPUT_ENTRIES,+ required=False,+ help_text=(+ f"Domains to block from feature flag requests (/flags and /decide), up to {MAX_BLOCKED_HOSTS}. "+ "A domain also covers its subdomains. It is compared with the Origin header, or with the Referer "+ "header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is "+ "reduced to its domain, and an internationalized domain is stored as punycode."+ ),+ )+ blocked_ips = serializers.ListField(+ child=serializers.CharField(max_length=2000, allow_blank=True),+ max_length=MAX_BLOCKLIST_INPUT_ENTRIES,+ required=False,+ help_text=(+ f"IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (/flags and /decide), "+ f"up to {MAX_BLOCKED_IPS}. Ranges can be /{MIN_BLOCKED_IPV4_PREFIX} or narrower for IPv4 and "+ f"/{MIN_BLOCKED_IPV6_PREFIX} or narrower for IPv6. Entries are stored in canonical form without "+ "duplicates, and an IPv4-mapped IPv6 address is stored as IPv4."+ ),+ )+class Meta:model = TeamFeatureFlagPolicyConfig- fields = ["require_tags"]+ fields = ["require_tags", "blocked_hosts", "blocked_ips"]++ def validate_blocked_hosts(self, value: list[str]) -> list[str]:+ try:+ return normalize_blocked_hosts(value)+ except BlocklistEntryError as error:+ raise serializers.ValidationError(str(error))++ def validate_blocked_ips(self, value: list[str]) -> list[str]:+ try:+ return normalize_blocked_ips(value)+ except BlocklistEntryError as error:+ raise serializers.ValidationError(str(error))class TeamCustomerAnalyticsPinnedAccountPropertySerializer(serializers.Serializer):diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.pyindex 7b2128d6e39f..81a6eb41528a 100644--- a/posthog/api/test/test_team_project_differential.py+++ b/posthog/api/test/test_team_project_differential.py@@ -204,7 +204,11 @@ FIELD_VALUES: dict[str, Any] = {"marketing_analytics_config": {"attribution_window_days": 14},"customer_analytics_config": {"activity_event": "$pageview"},"workflows_config": {"capture_workflows_engagement_events": True},- "feature_flag_policy_config": {"require_tags": True},+ "feature_flag_policy_config": {+ "require_tags": True,+ "blocked_hosts": ["https://Example.com/page"],+ "blocked_ips": ["198.51.100.42/24"],+ },"onboarding_tasks": {"task_x": "completed"},"base_currency": "EUR","web_analytics_pre_aggregated_tables_enabled": True,diff --git a/posthog/storage/team_metadata_cache.py b/posthog/storage/team_metadata_cache.pyindex d0e17fdbdccb..ff292710e88e 100644--- a/posthog/storage/team_metadata_cache.py+++ b/posthog/storage/team_metadata_cache.py@@ -65,6 +65,7 @@ from posthog.storage.hypercache_manager import (get_cache_stats as get_cache_stats_generic,)+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.feature_flags.backend.models.team_feature_flags_config import (PropertyMatchingVersion,TeamFeatureFlagsConfig,@@ -159,10 +160,26 @@ def _serialize_team_field(field: str, value: Any) -> Any:return value+REQUEST_BLOCKLIST_FIELDS = ("flags_blocked_hosts", "flags_blocked_ips")+++def _load_request_blocklists(team_ids: list[int]) -> dict[int, dict[str, list[str]]]:+ """Map each team id to its request blocklist cache fields, with empty lists when it has no policy row."""+ blocklists: dict[int, dict[str, list[str]]] = {+ team_id: {"flags_blocked_hosts": [], "flags_blocked_ips": []} for team_id in team_ids+ }+ for team_id, blocked_hosts, blocked_ips in TeamFeatureFlagPolicyConfig.objects.filter(+ team_id__in=team_ids+ ).values_list("team_id", "blocked_hosts", "blocked_ips"):+ blocklists[team_id] = {"flags_blocked_hosts": blocked_hosts, "flags_blocked_ips": blocked_ips}+ return blocklists++def _serialize_team_to_metadata(team: Team,minimal_flag_called_events: bool | None = None,property_matching_version: int | None = None,+ request_blocklist: dict[str, list[str]] | None = None,) -> dict[str, Any]:"""Serialize a Team object to metadata dictionary.@@ -173,6 +190,8 @@ def _serialize_team_to_metadata(batch callers avoid an N+1 query. If None, this looks it up itself.property_matching_version: Pre-fetched property matching semantics version. If None,this looks it up with the other feature flags config value.+ request_blocklist: Pre-fetched entry from _load_request_blocklists. If None, this+ looks it up itself.Returns:Dictionary containing full team metadata@@ -202,6 +221,10 @@ def _serialize_team_to_metadata(metadata["minimal_flag_called_events"] = minimal_flag_called_events or Falsemetadata["property_matching_version"] = property_matching_version or PropertyMatchingVersion.LEGACY+ if request_blocklist is None:+ request_blocklist = _load_request_blocklists([team.id])[team.id]+ metadata.update(request_blocklist)+return metadata@@ -225,11 +248,13 @@ def _batch_load_team_metadata(teams: list[Team]) -> dict[int, dict[str, Any]]:team_id__in=[team.id for team in teams]).values_list("team_id", "minimal_flag_called_events", "property_matching_version")}+ blocklist_by_team_id = _load_request_blocklists([team.id for team in teams])return {team.id: _serialize_team_to_metadata(team,minimal_flag_called_events=config_by_team_id.get(team.id, (False, PropertyMatchingVersion.LEGACY))[0],property_matching_version=config_by_team_id.get(team.id, (False, PropertyMatchingVersion.LEGACY))[1],+ request_blocklist=blocklist_by_team_id[team.id],)for team in teams}@@ -352,11 +377,14 @@ def verify_team_metadata("project_name","minimal_flag_called_events","property_matching_version",+ *REQUEST_BLOCKLIST_FIELDS,}diffs = []for key in fields_to_check:db_val = db_data.get(key)- cached_val = cached_data.get(key)+ # A blob without the blocklist keys reads the same as empty lists in the flags service,+ # so it only needs a fix when the team actually has entries.+ cached_val = cached_data.get(key, [] if key in REQUEST_BLOCKLIST_FIELDS else None)if db_val != cached_val:diffs.append({"field": key, "db_value": db_val, "cached_value": cached_val})diff --git a/posthog/storage/test/test_team_metadata_cache.py b/posthog/storage/test/test_team_metadata_cache.pyindex c1e07764203c..088d91e5b53b 100644--- a/posthog/storage/test/test_team_metadata_cache.py+++ b/posthog/storage/test/test_team_metadata_cache.py@@ -27,6 +27,7 @@ from posthog.storage.team_metadata_cache import ()from posthog.tasks.team_metadata import update_team_metadata_cache_task+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig@@ -448,6 +449,8 @@ class TestVerifyTeamMetadata(BaseTest):# TeamFeatureFlagsConfig fields are tracked separately from TEAM_METADATA_FIELDS.("minimal_flag_called_events", True),("property_matching_version", 2),+ ("flags_blocked_hosts", ["example.com"]),+ ("flags_blocked_ips", ["203.0.113.7"]),])@patch("posthog.storage.team_metadata_cache.get_team_metadata")@@ -466,6 +469,23 @@ class TestVerifyTeamMetadata(BaseTest):self.assertEqual(result["issue"], "DATA_MISMATCH")self.assertIn(field, result["diff_fields"])+ @parameterized.expand([("without_entries", [], "match"), ("with_entries", ["example.com"], "mismatch")])+ @patch("posthog.storage.team_metadata_cache.get_team_metadata")+ def test_verify_reads_missing_blocklist_keys_as_empty(+ self, _name, blocked_hosts, expected_status, mock_get_metadata+ ):+ from posthog.storage.team_metadata_cache import _serialize_team_to_metadata++ TeamFeatureFlagPolicyConfig.objects.create(team=self.team, blocked_hosts=blocked_hosts)+ cached_data = _serialize_team_to_metadata(self.team)+ del cached_data["flags_blocked_hosts"]+ del cached_data["flags_blocked_ips"]+ mock_get_metadata.return_value = cached_data++ result = verify_team_metadata(self.team)++ self.assertEqual(result["status"], expected_status)+@patch("posthog.storage.team_metadata_cache.get_team_metadata")def test_verify_returns_miss_when_no_cached_data(self, mock_get_metadata):"""Verify returns cache miss when no data is cached."""@@ -487,6 +507,8 @@ class TestFeatureFlagsConfigInMetadata(BaseTest):self.assertIs(metadata["minimal_flag_called_events"], False)self.assertEqual(metadata["property_matching_version"], 1)+ self.assertEqual(metadata["flags_blocked_hosts"], [])+ self.assertEqual(metadata["flags_blocked_ips"], [])def test_reflects_gated_config_row(self):from posthog.storage.team_metadata_cache import _serialize_team_to_metadata@@ -509,9 +531,16 @@ class TestFeatureFlagsConfigInMetadata(BaseTest):team=gated_team,defaults={"minimal_flag_called_events": True, "property_matching_version": 2},)+ TeamFeatureFlagPolicyConfig.objects.create(+ team=gated_team, blocked_hosts=["example.com"], blocked_ips=["203.0.113.0/24"]+ )ungated_team = self.organization.teams.create(name="Ungated team")+ teams = list(+ Team.objects.select_related("organization", "project").filter(id__in=[gated_team.id, ungated_team.id])+ )- batch_result = _batch_load_team_metadata([gated_team, ungated_team])+ with self.assertNumQueries(2):+ batch_result = _batch_load_team_metadata(teams)self.assertEqual(batch_result[gated_team.id]["minimal_flag_called_events"],@@ -525,6 +554,13 @@ class TestFeatureFlagsConfigInMetadata(BaseTest):self.assertEqual(batch_result[gated_team.id]["property_matching_version"], 2)self.assertIs(batch_result[ungated_team.id]["minimal_flag_called_events"], False)self.assertEqual(batch_result[ungated_team.id]["property_matching_version"], 1)+ for team in (gated_team, ungated_team):+ single_result = _serialize_team_to_metadata(team)+ for field in ("flags_blocked_hosts", "flags_blocked_ips"):+ self.assertEqual(batch_result[team.id][field], single_result[field])+ self.assertEqual(batch_result[gated_team.id]["flags_blocked_hosts"], ["example.com"])+ self.assertEqual(batch_result[gated_team.id]["flags_blocked_ips"], ["203.0.113.0/24"])+ self.assertEqual(batch_result[ungated_team.id]["flags_blocked_hosts"], [])@override_settings(FLAGS_REDIS_URL="redis://test:6379/0")diff --git a/posthog/tasks/team_metadata.py b/posthog/tasks/team_metadata.pyindex e859c78f9ec7..bf96fc3af790 100644--- a/posthog/tasks/team_metadata.py+++ b/posthog/tasks/team_metadata.py@@ -29,6 +29,8 @@ from posthog.storage.team_metadata_cache import ()from posthog.tasks.utils import CeleryQueue+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig+logger = structlog.get_logger(__name__)@@ -145,20 +147,15 @@ def refresh_expiring_team_metadata_cache_entries() -> None:raise-@receiver(post_save, sender=Team)-def update_team_metadata_cache_on_save(sender: type[Team], instance: Team, created: bool, **kwargs: Any) -> None:- """Update team metadata cache when a Team is saved."""- if not settings.FLAGS_REDIS_URL:- return-+def _enqueue_team_metadata_update_on_commit(team_id: int) -> None:def enqueue_task() -> None:try:- update_team_metadata_cache_task.delay(instance.id)+ update_team_metadata_cache_task.delay(team_id)except Exception as e:_record_enqueue_failure()logger.exception("Failed to enqueue cache update task",- team_id=instance.id,+ team_id=team_id,error=str(e),)@@ -167,6 +164,40 @@ def update_team_metadata_cache_on_save(sender: type[Team], instance: Team, creattransaction.on_commit(enqueue_task)+def _any_field_may_have_changed(update_fields: frozenset[str] | None, fields: frozenset[str]) -> bool:+ """Whether a save could have touched any of `fields`.++ A `None` update_fields means a full save, where we can't tell, so we assume it might have.+ """+ return update_fields is None or not fields.isdisjoint(update_fields)+++@receiver(post_save, sender=Team)+def update_team_metadata_cache_on_save(sender: type[Team], instance: Team, created: bool, **kwargs: Any) -> None:+ """Update team metadata cache when a Team is saved."""+ if not settings.FLAGS_REDIS_URL:+ return++ _enqueue_team_metadata_update_on_commit(instance.id)+++@receiver(post_save, sender=TeamFeatureFlagPolicyConfig)+def update_team_metadata_cache_on_flag_policy_save(+ sender: type[TeamFeatureFlagPolicyConfig], instance: TeamFeatureFlagPolicyConfig, created: bool, **kwargs: Any+) -> None:+ """Refresh the cached team when its request blocklists change, because the flags service reads them from that cache."""+ if not settings.FLAGS_REDIS_URL:+ return+ # The first read of Team.feature_flag_policy_config creates an empty row, and the cache+ # already holds empty lists for a team without a row.+ if created and not instance.blocked_hosts and not instance.blocked_ips:+ return+ if not _any_field_may_have_changed(kwargs.get("update_fields"), frozenset({"blocked_hosts", "blocked_ips"})):+ return++ _enqueue_team_metadata_update_on_commit(instance.team_id)++@receiver(pre_delete, sender=Team)def clear_team_metadata_cache_on_delete(sender: type[Team], instance: Team, **kwargs: Any) -> None:"""Clear team metadata cache when a Team is deleted."""@@ -184,14 +215,6 @@ def _record_enqueue_failure() -> None:).inc()-def _name_may_have_changed(update_fields: frozenset[str] | None) -> bool:- """Whether a save could have touched the `name` field.-- A `None` update_fields means a full save, where we can't tell, so we assume it might have.- """- return update_fields is None or "name" in update_fields--def _enqueue_related_team_metadata_fanout(*, organization_id: int | None = None, project_id: int | None = None) -> None:try:update_related_teams_metadata_cache_task.delay(organization_id=organization_id, project_id=project_id)@@ -215,7 +238,7 @@ def update_team_metadata_cache_on_organization_save("""Refresh dependent team metadata caches when an organization is renamed."""if created or not settings.FLAGS_REDIS_URL:return- if not _name_may_have_changed(kwargs.get("update_fields")):+ if not _any_field_may_have_changed(kwargs.get("update_fields"), frozenset({"name"})):returntransaction.on_commit(lambda: _enqueue_related_team_metadata_fanout(organization_id=instance.id))@@ -228,7 +251,7 @@ def update_team_metadata_cache_on_project_save("""Refresh dependent team metadata caches when a project is renamed."""if created or not settings.FLAGS_REDIS_URL:return- if not _name_may_have_changed(kwargs.get("update_fields")):+ if not _any_field_may_have_changed(kwargs.get("update_fields"), frozenset({"name"})):returntransaction.on_commit(lambda: _enqueue_related_team_metadata_fanout(project_id=instance.id))diff --git a/posthog/tasks/test/test_team_metadata_signals.py b/posthog/tasks/test/test_team_metadata_signals.pyindex 072ab64d34da..93219d3ad375 100644--- a/posthog/tasks/test/test_team_metadata_signals.py+++ b/posthog/tasks/test/test_team_metadata_signals.py@@ -3,10 +3,14 @@ from unittest.mock import patchfrom django.test import override_settings+from parameterized import parameterized+from posthog.models.organization import Organizationfrom posthog.models.project import Projectfrom posthog.tasks.team_metadata import update_related_teams_metadata_cache_task+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig+@override_settings(FLAGS_REDIS_URL="redis://localhost:6379")class TestTeamMetadataInvalidationSignals(BaseTest):@@ -136,3 +140,50 @@ class TestOrgProjectDeleteCascadesToTeamClear(BaseTest):project.delete()self.assertIn(team_id, cleared_team_ids)+++@override_settings(FLAGS_REDIS_URL="redis://localhost:6379")+class TestFlagPolicyBlocklistCacheRefresh(BaseTest):+ @parameterized.expand(+ [+ ("create_with_entries", None, {"blocked_hosts": ["example.com"]}),+ ("set_on_existing_row", {}, {"blocked_hosts": ["example.com"], "blocked_ips": ["203.0.113.7"]}),+ (+ "clear_on_existing_row",+ {"blocked_hosts": ["example.com"], "blocked_ips": ["203.0.113.7"]},+ {"blocked_hosts": [], "blocked_ips": []},+ ),+ ]+ )+ def test_blocklist_save_refreshes_team_metadata_cache(+ self, _name: str, existing: dict[str, list[str]] | None, saved: dict[str, list[str]]+ ) -> None:+ config = None if existing is None else TeamFeatureFlagPolicyConfig.objects.create(team=self.team, **existing)++ with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_task:+ with self.captureOnCommitCallbacks(execute=True):+ if config is None:+ TeamFeatureFlagPolicyConfig.objects.create(team=self.team, **saved)+ else:+ for field, value in saved.items():+ setattr(config, field, value)+ config.save()++ mock_task.delay.assert_called_once_with(self.team.id)++ def test_creating_empty_flag_policy_does_not_refresh(self) -> None:+ with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_task:+ with self.captureOnCommitCallbacks(execute=True):+ TeamFeatureFlagPolicyConfig.objects.create(team=self.team)++ mock_task.delay.assert_not_called()++ def test_flag_policy_save_with_update_fields_outside_blocklist_does_not_refresh(self) -> None:+ config = TeamFeatureFlagPolicyConfig.objects.create(team=self.team, blocked_hosts=["example.com"])++ with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_task:+ with self.captureOnCommitCallbacks(execute=True):+ config.require_tags = True+ config.save(update_fields=["require_tags"])++ mock_task.delay.assert_not_called()diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex 9055a2ff3c95..6020eb2d9ff5 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -20023,6 +20023,8 @@ export namespace Schemas {}>;export type TeamFeatureFlagPolicyConfig = Partial<{require_tags: boolean;+ blocked_hosts: Array<string>;+ blocked_ips: Array<string>;}>;/*** A project and its settings, including the settings that live on its passthrough Team.diff --git a/products/feature_flags/backend/facade/request_blocklist.py b/products/feature_flags/backend/facade/request_blocklist.pynew file mode 100644index 000000000000..6b5387d049eb--- /dev/null+++ b/products/feature_flags/backend/facade/request_blocklist.py@@ -0,0 +1,121 @@+"""Validation and normalization for the per-team request blocklists on TeamFeatureFlagPolicyConfig.++The flags service trims hosts, strips a trailing dot, lowercases them, and skips invalid IP+entries. It applies no other rule, so every writer goes through these functions. Deliberately free of Django/DRF imports: the model module imports+the length limits at module level, and the serializer translates BlocklistEntryError.+"""++import ipaddress+from collections.abc import Iterable+from urllib.parse import urlsplit++import idna++# Caps each list so the flags service scans a short list on every /flags request.+MAX_BLOCKED_HOSTS = 100+MAX_BLOCKED_IPS = 100++# The broadest ranges a blocked IP entry may cover. A wider range blocks a large share of the+# internet, which is almost always a typo for a narrower one.+MIN_BLOCKED_IPV4_PREFIX = 8+MIN_BLOCKED_IPV6_PREFIX = 16++# Bounds the raw list a client sends, before the normalizers drop blanks and duplicates. It only+# guards against abuse, so that MAX_BLOCKED_HOSTS and MAX_BLOCKED_IPS apply to the unique entries.+MAX_BLOCKLIST_INPUT_ENTRIES = 1000++# Column widths. 253 is the DNS limit for a full domain name, which idna.encode enforces. 43 fits+# the longest canonical entry, an IPv6 address with no zero group to compress plus a two-digit+# prefix, such as "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe/127".+MAX_BLOCKED_HOST_LENGTH = 253+MAX_BLOCKED_IP_LENGTH = 43++_ALLOWED_SINGLE_LABEL_HOSTS = frozenset({"localhost"})+++class BlocklistEntryError(ValueError):+ """An entry for blocked_hosts or blocked_ips that cannot be stored. The message is user-facing."""+++def normalize_blocked_hosts(entries: Iterable[str]) -> list[str]:+ """Lowercase, deduplicate, and validate hostnames, keeping the order they were given in.++ A full URL is reduced to its hostname, because people often paste one from the browser.+ """+ hosts: dict[str, None] = {}+ for raw_entry in entries:+ entry = raw_entry.strip().lower()+ if not entry:+ continue+ invalid_error = BlocklistEntryError(+ f"'{raw_entry.strip()}' is not a valid domain. Enter a domain like example.com."+ )+ if "://" in entry:+ # Browsers read a backslash in a URL as a slash, so "https://example.com\@evil.com"+ # opens example.com. urlsplit reads it as part of the userinfo and returns evil.com.+ try:+ entry = urlsplit(entry.replace("\\", "/")).hostname or ""+ except ValueError:+ raise invalid_error+ entry = entry.rstrip(".")+ if entry.startswith("*."):+ raise BlocklistEntryError(+ f"Enter '{entry[2:]}' instead of '{entry}'. A domain already blocks all of its subdomains."+ )+ # Browsers send an internationalized domain in the Origin header as punycode. UTS 46 maps+ # ideographic full stops to ".", so strip the trailing dots again after the encoding.+ try:+ entry = idna.encode(entry, uts46=True, std3_rules=True).decode("ascii").rstrip(".")+ except idna.IDNAError:+ raise invalid_error+ if "." not in entry and entry not in _ALLOWED_SINGLE_LABEL_HOSTS:+ raise BlocklistEntryError(+ f"'{entry}' would block every domain that ends in .{entry}. Enter a full domain like example.com."+ )+ hosts[entry] = None+ if len(hosts) > MAX_BLOCKED_HOSTS:+ raise BlocklistEntryError(f"You can block up to {MAX_BLOCKED_HOSTS} domains.")+ return list(hosts)+++def normalize_blocked_ips(entries: Iterable[str]) -> list[str]:+ """Validate IP addresses and CIDR ranges and store them in canonical form, deduplicated.++ Host bits are dropped (`203.0.113.7/24` becomes `203.0.113.0/24`), and a single address is+ stored without its `/32` or `/128` suffix.+ """+ ips: dict[str, None] = {}+ for raw_entry in entries:+ entry = raw_entry.strip()+ if not entry:+ continue+ network: ipaddress.IPv4Network | ipaddress.IPv6Network | None+ try:+ network = ipaddress.ip_network(entry, strict=False)+ except ValueError:+ network = None+ # A client IP never carries an IPv6 zone ID (fe80::1%eth0), so a scoped entry can never match.+ if network is None or "%" in entry:+ raise BlocklistEntryError(+ f"'{entry}' is not a valid IP address or range. Enter an address like 203.0.113.7 or a range like 203.0.113.0/24."+ )+ # The flags service matches IPv4 clients against IPv4 entries only, so store a mapped+ # address (::ffff:203.0.113.7) as the IPv4 address it stands for.+ if (+ isinstance(network, ipaddress.IPv6Network)+ and network.prefixlen >= 96+ and network.network_address.ipv4_mapped is not None+ ):+ network = ipaddress.ip_network(f"{network.network_address.ipv4_mapped}/{network.prefixlen - 96}")+ min_prefix = MIN_BLOCKED_IPV4_PREFIX if network.version == 4 else MIN_BLOCKED_IPV6_PREFIX+ if network.prefixlen < min_prefix:+ raise BlocklistEntryError(+ f"'{entry}' covers too many addresses. IPv{network.version} ranges can be /{min_prefix} or narrower."+ )+ normalized = (+ str(network.network_address) if network.prefixlen == network.max_prefixlen else network.with_prefixlen+ )+ ips[normalized] = None+ if len(ips) > MAX_BLOCKED_IPS:+ raise BlocklistEntryError(f"You can block up to {MAX_BLOCKED_IPS} IP addresses or ranges.")+ return list(ips)diff --git a/products/feature_flags/backend/migrations/0023_teamfeatureflagpolicyconfig_blocked_hosts_and_ips.py b/products/feature_flags/backend/migrations/0023_teamfeatureflagpolicyconfig_blocked_hosts_and_ips.pynew file mode 100644index 000000000000..d5cf23f93a43--- /dev/null+++ b/products/feature_flags/backend/migrations/0023_teamfeatureflagpolicyconfig_blocked_hosts_and_ips.py@@ -0,0 +1,35 @@+# Generated by Django 5.2.18 on 2026-10-21 18:31++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0022_organizationfeatureflagsconfig"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamfeatureflagpolicyconfig",+ name="blocked_hosts",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=253),+ blank=True,+ db_default=[],+ default=list,+ size=None,+ ),+ ),+ migrations.AddField(+ model_name="teamfeatureflagpolicyconfig",+ name="blocked_ips",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=43),+ blank=True,+ db_default=[],+ default=list,+ size=None,+ ),+ ),+ ]diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txtindex 1e5329c29b7d..487ccf1e4c93 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0022_organizationfeatureflagsconfig+0023_teamfeatureflagpolicyconfig_blocked_hosts_and_ipsdiff --git a/products/feature_flags/backend/models/team_feature_flag_policy_config.py b/products/feature_flags/backend/models/team_feature_flag_policy_config.pyindex 424e21794cdd..2419170d0975 100644--- a/products/feature_flags/backend/models/team_feature_flag_policy_config.py+++ b/products/feature_flags/backend/models/team_feature_flag_policy_config.py@@ -1,16 +1,19 @@+from django.contrib.postgres.fields import ArrayFieldfrom django.db import models+from products.feature_flags.backend.facade.request_blocklist import MAX_BLOCKED_HOST_LENGTH, MAX_BLOCKED_IP_LENGTH+class TeamFeatureFlagPolicyConfig(models.Model):- """Customer-editable rules that guard how a team's members create flags.+ """Customer-editable feature flag rules for a team.Distinct from TeamFeatureFlagsConfig, which holds staff-only rollout switches and is neverexposed to customers. This one is reachable by project admins as `feature_flag_policy_config`on the team/project API.- These rules are bookkeeping, and they do not hold on every write path. The exemptions are- declared by the caller, and a path that builds a serializer context without `get_team` skips- the rules entirely: the organization-level flag copy and the approvals apply path both do.+ The require_tags rule is bookkeeping, and it does not hold on every write path. The exemptions+ are declared by the caller, and a path that builds a serializer context without `get_team` skips+ the rule entirely: the organization-level flag copy and the approvals apply path both do."""# db_constraint=False: a real FK constraint would take a SHARE ROW EXCLUSIVE@@ -27,6 +30,15 @@ class TeamFeatureFlagPolicyConfig(models.Model):# forms have no tag input and would otherwise dead-end.require_tags = models.BooleanField(default=False)+ # Saving does not normalize these lists, so every writer goes through facade.request_blocklist first.+ # db_default lets pods on the previous release insert rows without naming these columns.+ blocked_hosts = ArrayField(+ models.CharField(max_length=MAX_BLOCKED_HOST_LENGTH), default=list, blank=True, db_default=[]+ )+ blocked_ips = ArrayField(+ models.CharField(max_length=MAX_BLOCKED_IP_LENGTH), default=list, blank=True, db_default=[]+ )+def team_requires_flag_tags(team_id: int) -> bool:"""Whether this team requires tags on flags.diff --git a/products/feature_flags/backend/test/test_team_feature_flag_policy_config.py b/products/feature_flags/backend/test/test_team_feature_flag_policy_config.pyindex 3efc78f4271e..9d662ee9b65c 100644--- a/products/feature_flags/backend/test/test_team_feature_flag_policy_config.py+++ b/products/feature_flags/backend/test/test_team_feature_flag_policy_config.py@@ -1,15 +1,112 @@from posthog.test.base import APIBaseTest+from django.test import SimpleTestCase++from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import OrganizationMembership-+from posthog.models.activity_logging.activity_log import ActivityLog++from products.feature_flags.backend.facade.request_blocklist import (+ MAX_BLOCKED_HOST_LENGTH,+ MAX_BLOCKED_HOSTS,+ MAX_BLOCKED_IP_LENGTH,+ MAX_BLOCKED_IPS,+ BlocklistEntryError,+ normalize_blocked_hosts,+ normalize_blocked_ips,+)from products.feature_flags.backend.models.team_feature_flag_policy_config import (TeamFeatureFlagPolicyConfig,team_requires_flag_tags,)+class TestNormalizeBlockedHosts(SimpleTestCase):+ @parameterized.expand(+ [+ ("lowercases_and_trims", [" Example.COM. "], ["example.com"]),+ ("reduces_url_to_host", ["https://App.Example.com:8443/path?q=1"], ["app.example.com"]),+ ("dedupes_keeping_order", ["example.org", "example.com", "EXAMPLE.org"], ["example.org", "example.com"]),+ ("skips_blank_entries", ["", " ", "example.com"], ["example.com"]),+ ("accepts_ip_literal_host", ["203.0.113.7"], ["203.0.113.7"]),+ ("accepts_localhost", ["http://localhost:3000"], ["localhost"]),+ ("encodes_idn_as_punycode", ["Bücher.example"], ["xn--bcher-kva.example"]),+ ("keeps_punycode_unchanged", ["xn--bcher-kva.example"], ["xn--bcher-kva.example"]),+ ("strips_ideographic_trailing_dot", ["example.com\u3002", "ü.com\u3002"], ["example.com", "xn--tda.com"]),+ ("backslash_in_url_reads_as_slash", ["https://example.com\\@evil.com"], ["example.com"]),+ (+ "accepts_max_after_dedupe",+ [f"host{i}.example.com" for i in range(MAX_BLOCKED_HOSTS)] + ["HOST0.example.com"],+ [f"host{i}.example.com" for i in range(MAX_BLOCKED_HOSTS)],+ ),+ ]+ )+ def test_normalizes(self, _name: str, entries: list[str], expected: list[str]) -> None:+ assert normalize_blocked_hosts(entries) == expected++ @parameterized.expand(+ [+ ("wildcard", ["*.example.com"], "Enter 'example.com' instead"),+ ("path_without_scheme", ["example.com/path"], "is not a valid domain"),+ ("port_without_scheme", ["example.com:8080"], "is not a valid domain"),+ ("leading_hyphen_label", ["-example.com"], "is not a valid domain"),+ ("embedded_newline", ["example\n.com"], "is not a valid domain"),+ ("malformed_url", ["https://[example.com"], "is not a valid domain"),+ ("longer_than_253_chars", [".".join(["a" * 63] * 4)], "is not a valid domain"),+ ("invalid_idn_joiner", ["a\u200db.example"], "is not a valid domain"),+ ("invalid_punycode", ["xn--zz.com"], "is not a valid domain"),+ ("single_label", ["com"], "would block every domain that ends in .com"),+ ("too_many", [f"host{i}.example.com" for i in range(MAX_BLOCKED_HOSTS + 1)], "up to 100 domains"),+ ]+ )+ def test_rejects(self, _name: str, entries: list[str], message: str) -> None:+ with self.assertRaisesRegex(BlocklistEntryError, message):+ normalize_blocked_hosts(entries)+++class TestNormalizeBlockedIps(SimpleTestCase):+ @parameterized.expand(+ [+ ("ipv4_address", ["203.0.113.7"], ["203.0.113.7"]),+ ("ipv4_full_prefix_drops_suffix", ["203.0.113.7/32"], ["203.0.113.7"]),+ ("ipv4_cidr_drops_host_bits", ["198.51.100.42/24"], ["198.51.100.0/24"]),+ ("ipv4_widest_allowed", ["10.1.2.3/8"], ["10.0.0.0/8"]),+ ("ipv6_address_compressed", ["2001:0db8:0000:0000:0000:0000:0000:0001"], ["2001:db8::1"]),+ ("ipv6_cidr", ["2001:db8:abcd:12::/48"], ["2001:db8:abcd::/48"]),+ ("ipv6_widest_allowed", ["2001:db8::/16"], ["2001::/16"]),+ ("dedupes_after_normalizing", ["203.0.113.7", " 203.0.113.7/32 ", ""], ["203.0.113.7"]),+ ("ipv4_mapped_address_as_ipv4", ["::ffff:203.0.113.7"], ["203.0.113.7"]),+ ("ipv4_mapped_range_as_ipv4", ["::ffff:203.0.113.0/120"], ["203.0.113.0/24"]),+ (+ "accepts_max_after_dedupe",+ [f"10.0.0.{i}" for i in range(MAX_BLOCKED_IPS)] + ["10.0.0.0/32"],+ [f"10.0.0.{i}" for i in range(MAX_BLOCKED_IPS)],+ ),+ ]+ )+ def test_normalizes(self, _name: str, entries: list[str], expected: list[str]) -> None:+ assert normalize_blocked_ips(entries) == expected++ @parameterized.expand(+ [+ ("not_an_ip", ["example.com"], "is not a valid IP address or range"),+ ("bad_prefix", ["203.0.113.0/33"], "is not a valid IP address or range"),+ ("ipv4_everything", ["0.0.0.0/0"], "IPv4 ranges can be /8 or narrower"),+ ("ipv4_too_broad", ["192.0.0.0/7"], "IPv4 ranges can be /8 or narrower"),+ ("ipv6_everything", ["::/0"], "IPv6 ranges can be /16 or narrower"),+ ("ipv6_too_broad", ["2000::/15"], "IPv6 ranges can be /16 or narrower"),+ ("ipv4_mapped_everything", ["::ffff:0:0/96"], "IPv4 ranges can be /8 or narrower"),+ ("ipv6_scoped", ["fe80::1%eth0"], "is not a valid IP address or range"),+ ("too_many", [f"10.0.{i // 256}.{i % 256}" for i in range(MAX_BLOCKED_IPS + 1)], "up to 100 IP"),+ ]+ )+ def test_rejects(self, _name: str, entries: list[str], message: str) -> None:+ with self.assertRaisesRegex(BlocklistEntryError, message):+ normalize_blocked_ips(entries)++class TestTeamFeatureFlagPolicyConfig(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -21,7 +118,11 @@ class TestTeamFeatureFlagPolicyConfig(APIBaseTest):response = self.client.get(self.url)assert response.status_code == status.HTTP_200_OK- assert response.json()["feature_flag_policy_config"] == {"require_tags": False}+ assert response.json()["feature_flag_policy_config"] == {+ "require_tags": False,+ "blocked_hosts": [],+ "blocked_ips": [],+ }def test_admin_can_toggle_require_tags(self) -> None:response = self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})@@ -36,14 +137,87 @@ class TestTeamFeatureFlagPolicyConfig(APIBaseTest):assert response.json()["feature_flag_policy_config"]["require_tags"] is Falseassert TeamFeatureFlagPolicyConfig.objects.get(team=self.team).require_tags is False- def test_member_cannot_toggle_require_tags(self) -> None:+ def test_admin_sets_request_blocklist_normalized_and_logged(self) -> None:+ self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}}, format="json")+ other_hosts = [f"host{i}.example.com" for i in range(MAX_BLOCKED_HOSTS - 2)]+ # Each fills its column exactly. Postgres truncates an entry that is too long for its+ # varchar(n)[] column instead of raising an error, so only the read-back shows that it fits.+ longest_host = ".".join(["a" * 63] * 3 + ["b" * 61])+ longest_ip = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe/127"+ assert (len(longest_host), len(longest_ip)) == (MAX_BLOCKED_HOST_LENGTH, MAX_BLOCKED_IP_LENGTH)++ response = self.client.patch(+ self.url,+ {+ "feature_flag_policy_config": {+ "blocked_hosts": ["https://Example.com/page", "", *other_hosts, longest_host, "EXAMPLE.com"],+ "blocked_ips": ["198.51.100.42/24", "2001:db8::1", longest_ip],+ }+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ expected_hosts = ["example.com", *other_hosts, longest_host]+ expected_ips = ["198.51.100.0/24", "2001:db8::1", longest_ip]+ config = TeamFeatureFlagPolicyConfig.objects.get(team=self.team)+ assert config.blocked_hosts == expected_hosts+ assert config.blocked_ips == expected_ips+ assert config.require_tags is True+ log = ActivityLog.objects.filter(team_id=self.team.id, scope="Team", activity="updated").latest("created_at")+ assert log.detail is not None+ change = log.detail["changes"][0]+ assert change["field"] == "feature_flag_policy_config"+ assert change["after"]["blocked_hosts"] == expected_hosts+ assert change["after"]["blocked_ips"] == expected_ips++ response = self.client.patch(self.url, {"feature_flag_policy_config": {"blocked_hosts": []}}, format="json")++ assert response.status_code == status.HTTP_200_OK+ config.refresh_from_db()+ assert config.blocked_hosts == []+ assert config.blocked_ips == expected_ips+ assert config.require_tags is True++ @parameterized.expand(+ [+ ("ip_too_broad", {"blocked_ips": ["0.0.0.0/0"]}, "/8 or narrower"),+ ("host_malformed_url", {"blocked_hosts": ["https://[example.com"]}, "is not a valid domain"),+ (+ "hosts_over_unique_cap",+ {"blocked_hosts": [f"host{i}.example.com" for i in range(MAX_BLOCKED_HOSTS + 1)]},+ "up to 100 domains",+ ),+ ]+ )+ def test_invalid_blocklist_entry_is_rejected(self, _name: str, policy: dict, message: str) -> None:+ response = self.client.patch(self.url, {"feature_flag_policy_config": policy}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert message in str(response.json())+ assert not TeamFeatureFlagPolicyConfig.objects.filter(team=self.team).exclude(blocked_hosts=[]).exists()+ assert not TeamFeatureFlagPolicyConfig.objects.filter(team=self.team).exclude(blocked_ips=[]).exists()++ def test_member_cannot_change_policy(self) -> None:self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()- response = self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})+ response = self.client.patch(+ self.url,+ {+ "feature_flag_policy_config": {+ "require_tags": True,+ "blocked_hosts": ["example.com"],+ "blocked_ips": ["203.0.113.7"],+ }+ },+ format="json",+ )assert response.status_code == status.HTTP_403_FORBIDDENassert team_requires_flag_tags(self.team.id) is False+ assert not TeamFeatureFlagPolicyConfig.objects.filter(team=self.team).exclude(blocked_hosts=[]).exists()+ assert not TeamFeatureFlagPolicyConfig.objects.filter(team=self.team).exclude(blocked_ips=[]).exists()def test_patching_other_team_fields_leaves_require_tags_alone(self) -> None:self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5960974d252b..59111863ad20 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -87314,6 +87314,18 @@ export namespace Schemas {export interface TeamFeatureFlagPolicyConfig {/** When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag. */require_tags?: boolean;+ /**+ * Domains to block from feature flag requests (/flags and /decide), up to 100. A domain also covers its subdomains. It is compared with the Origin header, or with the Referer header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is reduced to its domain, and an internationalized domain is stored as punycode.+ * @maxItems 1000+ * @items.maxLength 2000+ */+ blocked_hosts?: string[];+ /**+ * IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (/flags and /decide), up to 100. Ranges can be /8 or narrower for IPv4 and /16 or narrower for IPv6. Entries are stored in canonical form without duplicates, and an IPv4-mapped IPv6 address is stored as IPv4.+ * @maxItems 1000+ * @items.maxLength 2000+ */+ blocked_ips?: string[];}/**diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex bf8970098c97..00477155a719 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -371,6 +371,14 @@ export const organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapexport const organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax = 30+export const organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedHostsItemMax = 2000++export const organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedHostsMax = 1000++export const organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedIpsItemMax = 2000++export const organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedIpsMax = 1000+export const organizationsProjectsCreateBodyDefaultDataThemeMin = -2147483648export const organizationsProjectsCreateBodyDefaultDataThemeMax = 2147483647@@ -2919,6 +2927,20 @@ export const OrganizationsProjectsCreateBody = () => zod.describe('When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag.'),+ blocked_hosts: zod+ .array(zod.string().max(organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedHostsItemMax))+ .max(organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedHostsMax)+ .optional()+ .describe(+ 'Domains to block from feature flag requests (\/flags and \/decide), up to 100. A domain also covers its subdomains. It is compared with the Origin header, or with the Referer header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is reduced to its domain, and an internationalized domain is stored as punycode.'+ ),+ blocked_ips: zod+ .array(zod.string().max(organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedIpsItemMax))+ .max(organizationsProjectsCreateBodyFeatureFlagPolicyConfigBlockedIpsMax)+ .optional()+ .describe(+ 'IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (\/flags and \/decide), up to 100. Ranges can be \/8 or narrower for IPv4 and \/16 or narrower for IPv6. Entries are stored in canonical form without duplicates, and an IPv4-mapped IPv6 address is stored as IPv4.'+ ),}).optional(),base_currency: zod@@ -3224,6 +3246,14 @@ export const organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequexport const organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax = 30+export const organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedHostsItemMax = 2000++export const organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedHostsMax = 1000++export const organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedIpsItemMax = 2000++export const organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedIpsMax = 1000+export const organizationsProjectsPartialUpdateBodyDefaultDataThemeMin = -2147483648export const organizationsProjectsPartialUpdateBodyDefaultDataThemeMax = 2147483647@@ -5786,6 +5816,26 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod.describe('When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag.'),+ blocked_hosts: zod+ .array(+ zod+ .string()+ .max(organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedHostsItemMax)+ )+ .max(organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedHostsMax)+ .optional()+ .describe(+ 'Domains to block from feature flag requests (\/flags and \/decide), up to 100. A domain also covers its subdomains. It is compared with the Origin header, or with the Referer header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is reduced to its domain, and an internationalized domain is stored as punycode.'+ ),+ blocked_ips: zod+ .array(+ zod.string().max(organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedIpsItemMax)+ )+ .max(organizationsProjectsPartialUpdateBodyFeatureFlagPolicyConfigBlockedIpsMax)+ .optional()+ .describe(+ 'IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (\/flags and \/decide), up to 100. Ranges can be \/8 or narrower for IPv4 and \/16 or narrower for IPv6. Entries are stored in canonical form without duplicates, and an IPv4-mapped IPv6 address is stored as IPv4.'+ ),}).optional(),base_currency: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.jsonindex 095c9db25e34..bbeb336d8445 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json@@ -418,6 +418,24 @@},"feature_flag_policy_config": {"properties": {+ "blocked_hosts": {+ "description": "Domains to block from feature flag requests (/flags and /decide), up to 100. A domain also covers its subdomains. It is compared with the Origin header, or with the Referer header when Origin is missing. Entries are stored lowercase without duplicates. A pasted URL is reduced to its domain, and an internationalized domain is stored as punycode.",+ "items": {+ "maxLength": 2000,+ "type": "string"+ },+ "maxItems": 1000,+ "type": "array"+ },+ "blocked_ips": {+ "description": "IPv4 or IPv6 addresses or CIDR ranges to block from feature flag requests (/flags and /decide), up to 100. Ranges can be /8 or narrower for IPv4 and /16 or narrower for IPv6. Entries are stored in canonical form without duplicates, and an IPv4-mapped IPv6 address is stored as IPv4.",+ "items": {+ "maxLength": 2000,+ "type": "string"+ },+ "maxItems": 1000,+ "type": "array"+ },"require_tags": {"description": "When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag.","type": "boolean"