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(conversations): truncate oversized widget session context (#73109)

Christiaan Hendriksen7fa9377c2420
diff --git a/products/conversations/backend/api/serializers.py b/products/conversations/backend/api/serializers.py
index bd0053ecc898..a047c79b44af 100644
--- a/products/conversations/backend/api/serializers.py
+++ b/products/conversations/backend/api/serializers.py
@@ -1,5 +1,6 @@
"""Serializers for Conversations API."""
+from typing import Any
from urllib.parse import urlparse
from drf_spectacular.utils import extend_schema_field
@@ -70,6 +71,48 @@ class WidgetAuthSerializer(serializers.Serializer):
return data
+def _sanitize_context(
+ value: dict[str, Any],
+ *,
+ max_entries: int,
+ max_key_length: int,
+ max_value_length: int,
+ coerce_to_string: bool = False,
+) -> dict[str, Any]:
+ """Bound widget-attached context by truncating and skipping rather than raising.
+
+ The widget attaches this context itself, so the person filing a ticket can't shorten the
+ page URL it captured: a validation error here costs them the ticket rather than prompting
+ them to fix anything. Over-long values are therefore sliced to the cap, matching how
+ posthog-js handles over-long string properties, and unusable keys and excess entries are
+ skipped for the same reason.
+
+ Entries past max_entries are skipped in iteration order, so a client sending more than
+ that keeps whichever entries it serialized first.
+ """
+ sanitized: dict[str, Any] = {}
+ for key, val in value.items():
+ if len(sanitized) >= max_entries:
+ break
+
+ if not isinstance(key, str) or len(key) > max_key_length:
+ continue
+
+ # Simple types only for MVP
+ if not isinstance(val, str | int | float | bool | type(None)):
+ continue
+
+ if coerce_to_string and val is not None:
+ val = str(val)
+
+ if isinstance(val, str):
+ val = val[:max_value_length]
+
+ sanitized[key] = val
+
+ return sanitized
+
+
class WidgetMessageSerializer(WidgetAuthSerializer):
"""Serializer for incoming widget messages."""
@@ -97,60 +140,22 @@ class WidgetMessageSerializer(WidgetAuthSerializer):
raise serializers.ValidationError("Message content is required")
return value.strip()
- def validate_traits(self, value):
- if not isinstance(value, dict):
- raise serializers.ValidationError("traits must be a dictionary")
-
- if len(value) > 50:
- raise serializers.ValidationError(f"Too many traits: {len(value)} (max 50)")
-
- validated = {}
- for key, val in value.items():
- # Validate key is a string with reasonable length
- if not isinstance(key, str):
- continue
- if len(key) > 200:
- raise serializers.ValidationError(f"Trait key too long: '{key[:50]}...' (max 200 chars)")
-
- # Only allow simple types for MVP
- if not isinstance(val, str | int | float | bool | type(None)):
- continue
-
- # Convert to string and validate length
- str_value = str(val) if val is not None else None
- if str_value and len(str_value) > 500:
- raise serializers.ValidationError(f"Trait value too long for '{key}' (max 500 chars)")
-
- validated[key] = str_value
-
- return validated
-
- def validate_session_context(self, value):
- if not isinstance(value, dict):
- raise serializers.ValidationError("session_context must be a dictionary")
-
- if len(value) > 20:
- raise serializers.ValidationError(f"Too many session context fields: {len(value)} (max 20)")
-
- validated = {}
- for key, val in value.items():
- # Validate key
- if not isinstance(key, str):
- continue
- if len(key) > 100:
- raise serializers.ValidationError(f"Session context key too long: '{key[:50]}...' (max 100 chars)")
-
- # Allow simple types and validate length
- if not isinstance(val, str | int | float | bool | type(None)):
- continue
-
- # Validate string length for string values
- if isinstance(val, str) and len(val) > 2000: # URLs can be long
- raise serializers.ValidationError(f"Session context value too long for '{key}' (max 2000 chars)")
-
- validated[key] = val
-
- return validated
+ def validate_traits(self, value: dict[str, Any]) -> dict[str, Any]:
+ return _sanitize_context(
+ value,
+ max_entries=50,
+ max_key_length=200,
+ max_value_length=500,
+ coerce_to_string=True,
+ )
+
+ def validate_session_context(self, value: dict[str, Any]) -> dict[str, Any]:
+ return _sanitize_context(
+ value,
+ max_entries=20,
+ max_key_length=100,
+ max_value_length=2000, # URLs can be long
+ )
class WidgetMessagesQuerySerializer(WidgetAuthSerializer):
diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.py
index 5f5240404c64..18c656654775 100644
--- a/products/conversations/backend/api/tests/test_widget.py
+++ b/products/conversations/backend/api/tests/test_widget.py
@@ -3,11 +3,15 @@ import uuid
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
from posthog.models.comment import Comment
+from products.conversations.backend.api.serializers import WidgetMessageSerializer
from products.conversations.backend.models import Ticket
from products.conversations.backend.models.constants import ChannelDetail, Status
from products.conversations.backend.services.identity import compute_identity_hash
@@ -542,6 +546,22 @@ class TestWidgetAPI(BaseTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ def test_long_current_url_is_truncated_not_rejected(self):
+ long_url = "https://app.example.com/insights?q=" + "x" * 3000
+ response = self.client.post(
+ "/api/conversations/v1/widget/message",
+ {
+ "message": "Hello",
+ "widget_session_id": self.widget_session_id,
+ "distinct_id": self.distinct_id,
+ "session_context": {"current_url": long_url},
+ },
+ **self._get_headers(),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ticket = Ticket.objects.get(id=response.json()["ticket_id"])
+ self.assertEqual(ticket.session_context["current_url"], long_url[:2000])
+
class TestWidgetCacheInvalidation(BaseTest):
"""Test that widget message creation invalidates unread count cache."""
@@ -914,3 +934,81 @@ class TestWidgetIdentityVerification(BaseTest):
**self._get_headers(),
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+
+class TestWidgetContextSanitization(SimpleTestCase):
+ def _serializer(self, **overrides):
+ return WidgetMessageSerializer(
+ data={
+ "widget_session_id": str(uuid.uuid4()),
+ "distinct_id": "user-123",
+ "message": "Hello",
+ **overrides,
+ }
+ )
+
+ def _validated(self, **overrides):
+ serializer = self._serializer(**overrides)
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ return serializer.validated_data
+
+ @parameterized.expand(
+ [
+ ("session_context", "current_url", 2000),
+ ("traits", "name", 500),
+ ]
+ )
+ def test_oversized_value_is_truncated(self, field, key, max_length):
+ value = "x" * (max_length + 500)
+
+ validated = self._validated(**{field: {key: value}})
+
+ self.assertEqual(validated[field][key], value[:max_length])
+
+ @parameterized.expand(
+ [
+ ("session_context", 20, 100),
+ ("traits", 50, 200),
+ ]
+ )
+ def test_long_keys_and_excess_entries_are_dropped(self, field, max_entries, max_key_length):
+ long_key = "k" * (max_key_length + 1)
+ payload = {long_key: "value", **{f"key_{i}": "value" for i in range(max_entries + 5)}}
+
+ validated = self._validated(**{field: payload})
+
+ self.assertNotIn(long_key, validated[field])
+ self.assertEqual(len(validated[field]), max_entries)
+
+ @parameterized.expand(
+ [
+ (
+ "session_context",
+ {"tab_index": 3, "is_replay": True, "referrer": None},
+ {"tab_index": 3, "is_replay": True, "referrer": None},
+ ),
+ (
+ "traits",
+ {"plan_seats": 3, "is_admin": True, "email": None},
+ {"plan_seats": "3", "is_admin": "True", "email": None},
+ ),
+ ]
+ )
+ def test_non_string_values_are_coerced_per_field(self, field, payload, expected):
+ validated = self._validated(**{field: payload})
+
+ self.assertEqual(validated[field], expected)
+
+ @parameterized.expand(
+ [
+ ("session_context", "not-a-dict"),
+ ("session_context", None),
+ ("traits", "not-a-dict"),
+ ("traits", None),
+ ]
+ )
+ def test_structurally_malformed_context_is_still_rejected(self, field, value):
+ serializer = self._serializer(**{field: value})
+
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(field, serializer.errors)