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(hogql): guard resolver macro expansion against nested DoS (#64090)

Robbied2ecebac99ca
diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.py
index 7658e75b4cb1..aaec26684433 100644
--- a/posthog/hogql/functions/test/test_traffic_type_functions.py
+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py
@@ -1,6 +1,11 @@
import pytest
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import QueryError
from posthog.hogql.functions.traffic_type import (
get_bot_name,
get_bot_type,
@@ -8,7 +13,10 @@ from posthog.hogql.functions.traffic_type import (
get_traffic_type,
is_bot,
)
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+from products.actions.backend.models.action import Action
from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
@@ -419,3 +427,66 @@ class TestBotDefinitionsDataStructure:
assert patterns.index(p2) < patterns.index(p1), (
f"{p2} must come before {p1} for correct multiMatchAnyIndex matching"
)
+
+
+# Bot-lookup macros whose builders duplicate their argument and so expand under the re-entrancy
+# guard in Resolver._expand_duplicating_macro. Parameterized over so a malformed dispatch line for
+# any one of them (missing guard, wrong flag reset) is caught.
+DUPLICATING_MACROS = [
+ "__preview_getTrafficType",
+ "__preview_getTrafficCategory",
+ "__preview_getBotType",
+ "__preview_getBotName",
+ "__preview_getBotOperator",
+]
+
+
+class TestMacroExpansionGuard(BaseTest):
+ def _print(self, select: str) -> str:
+ return prepare_and_print_ast(
+ parse_select(select),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ "clickhouse",
+ )[0]
+
+ @parameterized.expand(DUPLICATING_MACROS)
+ def test_single_level_macro_expands(self, macro: str):
+ # A non-nested call resolves and expands to the multiMatchAnyIndex lookup.
+ printed = self._print(f"SELECT {macro}(toString(properties.x)) FROM events")
+ assert "multiMatchAnyIndex" in printed
+
+ @parameterized.expand(DUPLICATING_MACROS)
+ def test_nested_duplicating_macro_is_rejected(self, macro: str):
+ # The bot-lookup builders duplicate their argument, so a duplicating macro nested inside
+ # another's expansion would blow up ~2^depth during resolution. Reject it instead.
+ with pytest.raises(QueryError, match="cannot be nested inside another expanded function call"):
+ self._print(f"SELECT {macro}({macro}(toString(properties.x))) FROM events")
+
+ def test_cross_duplicating_macro_nesting_is_rejected(self):
+ # Nesting two *different* duplicating macros is the same exponential vector.
+ with pytest.raises(QueryError, match="cannot be nested inside another expanded function call"):
+ self._print("SELECT __preview_getTrafficType(__preview_getBotName(toString(properties.x))) FROM events")
+
+ def test_non_duplicating_macro_inside_duplicating_macro_is_allowed(self):
+ # isBot does not duplicate its argument, so reaching it inside a duplicating macro's
+ # expansion is bounded (not exponential) and must still resolve, not raise.
+ printed = self._print("SELECT __preview_getTrafficType(toString(__preview_isBot(properties.x))) FROM events")
+ assert "multiMatchAnyIndex" in printed
+
+ def test_matches_action_with_macro_property_still_resolves(self):
+ # matchesAction expands a user-defined action, whose hogql property filters re-parse
+ # arbitrary user HogQL. A guarded macro referenced there must still expand — the guard
+ # must not fire across matchesAction's (bounded) action expansion.
+ action = Action.objects.create(
+ team=self.team,
+ steps_json=[
+ {
+ "event": "$pageview",
+ "properties": [
+ {"type": "hogql", "key": "__preview_getTrafficType(properties.$user_agent) = 'Bot'"}
+ ],
+ }
+ ],
+ )
+ printed = self._print(f"SELECT matchesAction({action.pk}) FROM events")
+ assert "multiMatchAnyIndex" in printed
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index e3413e4acd8c..f65d2a24c0f3 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -256,6 +256,8 @@ class Resolver(CloningVisitor):
self.cte_counter = 0
self._scope_table_names: dict[int, dict[str, str]] = {}
self._scope_table_column_aliases: dict[int, dict[str, list[str]]] = {}
+ # Re-entrancy guard for argument-duplicating bot-lookup macros (see _expand_duplicating_macro).
+ self._inside_posthog_macro_expansion: bool = False
def _get_scope_table_names(self, scope: ast.SelectQueryType) -> dict[str, str]:
return self._scope_table_names.setdefault(id(scope), {})
@@ -1508,6 +1510,27 @@ class Resolver(CloningVisitor):
node.type.nullable = left_type.nullable or right_type.nullable
return node
+ def _expand_duplicating_macro(self, node: ast.Call, builder: Callable[[], ast.Expr]) -> ast.Expr:
+ """Build and resolve a bot-lookup macro whose builder duplicates its argument.
+
+ The bot-lookup helpers reference the same multiMatchAnyIndex node in two positions
+ (`_build_bot_array_lookup`), so each level copies the unvisited argument subtree, and a
+ user-written duplicating macro nested inside another's argument would expand ~2^depth
+ during resolution. The flag is set across the visit so the inner macro is rejected before
+ the blowup compounds; it persists through any non-duplicating macro's plain visit in
+ between, so `getTrafficType(toString(getBotName(...)))` is still caught. Only the
+ duplicating bot-lookup macros set the flag — macros that embed their argument once or
+ expand bounded, user-authored content (matchesAction's action, the survey filters) must
+ not, or they would reject a legitimate macro reached during their expansion.
+ """
+ if self._inside_posthog_macro_expansion:
+ raise QueryError(f"Function '{node.name}' cannot be nested inside another expanded function call.")
+ self._inside_posthog_macro_expansion = True
+ try:
+ return self.visit(builder())
+ finally:
+ self._inside_posthog_macro_expansion = False
+
def visit_call(self, node: ast.Call):
"""Visit function calls."""
@@ -1552,18 +1575,20 @@ class Resolver(CloningVisitor):
return self.visit(
unique_survey_submissions_filter(node=node, args=node.args, team_id=self.context.team_id)
)
- if node.name == "__preview_getTrafficType":
- return self.visit(get_traffic_type(node=node, args=node.args))
- if node.name == "__preview_getTrafficCategory":
- return self.visit(get_traffic_category(node=node, args=node.args))
if node.name == "__preview_isBot":
return self.visit(is_bot(node=node, args=node.args))
+ # The bot-lookup builders below duplicate their argument, so they must expand under the
+ # re-entrancy guard to bound nested expansion (see _expand_duplicating_macro).
+ if node.name == "__preview_getTrafficType":
+ return self._expand_duplicating_macro(node, lambda: get_traffic_type(node=node, args=node.args))
+ if node.name == "__preview_getTrafficCategory":
+ return self._expand_duplicating_macro(node, lambda: get_traffic_category(node=node, args=node.args))
if node.name == "__preview_getBotType":
- return self.visit(get_bot_type(node=node, args=node.args))
+ return self._expand_duplicating_macro(node, lambda: get_bot_type(node=node, args=node.args))
if node.name == "__preview_getBotName":
- return self.visit(get_bot_name(node=node, args=node.args))
+ return self._expand_duplicating_macro(node, lambda: get_bot_name(node=node, args=node.args))
if node.name == "__preview_getBotOperator":
- return self.visit(get_bot_operator(node=node, args=node.args))
+ return self._expand_duplicating_macro(node, lambda: get_bot_operator(node=node, args=node.args))
if self._is_higher_order_array_call(node):
node = self._visit_higher_order_array_call(node)