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(actions): reject invalid regexes in action steps before ClickHouse compiles them (#117039)

Thomas Obermüllerc3c18b74b574
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index a84e2527ed49..415231378b43 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -738,14 +738,19 @@ def _multi_search_not_found_for_values(expr: ast.Expr, value: list) -> ast.Expr:
return ast.Not(expr=_multi_search_found_for_values(expr, value))
-def _validate_regex(value: ValueT) -> None:
+# log_errors=False keeps RE2 from writing rejected patterns to stderr.
+_RE2_QUIET = re2.Options()
+_RE2_QUIET.log_errors = False
+
+
+def validate_regex(value: ValueT) -> None:
"""Reject an invalid regular expression with a clear user-facing error rather
than letting ClickHouse fail the whole query with CANNOT_COMPILE_REGEXP. The
same RE2 engine ClickHouse uses validates the pattern here."""
if not isinstance(value, str):
return
try:
- re2.compile(value)
+ re2.compile(value, options=_RE2_QUIET)
except re2.error as err:
raise QueryError(f"Invalid regular expression: '{value}'") from err
@@ -822,7 +827,7 @@ def _expr_to_compare_op(
values_list = cast(list, [value])
return _multi_search_not_found_for_values(expr, values_list)
elif operator == PropertyOperator.REGEX:
- _validate_regex(value)
+ validate_regex(value)
return ast.Call(
name="ifNull",
args=[
@@ -831,7 +836,7 @@ def _expr_to_compare_op(
],
)
elif operator == PropertyOperator.NOT_REGEX:
- _validate_regex(value)
+ validate_regex(value)
return ast.Call(
name="ifNull",
args=[
@@ -1837,6 +1842,7 @@ def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optiona
exprs.append(tag_name_to_expr(step.tag_name))
if step.href is not None:
if step.href_matching == "regex":
+ validate_regex(step.href)
exprs.append(
ast.CompareOperation(
op=ast.CompareOperationOp.Regex,
@@ -1863,6 +1869,7 @@ def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optiona
if step.text is not None:
value = step.text
if step.text_matching == "regex":
+ validate_regex(value)
exprs.append(
parse_expr(
"arrayExists(x -> x =~ {value}, elements_chain_texts)",
@@ -1898,6 +1905,7 @@ def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optiona
right=ast.Constant(value=step.url),
)
elif step.url_matching == "regex":
+ validate_regex(step.url)
expr = ast.CompareOperation(
op=ast.CompareOperationOp.Regex,
left=ast.Field(
diff --git a/posthog/hogql/test/test_action_to_expr.py b/posthog/hogql/test/test_action_to_expr.py
index 3afaaba063e4..6a29d9e24c95 100644
--- a/posthog/hogql/test/test_action_to_expr.py
+++ b/posthog/hogql/test/test_action_to_expr.py
@@ -1,13 +1,17 @@
from typing import Any, Optional
+import pytest
from posthog.test.base import BaseTest, _create_event
from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import action_to_expr, steps_to_expr
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.visitor import clear_locations
+from posthog.models import Team
+
from products.actions.backend.models.action import Action, ActionStepJSON
@@ -176,3 +180,21 @@ class TestActionToExpr(BaseTest):
clear_locations(steps_to_expr([], self.team)),
clear_locations(parse_expr("true")),
)
+
+
+class TestStepsToExprRegexValidation:
+ @pytest.mark.parametrize(
+ "step",
+ [
+ ActionStepJSON(event="$pageview", url="/token-abc123/\\d+\\", url_matching="regex"),
+ ActionStepJSON(event="$autocapture", href="/token-abc123/\\d+\\", href_matching="regex"),
+ ActionStepJSON(event="$autocapture", text="/token-abc123/\\d+\\", text_matching="regex"),
+ ],
+ ids=["url", "href", "text"],
+ )
+ def test_invalid_step_regex_raises_query_error_without_logging_it(
+ self, step: ActionStepJSON, capfd: pytest.CaptureFixture[str]
+ ) -> None:
+ with pytest.raises(QueryError, match="Invalid regular expression"):
+ steps_to_expr([step], team=Team())
+ assert "token-abc123" not in capfd.readouterr().err
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index a4482a5638f7..d04f4657edf5 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -17,6 +17,9 @@ from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework_csv import renderers as csvrenderers
+from posthog.hogql.errors import QueryError
+from posthog.hogql.property import validate_regex
+
from posthog.api.documentation import (
ArrayPropertyFilterSerializer,
DatePropertyFilterSerializer,
@@ -258,6 +261,26 @@ class ActionSerializer(
def get_creation_context(self, obj) -> None:
return None
+ def validate_steps(self, steps: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None:
+ # ClickHouse compiles these with RE2 at query time, so one pattern RE2 rejects fails
+ # every insight that uses the action. steps_to_expr runs this same check on stored steps.
+ # The check runs here and not on the step serializer because the error renderer turns an
+ # error nested inside one list item into a Python repr instead of a readable message.
+ for step in steps or []:
+ for value_field, matching_field in (
+ ("url", "url_matching"),
+ ("href", "href_matching"),
+ ("text", "text_matching"),
+ ):
+ value = step.get(value_field)
+ if step.get(matching_field) != "regex" or not isinstance(value, str):
+ continue
+ try:
+ validate_regex(value)
+ except QueryError as err:
+ raise serializers.ValidationError(str(err)) from err
+ return steps
+
def validate(self, attrs):
instance = cast(Action, self.instance)
exclude_args = {}
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index e0be203abad2..371692cdf13a 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -14,11 +14,12 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from posthog.models import Tag, User
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
-from products.actions.backend.api.action import ActionStepJSONSerializer
+from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializer
from products.actions.backend.models.action import Action
from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -187,6 +188,28 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(Action.objects.count(), count)
+ def test_cant_create_action_with_invalid_step_regex(self, *args):
+ count = Action.objects.count()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/actions/",
+ {
+ "name": "pricing pages",
+ "steps": [{"event": "$pageview", "url": "/pricing/\\d+\\", "url_matching": "regex"}],
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {
+ "type": "validation_error",
+ "code": "invalid_input",
+ "detail": "Invalid regular expression: '/pricing/\\d+\\'",
+ "attr": "steps",
+ },
+ )
+ self.assertEqual(Action.objects.count(), count)
+
def test_cant_create_action_with_whitespace_only_name(self, *args):
count = Action.objects.count()
@@ -1060,6 +1083,29 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert action_result["reference_count"] == 4
+class TestActionStepRegexValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (f"{field}_{case}", field, matching, value, expect_valid)
+ for field in ("url", "href", "text")
+ for case, matching, value, expect_valid in (
+ ("trailing_backslash", "regex", "/pricing/\\d+\\", False),
+ # Python's re accepts a lookahead, so this case fails if the check stops using RE2.
+ ("lookahead", "regex", "/pricing/(?=annual)", False),
+ ("valid_regex", "regex", "/pricing/\\d+", True),
+ ("contains_is_not_a_regex", "contains", "/pricing/\\d+\\", True),
+ )
+ ]
+ )
+ def test_validates_step_regex(self, _name: str, field: str, matching: str, value: str, expect_valid: bool) -> None:
+ steps = [{"event": "$autocapture", field: value, f"{field}_matching": matching}]
+ if expect_valid:
+ self.assertEqual(ActionSerializer().validate_steps(steps), steps)
+ else:
+ with self.assertRaisesMessage(ValidationError, "Invalid regular expression"):
+ ActionSerializer().validate_steps(steps)
+
+
class TestSelectorWarning(SimpleTestCase):
@parameterized.expand(
[