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): reject uncompilable regex patterns when writing rules v2 flags (#109444)

Anders15228d6950ef
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.md
index 7cd091d84aa1..bc6c863d83ed 100644
--- a/docs/internal/feature-flags/api-writes.md
+++ b/docs/internal/feature-flags/api-writes.md
@@ -78,7 +78,8 @@ A stored version 2 row that is not remote-configured and carries no encrypted pa
- A new row is created disabled with server-owned rule IDs and seeds; the request document is resolved against an empty stored document and validated strictly before it is persisted exactly. No v1 row is converted.
- A supplied `filters` object replaces the whole configuration. There is no top-level merge, no rule merge by index, no filling of omitted fields from the stored document, and no v1 normalization. `{}`, `null`, a list, and an incomplete object are invalid; a complete document with `rules: []` is valid.
- `return_type` is `boolean`, `string`, `number` or `object` and cannot change after creation. `default_value` is null or the declared type; every rule `value` is the declared type. Strings are non-empty and not `$false`, the event-storage sentinel that v1 also reserves as a variant key; numbers lie within ±(2^53 − 1); objects nest at most 20 object or array levels with numbers in the same range.
-- Writer-only rules (`check_writer_rules` in `facade/config_writes.py`, currently the `$false` reservation) apply to a created or replacing document and to the stored document being enabled. The shared validator, and with it the flags caches and the stored side of an update, does not apply them: tightening a writer rule never hides a stored row from evaluation or blocks replacing it.
+- Writer-only rules (`check_writer_rules` in `facade/config_writes.py`, currently the `$false` reservation and the regex check below) apply to a created or replacing document and to the stored document being enabled. The shared validator, and with it the flags caches and the stored side of an update, does not apply them: tightening a writer rule never hides a stored row from evaluation or blocks replacing it.
+- `regex` and `not_regex` patterns must compile with Python's `re`, as on the v1 write path. This is a writer-only rule: readers store an uncompilable pattern and report an evaluation error when evaluation reaches it. The flags service compiles with `fancy_regex`, whose dialect differs at the edges, so, as in v1, a pattern the stored document already holds is not checked again, and enabling checks no pattern.
- Rule IDs and percentage-rollout seeds are server-owned and identify rules rather than list positions. An echoed ID keeps its seed through reordering and unrelated edits; a rule that omits its ID is new and receives fresh identity. An unknown ID, an ID used twice, a client-chosen seed, and a changed seed are all rejected.
- `FeatureFlag.version` is required on every update and must equal the locked row's value. Unlike v1 there is no `original_flag` merge: a stale token is a conflict even when no individual field clashes. The token applies to disabling and deleting too.
- Identity resolution, validation and the enable check run against the locked row inside the existing update transaction. A stored document with an unsupported shape or semantics is rejected rather than replaced or enabled. Configuration and metadata byte limits apply to a replacement, so an oversized stored document can be edited back under a lowered limit; enabling requires the stored document to fit the current limits.
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
index 4d8fac01379c..e9e0822af836 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
@@ -784,6 +784,72 @@ class TestWriterOnlyRules(AdmittedV2TestCase):
assert (flag.active, flag.version) == (False, 4)
+def regex_config(*patterns: tuple[str, str], rule_id: str | None = RULE_A, **extra: Any) -> dict:
+ properties = [{"key": "email", "type": "person", "operator": op, "value": value} for op, value in patterns]
+ return config(targeted(rule_id=rule_id, targeting={"properties": properties}, **extra))
+
+
+COMPILABLE = ("regex", r"@example\.com$")
+UNCOMPILABLE_PATTERNS = [
+ ("regex", "regex", "["),
+ ("not_regex", "not_regex", "(?P<"),
+ ("repetition_overflow", "regex", "a{4294967296}"),
+ ("repetition_past_the_int_digit_limit", "regex", "a{" + "9" * 5000 + "}"),
+ ("nesting_past_the_recursion_limit", "not_regex", "(" * 5000 + ")" * 5000),
+]
+
+
+class TestWriterRegexPatterns(AdmittedV2TestCase):
+ """New patterns must compile with Python's `re`, as in v1; readers accept any, and a pattern the row holds is kept."""
+
+ @parameterized.expand(UNCOMPILABLE_PATTERNS)
+ def test_create_rejects_an_uncompilable_pattern(self, _name: str, operator: str, pattern: str) -> None:
+ with admit_v2(self.team.id, creation=True):
+ filters = regex_config(COMPILABLE, (operator, pattern), rule_id=None)
+ response = self.post_flag({"key": "new-v2", "filters": filters})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert (response.json()["code"], response.json()["detail"]) == (
+ "invalid_input",
+ "filters.rules[0].targeting.properties[1].value: Must be a valid regular expression.",
+ )
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+
+ @parameterized.expand(UNCOMPILABLE_PATTERNS)
+ def test_update_rejects_a_new_uncompilable_pattern(self, _name: str, operator: str, pattern: str) -> None:
+ flag = self.flag(regex_config(COMPILABLE))
+ response = self.patch_flag(flag, {"version": 3, "filters": regex_config(COMPILABLE, (operator, pattern))})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == (
+ "filters.rules[0].targeting.properties[1].value: Must be a valid regular expression."
+ )
+ flag.refresh_from_db()
+ assert (flag.filters, flag.version) == (regex_config(COMPILABLE), 3)
+
+ def test_an_update_keeps_patterns_the_row_already_holds(self) -> None:
+ # The flags service compiles `\p{Lu}`, Python's `re` does not; `[` compiles in neither.
+ held = [("regex", "["), ("not_regex", r"^\p{Lu}")]
+ flag = self.flag(regex_config(*held))
+ response = self.patch_flag(flag, {"version": 3, "filters": regex_config(*held, ("regex", "("))})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == (
+ "filters.rules[0].targeting.properties[2].value: Must be a valid regular expression."
+ )
+
+ replacement = regex_config(*held, description="Reviewed")
+ response = self.patch_flag(flag, {"version": 3, "filters": replacement})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.filters, flag.version) == (replacement, 4)
+
+ def test_a_stored_uncompilable_pattern_can_be_enabled(self) -> None:
+ stored = regex_config(("regex", "["))
+ flag = self.flag(stored, active=False)
+ response = self.patch_flag(flag, {"version": 3, "active": True})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.active, flag.filters, flag.version) == (True, stored, 4)
+
+
class TestV2RequestBytes(AdmittedV2TestCase):
def post_bytes(self, flag: FeatureFlag, body: str):
return self.client.patch(
diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.py
index e75069df1470..ae5dc1df4e29 100644
--- a/products/feature_flags/backend/facade/config_writes.py
+++ b/products/feature_flags/backend/facade/config_writes.py
@@ -14,12 +14,14 @@ Four things a v2 write needs that the pure validator deliberately does not do:
rejected. Byte limits apply only to the candidate so oversized rows can be reduced.
- **Writer-only rules.** ``check_writer_rules`` rejects what readers accept but a writer may
not store. It runs on the submitted document and on a stored one being enabled, never on
- the stored side of an update, so tightening a rule never blocks replacing a stored row.
+ the stored side of an update, so tightening a rule never blocks replacing a stored row. A
+ rule may also accept what the stored document already holds.
Deliberately free of Django ORM and DRF imports: the endpoint owns HTTP error shapes and
the row lock, this module owns the document.
"""
+import re
import sys
import json
from collections.abc import Callable, Iterator, Mapping
@@ -32,6 +34,7 @@ import structlog
from posthog.hogql.constants import FEATURE_FLAG_FALSE_VARIANT_SENTINEL
+from posthog.dataclasses import frozen
from posthog.ph_client import feature_enabled_or_false
from products.feature_flags.backend.facade.config_validation import (
@@ -238,7 +241,7 @@ def review_update(
)
warnings = review_config(document, limits=limits, current=current).warnings
assert isinstance(document, Mapping) # review_config rejects anything else
- check_writer_rules(document)
+ check_writer_rules(document, stored=stored)
return warnings
@@ -257,25 +260,26 @@ def _validated_stored(
try:
config = validate_config(stored, limits=limits)
if writer_rules:
- check_writer_rules(stored)
+ check_writer_rules(stored, stored=stored)
return config
except ConfigValidationError as exc:
detail = f"This flag's stored configuration cannot be {operation} through this API."
raise ConfigValidationError([ConfigError(code="unsupported", detail=detail, attr="filters")]) from exc
-def check_writer_rules(document: Mapping[str, Any]) -> None:
+def check_writer_rules(document: Mapping[str, Any], *, stored: Mapping[str, Any]) -> None:
"""Reject a document ``validate_config`` admitted that a writer still may not store.
Readers never apply these. Each entry in ``_WRITER_RULES`` reads the validated document
+ and the validated stored document it replaces (empty on create, itself when enabling)
and yields its field errors.
"""
- errors = [error for rule in _WRITER_RULES for error in rule(document)]
+ errors = [error for rule in _WRITER_RULES for error in rule(document, stored)]
if errors:
raise ConfigValidationError(errors)
-def _reserved_string_values(document: Mapping[str, Any]) -> Iterator[ConfigError]:
+def _reserved_string_values(document: Mapping[str, Any], _stored: Mapping[str, Any]) -> Iterator[ConfigError]:
# A string value is served as the variant, and `$false` is the event-storage sentinel that v1 reserves as a variant key.
if document["return_type"] != "string":
return
@@ -287,4 +291,42 @@ def _reserved_string_values(document: Mapping[str, Any]) -> Iterator[ConfigError
yield ConfigError(code="invalid", detail=f"{detail}.", attr=f"filters.rules[{index}].value")
-_WRITER_RULES: tuple[Callable[[Mapping[str, Any]], Iterator[ConfigError]], ...] = (_reserved_string_values,)
+def _compilable_patterns(document: Mapping[str, Any], stored: Mapping[str, Any]) -> Iterator[ConfigError]:
+ """New ``regex`` and ``not_regex`` patterns must compile with Python's ``re``, as v1 writes must.
+
+ The flags service compiles with fancy_regex, which accepts some patterns ``re`` rejects, so
+ like v1 this keeps any pattern the stored document already holds; enabling adds none.
+ """
+ held = {regex.pattern for regex in _regex_patterns(stored)} if stored else set()
+ for regex in _regex_patterns(document):
+ if regex.pattern not in held and not _compiles(regex.pattern):
+ yield ConfigError(code="invalid", detail="Must be a valid regular expression.", attr=regex.attr)
+
+
+@frozen
+class _RegexPattern:
+ attr: str
+ pattern: str
+
+
+def _regex_patterns(document: Mapping[str, Any]) -> Iterator[_RegexPattern]:
+ for rule_index, rule in enumerate(document["rules"]):
+ for index, prop in enumerate(rule["targeting"]["properties"]):
+ if prop.get("operator") in ("regex", "not_regex"):
+ yield _RegexPattern(
+ attr=f"filters.rules[{rule_index}].targeting.properties[{index}].value", pattern=prop["value"]
+ )
+
+
+def _compiles(pattern: str) -> bool:
+ try:
+ re.compile(pattern)
+ except (re.error, ValueError, OverflowError, RecursionError):
+ return False
+ return True
+
+
+_WRITER_RULES: tuple[Callable[[Mapping[str, Any], Mapping[str, Any]], Iterator[ConfigError]], ...] = (
+ _reserved_string_values,
+ _compilable_patterns,
+)
diff --git a/products/feature_flags/backend/test/test_facade_config_validation.py b/products/feature_flags/backend/test/test_facade_config_validation.py
index 8b008aad29da..8a50aa45a4c6 100644
--- a/products/feature_flags/backend/test/test_facade_config_validation.py
+++ b/products/feature_flags/backend/test/test_facade_config_validation.py
@@ -173,6 +173,8 @@ VALID_DOCUMENTS: list[tuple[str, dict[str, Any]]] = [
)
),
),
+ ("uncompilable_regex", config(targeted(targeting={"properties": [person(operator="regex", value="[")]}))),
+ ("uncompilable_not_regex", config(targeted(targeting={"properties": [person(operator="not_regex", value="(")]}))),
(
"string_values",
config(targeted(value="compact"), rollout(value="wide"), return_type="string", default_value="standard"),
diff --git a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json
index 624ad4fcbb9b..c3f2461f4b22 100644
--- a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json
+++ b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json
@@ -189,6 +189,25 @@
"expect": "unsupported",
"reason": "a four-part version is not semver, so the flags service parser rejects it"
},
+ {
+ "key": "v2-regex-uncompilable-active",
+ "active": true,
+ "filters": {
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": null,
+ "rules": [
+ {
+ "id": "e5e5e5e5-e5e5-4e5e-8e5e-e5e5e5e5e5e5",
+ "rule_type": "targeted_release",
+ "targeting": { "properties": [{ "key": "email", "type": "person", "operator": "regex", "value": "[" }] },
+ "value": true
+ }
+ ]
+ },
+ "expect": "kept",
+ "reason": "an uncompilable pattern is an evaluation error, not a parse error; only the writer compiles it"
+ },
{
"key": "v2-malformed-active",
"active": true,