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(activity-log): validate detail_filters field paths (#74434)

Tom Piccirello10d615f46e67
diff --git a/.semgrep/rules/security/orm-field-injection.yaml b/.semgrep/rules/security/orm-field-injection.yaml
index c7a6ba73648d..7f50deeaf8a2 100644
--- a/.semgrep/rules/security/orm-field-injection.yaml
+++ b/.semgrep/rules/security/orm-field-injection.yaml
@@ -9,9 +9,11 @@ rules:
and exfiltrate sensitive fields (e.g. user__password, team__api_token).
Fix: validate the variable against an allowlist of permitted field names
- before using it in the ORM lookup. If the first path segment is a JSONField,
- the risk is mitigated (Django routes all subsequent __ as JSON key lookups),
- but an allowlist is still recommended as defense in depth.
+ before using it in the ORM lookup. Anchoring the path on a JSONField is not
+ enough on its own: Django still resolves the last segment as a lookup, so a
+ path like detail__<var> or detail__key__<var> lets the caller pick the
+ operation (e.g. regex, which runs an attacker-supplied Postgres regular
+ expression over every row). Validate every segment, including the last.
Suppress with: # nosemgrep: orm-field-injection <reason>
patterns:
diff --git a/posthog/api/advanced_activity_logs/filters.py b/posthog/api/advanced_activity_logs/filters.py
index 258162bcd933..e50476039670 100644
--- a/posthog/api/advanced_activity_logs/filters.py
+++ b/posthog/api/advanced_activity_logs/filters.py
@@ -1,12 +1,96 @@
import re
from typing import Any
-from django.db.models import Q, QuerySet
+from django.db.models import JSONField, Q, QuerySet
+from django.db.models.fields.json import KeyTransform
+
+from rest_framework import serializers
from posthog.models.activity_logging.activity_log import ActivityLog
_ALLOWED_DETAIL_FILTER_OPERATIONS = {"exact", "contains", "in"}
+# Names Django resolves as a lookup instead of a JSON key. A field path segment matching one of
+# these turns the caller's key into the ORM operation: `regex` becomes `detail::text ~ <value>`
+# and `name.regex` becomes `(detail ->> 'name')::text ~ <value>`, which evaluates an arbitrary
+# Postgres regular expression against every row. Computed from Django's registries so the set
+# stays correct when Django adds lookups.
+_DJANGO_LOOKUP_NAMES = frozenset(JSONField().get_lookups()) | frozenset(KeyTransform.get_lookups())
+
+_MAX_DETAIL_FILTERS = 100
+_MAX_FIELD_PATH_LENGTH = 500
+# Array filters only look at the first _MAX_ARRAY_INDICES_TO_CHECK elements of each array. Each
+# `[]` marker in a field path multiplies the number of generated index permutations by that number,
+# and every permutation costs a path string plus a Q object, so capping the product keeps a deeply
+# nested path from exhausting the worker's memory before any SQL runs. The cap is 5 ** 3, which
+# lets a path nest three arrays and rejects a fourth.
+_MAX_ARRAY_INDICES_TO_CHECK = 5
+_MAX_INDEXED_PATHS = 125
+
+
+def validate_detail_filters(detail_filters: Any) -> dict[str, Any]:
+ """Reject detail filters that Django would turn into an ORM operation or an unbounded expansion.
+
+ Raises ``serializers.ValidationError`` so callers surface a 400 rather than running the query.
+ """
+ if not isinstance(detail_filters, dict):
+ raise serializers.ValidationError("detail_filters must be an object.")
+
+ if len(detail_filters) > _MAX_DETAIL_FILTERS:
+ raise serializers.ValidationError(f"detail_filters accepts at most {_MAX_DETAIL_FILTERS} entries.")
+
+ for field_path, filter_config in detail_filters.items():
+ _validate_detail_filter(field_path, filter_config)
+
+ return detail_filters
+
+
+def _validate_detail_filter(field_path: Any, filter_config: Any) -> None:
+ if not isinstance(field_path, str) or not field_path:
+ raise serializers.ValidationError("Detail filter field paths must be non-empty strings.")
+
+ if len(field_path) > _MAX_FIELD_PATH_LENGTH:
+ raise serializers.ValidationError(
+ f"Detail filter field paths must be at most {_MAX_FIELD_PATH_LENGTH} characters."
+ )
+
+ if not isinstance(filter_config, dict):
+ raise serializers.ValidationError(f"Detail filter '{field_path}' must be an object.")
+
+ operation = filter_config.get("operation", "exact")
+ if operation not in _ALLOWED_DETAIL_FILTER_OPERATIONS:
+ raise serializers.ValidationError(
+ f"Unsupported detail filter operation '{operation}'. "
+ f"Allowed operations: {', '.join(sorted(_ALLOWED_DETAIL_FILTER_OPERATIONS))}."
+ )
+
+ # `__` is Django's lookup separator, so it would let a path traverse relationships or append a
+ # lookup regardless of the per-segment checks below.
+ if "__" in field_path:
+ raise serializers.ValidationError(f"Detail filter field path '{field_path}' contains '__'.")
+
+ if _MAX_ARRAY_INDICES_TO_CHECK ** field_path.count("[]") > _MAX_INDEXED_PATHS:
+ raise serializers.ValidationError(f"Detail filter field path '{field_path}' nests too many arrays.")
+
+ stripped = field_path.replace("[]", "")
+ for segment in stripped.split("."):
+ if not segment:
+ raise serializers.ValidationError(f"Detail filter field path '{field_path}' has an empty segment.")
+
+ # Check the components Django will actually see, not the dot-separated segments. A segment
+ # ending in `_` next to one starting with `_` joins into a run of underscores that shifts the
+ # `__` boundary, so a lookup name can surface as its own component without ever having been a
+ # segment -- and reach the database as a lookup.
+ for component in stripped.replace(".", "__").split("__"):
+ if not component:
+ raise serializers.ValidationError(
+ f"Detail filter field path '{field_path}' has an ambiguous underscore boundary."
+ )
+ if component in _DJANGO_LOOKUP_NAMES:
+ raise serializers.ValidationError(
+ f"Detail filter field path '{field_path}' uses reserved segment '{component}'."
+ )
+
class AdvancedActivityLogFilterManager:
def apply_filters(self, queryset: QuerySet[ActivityLog], filters: dict[str, Any]) -> QuerySet[ActivityLog]:
@@ -58,6 +142,11 @@ class AdvancedActivityLogFilterManager:
def _apply_detail_filters(
self, queryset: QuerySet[ActivityLog], detail_filters: dict[str, Any]
) -> QuerySet[ActivityLog]:
+ if not detail_filters:
+ return queryset
+
+ validate_detail_filters(detail_filters)
+
for field_path, filter_config in detail_filters.items():
operation = filter_config.get("operation", "exact")
value = filter_config.get("value")
@@ -65,11 +154,6 @@ class AdvancedActivityLogFilterManager:
if value is None:
continue
- # Block Django ORM relationship traversal (e.g. "user__password") and
- # restrict operations to a safe allowlist to prevent injection via arbitrary lookups.
- if "__" in field_path or operation not in _ALLOWED_DETAIL_FILTER_OPERATIONS:
- continue
-
if "[]" in field_path:
# Array fields like changes[].type need special handling
queryset = self._apply_array_field_filter(queryset, field_path, operation, value)
@@ -93,7 +177,7 @@ class AdvancedActivityLogFilterManager:
self, queryset: QuerySet[ActivityLog], field_path: str, value: Any
) -> QuerySet[ActivityLog]:
base_array_path = field_path.split("[]")[0]
- # nosemgrep: orm-field-injection -- field_path validated (__ rejected) and prefixed by detail__ JSONField
+ # nosemgrep: orm-field-injection -- field_path checked by validate_detail_filters (no `__`, no segment named after a Django lookup)
return queryset.filter(**{f"detail__{base_array_path}__icontains": value})
def _apply_array_exact_filter(
@@ -103,10 +187,9 @@ class AdvancedActivityLogFilterManager:
if len(parts) < 2:
return self._apply_array_contains_filter(queryset, field_path, value)
- max_indices_to_check = 5 # Check first 5 elements of each array
query_conditions = []
- indexed_paths = self._generate_indexed_paths(parts, field_path, max_indices_to_check)
+ indexed_paths = self._generate_indexed_paths(parts, field_path, _MAX_ARRAY_INDICES_TO_CHECK)
for django_path in indexed_paths:
query_condition = self._create_type_insensitive_query(f"detail__{django_path}", operation, value)
@@ -308,10 +391,10 @@ class AdvancedActivityLogFilterManager:
return combined_condition
elif operation == "in":
unique_values = self._expand_values_with_type_variants(value)
- # nosemgrep: orm-field-injection -- field_path validated (__ rejected) and prefixed by detail__ JSONField
+ # nosemgrep: orm-field-injection -- field_path checked by validate_detail_filters (no `__`, no segment named after a Django lookup)
return Q(**{f"{field_path}__in": unique_values})
elif operation == "contains":
- # nosemgrep: orm-field-injection -- field_path validated (__ rejected) and prefixed by detail__ JSONField
+ # nosemgrep: orm-field-injection -- field_path checked by validate_detail_filters (no `__`, no segment named after a Django lookup)
return Q(**{f"{field_path}__icontains": value})
else:
return Q(**{field_path: value})
diff --git a/posthog/api/advanced_activity_logs/test_filters.py b/posthog/api/advanced_activity_logs/test_filters.py
index f053e9bc0195..e43375657bb9 100644
--- a/posthog/api/advanced_activity_logs/test_filters.py
+++ b/posthog/api/advanced_activity_logs/test_filters.py
@@ -1,13 +1,17 @@
+import json
+from typing import Any
+
from posthog.test.base import BaseTest
from django.http import QueryDict
from django.test import SimpleTestCase
from parameterized import parameterized
+from rest_framework import serializers
from posthog.models.activity_logging.activity_log import ActivityLog
-from .filters import AdvancedActivityLogFilterManager
+from .filters import AdvancedActivityLogFilterManager, validate_detail_filters
from .viewset import AdvancedActivityLogFiltersSerializer
@@ -205,29 +209,46 @@ class TestAdvancedActivityLogFilterManager(BaseTest):
expected_ids = {log1.id, log2.id}
self.assertEqual(result_ids, expected_ids)
- def test_rejects_dunder_field_paths(self):
- log = self._create_activity_log({"name": "test"})
- queryset = ActivityLog.objects.filter(id=log.id)
- filtered = self.filter_manager._apply_detail_filters(
- queryset, {"user__email": {"operation": "exact", "value": "[email protected]"}}
- )
- self.assertEqual(filtered.count(), 1)
-
- filtered = self.filter_manager._apply_detail_filters(
- queryset, {"user__password": {"operation": "contains", "value": "pbkdf2"}}
- )
- self.assertEqual(filtered.count(), 1)
+class TestDetailFilterValidation(SimpleTestCase):
+ # Unsafe filters are rejected before any query is built, so no DB is needed here.
+ @parameterized.expand(
+ [
+ ("relationship_traversal", "user__email", {"operation": "exact", "value": "[email protected]"}),
+ ("unsupported_operation", "name", {"operation": "regex", "value": ".*"}),
+ ("lookup_suffixed_path", "name.regex", {"operation": "exact", "value": "^(a+)+$"}),
+ ("lookup_named_path", "regex", {"operation": "exact", "value": "^(a+)+$"}),
+ # Underscores at a segment boundary shift where the `__` separator falls once the
+ # segments are joined, so a lookup can reach Django without ever being a segment.
+ ("lookup_across_segment_boundary", "a_._regex", {"operation": "exact", "value": "^(a+)+$"}),
+ ("lookup_across_boundary_iregex", "name_._iregex", {"operation": "exact", "value": "^(a+)+$"}),
+ ("lookup_leading_segment", "regex_.a", {"operation": "exact", "value": "^(a+)+$"}),
+ ("array_nesting_fan_out", "a[].b[].c[].d[].e", {"operation": "exact", "value": "x"}),
+ ("non_object_filter_config", "name", "test"),
+ ]
+ )
+ def test_rejects_unsafe_detail_filters(self, _name: str, field_path: str, filter_config: Any) -> None:
+ filter_manager = AdvancedActivityLogFilterManager()
- def test_rejects_invalid_operations(self):
- log = self._create_activity_log({"name": "test"})
- queryset = ActivityLog.objects.filter(id=log.id)
+ with self.assertRaises(serializers.ValidationError):
+ filter_manager._apply_detail_filters(ActivityLog.objects.all(), {field_path: filter_config})
- filtered = self.filter_manager._apply_detail_filters(queryset, {"name": {"operation": "regex", "value": ".*"}})
- self.assertEqual(filtered.count(), 1)
+ # Only the lookups registered on JSONField and KeyTransform shadow a JSON key. Names that are
+ # transforms on some *other* field type -- `date` and `day` come from DateField -- reach Postgres
+ # as `detail -> 'date'`, so widening the reserved set past those two registries would start
+ # rejecting ordinary detail keys.
+ @parameterized.expand(
+ [
+ ("date_transform_name", "date"),
+ ("day_transform_name", "day"),
+ ("nested_array_path", "changes[].after.date"),
+ ("single_underscore_segment", "context.trigger_name"),
+ ]
+ )
+ def test_accepts_detail_filter_paths_that_are_not_json_lookups(self, _name: str, field_path: str) -> None:
+ detail_filters = {field_path: {"operation": "exact", "value": "x"}}
- filtered = self.filter_manager._apply_detail_filters(queryset, {"name": {"operation": "gt", "value": "a"}})
- self.assertEqual(filtered.count(), 1)
+ self.assertEqual(validate_detail_filters(detail_filters), detail_filters)
class TestIpAddressFilter(BaseTest):
@@ -313,6 +334,14 @@ class TestAdvancedActivityLogFiltersSerializerValidation(SimpleTestCase):
serializer = AdvancedActivityLogFiltersSerializer(data=query)
self.assertEqual(serializer.is_valid(), expected, serializer.errors)
+ def test_serializer_rejects_unsafe_detail_filter_paths(self) -> None:
+ query = QueryDict(mutable=True)
+ query["detail_filters"] = json.dumps({"name.regex": {"operation": "exact", "value": "^(a+)+$"}})
+ serializer = AdvancedActivityLogFiltersSerializer(data=query)
+
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("detail_filters", serializer.errors)
+
class TestTypeConversionIntegration(BaseTest):
def setUp(self):
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index 5228c7feac93..fc973441e145 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -35,7 +35,7 @@ from posthog.tasks import exporter
from products.exports.backend.models.exported_asset import ExportedAsset
from .field_discovery import AdvancedActivityLogFieldDiscovery
-from .filters import AdvancedActivityLogFilterManager
+from .filters import AdvancedActivityLogFilterManager, validate_detail_filters
from .utils import get_activity_log_lookback_restriction
@@ -358,6 +358,9 @@ class AdvancedActivityLogFiltersSerializer(serializers.Serializer):
help_text="Number of results per page (default: 100, max: 1000). Only used with page-based pagination.",
)
+ def validate_detail_filters(self, value: Any) -> dict[str, Any]:
+ return validate_detail_filters(value)
+
class ActivityLogFlatExportSerializer(serializers.ModelSerializer):
organization_id = serializers.UUIDField()